Mojo struct
IntTuple
struct IntTuple
A hierarchical, nested tuple of integers with efficient memory management.
IntTuple provides a flexible data structure for representing multi-dimensional shapes, indices, and other nested integer collections. It supports both flat and hierarchical representations with efficient memory sharing.
This structure is fundamental for tensor operations, layout specifications, and dimension handling in high-performance computing contexts.
Implemented traitsβ
AnyType,
Copyable,
Defaultable,
EqualityComparable,
ImplicitlyCopyable,
Intable,
Iterable,
Movable,
Sized,
Stringable,
UnknownDestructibility,
Writable
Aliasesβ
__copyinit__is_trivialβ
comptime __copyinit__is_trivial = False
__del__is_trivialβ
comptime __del__is_trivial = False
__moveinit__is_trivialβ
comptime __moveinit__is_trivial = True
IteratorTypeβ
comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[iterable_mut]] = _IntTupleIter[origin_of((muttoimm iterable_origin._mlir_origin))]
Parametersβ
MinimumValueβ
comptime MinimumValue = -65534
Minimum allowed value for integers in an IntTuple.
This constant defines the lower bound for integer values that can be stored
directly in an IntTuple. Values below this threshold are reserved for internal
use to represent structural information like sub-tuple offsets.
Methodsβ
__init__β
__init__(out self)
Initialize an empty IntTuple.
Creates an IntTuple with zero elements, which can be used as a starting
point for building tuples incrementally with append or extend.
Performance:
- Minimal allocation (just a single element for length).
- Structure validation only performed when
INT_TUPLE_VALIDATIONis enabled.
__init__(out self, *, num_elems: Int)
Initialize an IntTuple with a specified number of uninitialized elements.
Creates an IntTuple with space for the specified number of elements,
but does not initialize the elements themselves.
Note:
Structure validation only performed when INT_TUPLE_VALIDATION is enabled.
Args:
- βnum_elems (
Int): The number of elements to allocate space for.
__init__(out self, *elements: Int)
Initialize an IntTuple with a variadic list of integers.
Creates an IntTuple containing the provided integer values.
Args:
- β*elements (
Int): Variable number of integer values to store in the tuple.
__init__(out self, elements: VariadicList[Int])
Initialize an IntTuple with a list of integers.
Creates an IntTuple containing the provided integer values.
Notes:
- Pre-allocates exact memory needed for efficiency.
- Validates that all values are above
MinimumValue. If any value is less thanMinimumValue, aborts with an error message. - Structure validation only performed when
INT_TUPLE_VALIDATIONis enabled.
Args:
- βelements (
VariadicList): List of integer values to store in the tuple.
@implicit
__init__(out self, value: Int)
Initialize an IntTuple with a single integer value.
Creates an IntTuple containing a single integer element.
Args:
- βvalue (
Int): The integer value to store in the tuple.
__init__(out self, *elements: Self, *, __list_literal__: Tuple[] = Tuple[]())
Initialize an IntTuple with nested IntTuples.
Creates a hierarchical IntTuple containing the provided IntTuple elements,
preserving their nested structure.
Args:
- β*elements (
Self): Variable number ofIntTuplevalues to store in the tuple. - βlist_literal (
Tuple): Specifies that this constructor can be used for list literals.
__init__(out self, *, var _owned: IntArray)
Initialize an IntTuple taking the values of an IntArray.
Args:
- β_owned (
IntArray): TheIntArrayto use as storage.
__init__(out self, existing: Self, rng: _StridedRange)
Initialize an IntTuple as a slice of an existing IntTuple.
Creates a new IntTuple containing only the elements from the existing
IntTuple that are specified by the range.
Notes:
- Preserves nested structure of elements in the slice.
- Structure validation only performed when
INT_TUPLE_VALIDATIONis enabled.
Args:
- βexisting (
Self): The sourceIntTupleto slice from. - βrng (
_StridedRange): The range of indices to include in the newIntTuple.
__init__(out self, dimlist: DimList)
Initialize an IntTuple from a DimList.
Creates an IntTuple containing the dimensions from a DimList, handling
both defined and undefined dimensions appropriately.
Notes:
- Converts undefined dimensions to
UNKNOWN_VALUE. - Validates that all values are above
MinimumValue. If any value is less thanMinimumValue, aborts with an error message.
Args:
- βdimlist (
DimList): The DimList containing dimension information.
__init__[IterableType: Iterable](out self, iterable: IterableType)
Initialize an IntTuple from a zip iterator.
Creates an IntTuple by appending each element from the zip iterator.
Note: This implementation is not optimized and may be improved in future versions.
Parameters:
- βIterableType (
Iterable): The type of the iterable.
Args:
- βiterable (
IterableType): An iterable containing pairs of elements to append.
__copyinit__β
__copyinit__(out self, existing: Self)
Initialize by copying an existing IntTuple.
Creates a deep copy of the provided IntTuple, copying all its data
into newly allocated memory.
Note: There is a Mojo bug where this method unnecessarily propagates the origin of self to the new copy.
Args:
- βexisting (
Self): TheIntTupleto copy from.
__getitem__β
__getitem__(self, _idx: Int) -> Self
Retrieves an element at the specified index from the IntTuple.
Supports negative indexing (e.g., -1 for the last element).
Notes: If index validation is enabled and the index is out of bounds, aborts with an error message.
Args:
- β_idx (
Int): The index of the element to retrieve.
Returns:
Self: An IntTuple containing either a single value or a sub-tuple.
__getitem__(self, span: Slice) -> Self
Retrieves a slice of elements from the IntTuple.
Creates a new IntTuple containing the elements specified by the slice.
Args:
- βspan (
Slice): A slice object specifying the range of elements to retrieve.
Returns:
Self: A new IntTuple containing the specified elements.
__lt__β
__lt__(self, rhs: Self) -> Bool
Compare two IntTuples lexicographically.
This function performs element-wise comparison of two IntTuples and determines
if the first is lexicographically less than the second. It compares corresponding
elements until it finds a pair where the elements differ.
Example:
from layout.int_tuple import IntTuple
var tuple1 = IntTuple(1, 2, 3)
var tuple2 = IntTuple(1, 2, 4)
var result = tuple1 < tuple2 # Returns True because 3 < 4Args:
- βrhs (
Self): The otherIntTupleto compare.
Returns:
Bool: True if self is lexicographically less than rhs, False otherwise.
__eq__β
__eq__(self, other: Self) -> Bool
Equality operator for IntTuple.
Args:
- βother (
Self): TheIntTupleto compare with.
Returns:
Bool: True if the IntTuples are equal, False otherwise.
__ne__β
__ne__(self, other: Self) -> Bool
Inequality operator for IntTuple.
Args:
- βother (
Self): TheIntTupleto compare with.
Returns:
Bool: True if the IntTuples are not equal, False otherwise.
elements_sizeβ
static elements_size(elements: VariadicListMem[IntTuple, origin, is_owned]) -> Int
Calculate the total storage size needed for a list of IntTuples.
Computes the sum of sizes for all elements, accounting for both direct integer values and nested sub-tuples.
Args:
- βelements (
VariadicListMem): List ofIntTupleelements to measure.
Returns:
Int: The total storage size required for all elements.
static elements_size[_origin: ImmutOrigin, n: Int](elements: InlineArray[Pointer[IntTuple, _origin], n], idx: Int) -> Int
Calculate the total storage size needed for IntTuples at a specific index.
Computes the sum of sizes for all elements at the given index in an array
of IntTuple pointers.
Parameters:
- β_origin (
ImmutOrigin): Origin tracking for memory safety. - βn (
Int): Size of the inline array.
Args:
- βelements (
InlineArray): Array of pointers toIntTuples. - βidx (
Int): Index to access in eachIntTuple.
Returns:
Int: The total storage size required for all elements at the specified index.
owned_copyβ
owned_copy(self) -> Self
Create a deep copy of this IntTuple with its own memory ownership.
This method creates a completely independent copy of the IntTuple with
newly allocated memory. Unlike __copyinit__, this method can be called
on an existing instance to create a separate copy.
Example:
from layout import IntTuple
var original = IntTuple(1, 2, 3)
var copy = original.owned_copy()
# Modifying copy will not affect originalReturns:
Self: A new IntTuple containing the same data as this one but with
independent memory ownership.
replace_entryβ
replace_entry(self, idx: Int, value: Self) -> Self
Replace an entry in the tuple with another IntTuple.
Creates a new IntTuple with the element at the specified index replaced
by the provided IntTuple.
Note:
If the index is out of bounds and INT_TUPLE_VALIDATION is enabled,
aborts with an error message.
Args:
- βidx (
Int): The index of the element to replace. - βvalue (
Self): TheIntTupleto insert at the specified index.
Returns:
Self: A new IntTuple with the replacement applied.
replace_entry(mut self, idx: Int, *, int_value: Int)
Replace an integer value at the specified index in-place.
Directly modifies the tuple by replacing the integer value at the given index. This is more efficient than creating a new tuple when only a single value needs to be changed.
Note:
If the index is out of bounds and INT_TUPLE_VALIDATION is enabled,
aborts with an error message.
Args:
count_valuesβ
count_values(self) -> Int
Count the total number of integer values in this tuple hierarchy.
Recursively traverses the nested tuple structure and counts all integer values. This is useful for determining the size needed for flattened representations.
Note:
For a flat tuple, this will return the same value as len(self).
For nested tuples, it counts all leaf integer values.
Returns:
Int: The total count of integer values in this tuple and all nested tuples.
flattenβ
flatten(self) -> Self
Flatten a nested IntTuple into a single-level IntTuple.
This function converts a hierarchical IntTuple structure into a flat
sequence of integer values, preserving the order of elements.
Returns:
Self: A new IntTuple containing all integer values in a flat structure.
product_flattenβ
product_flatten(self) -> Self
Coalesces a nested IntTuple into a single-level IntTuple, by multiplying all the values together.
Returns:
Self: A new IntTuple containing the products of each top level tuple, in a flat structure.
all_knownβ
all_known(self) -> Bool
Check if all values in this tuple hierarchy are known (not UNKNOWN_VALUE).
Recursively traverses the nested tuple structure and checks if any value
is equal to UNKNOWN_VALUE.
Returns:
Bool: True if all values in this tuple and nested tuples are known,
False if any value is UNKNOWN_VALUE.
all_known[start: Int, end: Int](self) -> Bool
Check if all values in this tuple hierarchy are known (not UNKNOWN_VALUE).
Recursively traverses the nested tuple structure and checks if any value
is equal to UNKNOWN_VALUE.
Parameters:
- βstart (
Int): The starting index (inclusive) for the range to check. - βend (
Int): The ending index (exclusive) for the range to check.
Returns:
Bool: True if all values in this tuple and nested tuples are known,
False if any value is UNKNOWN_VALUE.
appendβ
append(mut self, *elements: Self)
Append one or more IntTuple elements to this tuple.
This method modifies the tuple in-place by adding the provided elements to the end of the tuple. It handles both value tuples and nested tuples.
Notes:
- This operation requires reallocating the underlying
IntArraystorage to accommodate the new elements, which may impact performance for large tuples.
Args:
- β*elements (
Self): Variable number ofIntTupleobjects to append to this tuple.
extendβ
extend(mut self, tuple: Self)
Extends this tuple by appending all elements from another tuple.
This method modifies the tuple in-place by adding all elements from the provided tuple to the end of this tuple. It efficiently handles both value elements and nested tuples.
Notes:
- This operation requires reallocating the underlying
IntArraystorage to accommodate the new elements, which may impact performance for large tuples. - If the input tuple is empty, this method returns without making any changes.
Args:
- βtuple (
Self): TheIntTuplewhose elements will be appended to this tuple.
sizeβ
size(self) -> Int
Returns the total size of the IntTuple in memory.
For owning tuples, returns the size of the underlying IntArray.
Returns:
Int: The total size in memory units.
tuple_sizeβ
static tuple_size(data: IntArray) -> Int
Recursively calculates the size of a tuple represented by an IntArray.
This method traverses the tuple structure, accounting for both direct values and nested sub-tuples to compute the total memory footprint.
Args:
- βdata (
IntArray):IntArraycontaining the tuple data.
Returns:
Int: The total size of the tuple in memory units.
validate_structureβ
validate_structure(self)
Validates the internal structure of the IntTuple.
Ensures that the actual size of the underlying data matches the computed size based on the tuple's structure. This helps detect memory corruption or implementation errors.
Aborts execution with an error message if validation fails.
__len__β
__len__(self) -> Int
Returns the number of elements in the IntTuple.
This is the logical length of the tuple, not its memory size.
Returns:
Int: The number of elements in the tuple.
__iter__β
__iter__(ref self) -> _IntTupleIter[origin_of((muttoimm self_is_origin))]
Returns an iterator over the elements of the IntTuple.
This enables iteration through the tuple using for-loops.
Returns:
_IntTupleIter: An iterator object for this IntTuple.
is_valueβ
is_value(self) -> Bool
Determines if this IntTuple represents a single value rather than a tuple.
Returns:
Bool: True if this IntTuple contains exactly one element that is a value,
False otherwise.
is_value(self, i: Int) -> Bool
Determines if the element at the specified index is a value rather than a tuple.
Notes: If index validation is enabled and the index is out of bounds, aborts with an error message.
Args:
- βi (
Int): The index of the element to check.
Returns:
Bool: True if the element at index i is a value, False if it's a tuple.
is_tupleβ
is_tuple(self) -> Bool
Determines if this IntTuple represents a tuple rather than a single value.
Returns:
Bool: True if this IntTuple is a tuple (not a single value), False otherwise.
is_tuple(self, i: Int) -> Bool
Determines if the element at the specified index is a tuple rather than a value.
Notes: This is the complement of is_value(i).
Args:
- βi (
Int): The index of the element to check.
Returns:
Bool: True if the element at index i is a tuple, False if it's a value.
valueβ
value(self) -> Int
Retrieves the value of this IntTuple if it represents a single value.
This method should only be called if is_value() returns True.
Returns:
Int: The integer value stored in this IntTuple.
value(self, i: Int) -> Int
Retrieves the value of the element at the specified index.
This method should only be called if is_value(i) returns True.
Notes: If the element is not a value, the behavior is undefined.
Args:
- βi (
Int): The index of the element to retrieve.
Returns:
Int: The integer value stored at the specified index.
tupleβ
tuple(ref self) -> ref [self] Self
Returns a reference to this IntTuple as a tuple.
Notes:
This method is used to access the current IntTuple as a tuple
without creating a copy of the data.
Returns:
ref: A reference to this IntTuple to avoid unnecessary copying.
write_toβ
write_to(self, mut writer: T)
Writes a string representation of this IntTuple to the provided writer.
Notes: For single values, writes just the value. For tuples, writes a comma-separated list of elements enclosed in parentheses.
Args:
- βwriter (
T): The writer to output the string representation to.
__str__β
__str__(self) -> String
Returns a string representation of this IntTuple.
Returns:
String: A string representation of the IntTuple, using the write_to method.
is_equalβ
static is_equal(a, b: Self) -> Bool
Compares two IntTuples for equality.
Notes: Handles nested tuples and special cases where a single-element tuple is equivalent to its contained value.
Args:
- βa (
Self): The firstIntTupleto compare. - βb (
Self): The secondIntTupleto compare.
Returns:
Bool: True if the IntTuples are equal in structure and values, False otherwise.
__repr__β
__repr__(self) -> String
Returns a string representation of this IntTuple for debugging.
Returns:
String: A string representation of the IntTuple, same as __str__.
__int__β
__int__(self) -> Int
Converts this IntTuple to an integer.
This method should only be called if is_value() returns True.
Aborts:
If the IntTuple is not a single value.
Returns:
Int: The integer value stored in this IntTuple.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!