Mojo struct
Span
@register_passable(trivial)
struct Span[mut: Bool, //, T: Copyable & Movable, origin: Origin[mut], *, address_space: AddressSpace = AddressSpace.GENERIC]
A non-owning view of contiguous data.
Parameters
- mut (
Bool): Whether the span is mutable. - T (
Copyable&Movable): The type of the elements in the span. - origin (
Origin): The origin of the Span. - address_space (
AddressSpace): The address space associated with the allocated memory.
Implemented traits
AnyType,
Boolable,
Copyable,
Defaultable,
DevicePassable,
ImplicitlyCopyable,
Movable,
Sized,
UnknownDestructibility
Aliases
__copyinit__is_trivial
alias __copyinit__is_trivial = True
__del__is_trivial
alias __del__is_trivial = True
__moveinit__is_trivial
alias __moveinit__is_trivial = True
device_type
alias device_type = Span[T, origin, address_space=address_space]
Immutable
alias Immutable = Span[T, origin_of((muttoimm origin._mlir_origin))]
The immutable version of the Span.
Mutable
alias Mutable = Span[T, origin_of((mutcast origin._mlir_origin))]
The mutable version of the Span.
UnsafePointerType
alias UnsafePointerType = LegacyUnsafePointer[T, address_space=address_space, mut=mut, origin=origin]
The UnsafePointer type that corresponds to this Span.
Methods
__init__
__init__() -> Self
Create an empty / zero-length span.
__init__(*, ptr: LegacyUnsafePointer[T, address_space=address_space, mut=mut, origin=origin], length: Int) -> Self
Unsafe construction from a pointer and length.
Args:
- ptr (
LegacyUnsafePointer): The underlying pointer of the span. - length (
Int): The length of the view.
@implicit
__init__(ref [origin, address_space] list: List[T]) -> Self
Construct a Span from a List.
Args:
- list (
List): The list to which the span refers.
@implicit
__init__[size: Int, //](ref [origin] array: InlineArray[T, size]) -> Self
Construct a Span from an InlineArray.
Parameters:
- size (
Int): The size of theInlineArray.
Args:
- array (
InlineArray): The array to which the span refers.
__bool__
__bool__(self) -> Bool
Check if a span is non-empty.
Returns:
Bool: True if a span is non-empty, False otherwise.
__getitem__
__getitem__[I: Indexer](self, idx: I) -> ref [origin, address_space] T
Get a reference to an element in the span.
Parameters:
- I (
Indexer): A type that can be used as an index.
Args:
- idx (
I): The index of the value to return.
Returns:
ref: An element reference.
__getitem__(self, slc: Slice) -> Self
Get a new span from a slice of the current span.
Allocation: This function allocates when the step is negative, to avoid a memory leak, take ownership of the value.
Args:
- slc (
Slice): The slice specifying the range of the new subslice.
Returns:
Self: A new span that points to the same data as the current span.
__eq__
__eq__[_T: EqualityComparable & Copyable & Movable, //](self: Span[_T, origin], rhs: Span[_T, origin]) -> Bool
Verify if span is equal to another span.
Parameters:
- _T (
EqualityComparable&Copyable&Movable): The type of the elements must implement the traitsEqualityComparable,CopyableandMovable.
Args:
- rhs (
Span): The span to compare against.
Returns:
Bool: True if the spans are equal in length and contain the same elements, False otherwise.
__ne__
__ne__[_T: EqualityComparable & Copyable & Movable, //](self: Span[_T, origin], rhs: Span[_T, origin]) -> Bool
Verify if span is not equal to another span.
Parameters:
- _T (
EqualityComparable&Copyable&Movable): The type of the elements in the span. Must implement the traitsEqualityComparable,CopyableandMovable.
Args:
- rhs (
Span): The span to compare against.
Returns:
Bool: True if the spans are not equal in length or contents, False otherwise.
__contains__
__contains__[dtype: DType, //](self: Span[Scalar[dtype], origin, address_space=address_space], value: Scalar[dtype]) -> Bool
Verify if a given value is present in the Span.
Parameters:
- dtype (
DType): The DType of the scalars stored in the Span.
Args:
- value (
Scalar): The value to find.
Returns:
Bool: True if the value is contained in the list, False otherwise.
get_type_name
static get_type_name() -> String
Gets this type's name, for use in error messages when handing arguments to kernels.
Returns:
String: This type's name.
get_device_type_name
static get_device_type_name() -> String
Gets device_type's name, for use in error messages when handing arguments to kernels.
Returns:
String: This type's name.
__iter__
__iter__(self) -> _SpanIter[T, origin, address_space=address_space]
Get an iterator over the elements of the Span.
Returns:
_SpanIter: An iterator over the elements of the Span.
__reversed__
__reversed__(self) -> _SpanIter[T, origin, False, address_space]
Iterate backwards over the Span.
Returns:
_SpanIter: A reversed iterator of the Span elements.
__len__
__len__(self) -> Int
Returns the length of the span. This is a known constant value.
Returns:
Int: The size of the span.
__str__
__str__[U: Representable & Copyable & Movable, //](self: Span[U, origin]) -> String
Returns a string representation of a Span.
Notes: Note that since we can't condition methods on a trait yet, the way to call this method is a bit special. Here is an example below:
var my_list = [1, 2, 3]
var my_span = Span(my_list)
print(my_span.__str__())When the compiler supports conditional methods, then a simple
String(my_span) will be enough.
Parameters:
- U (
Representable&Copyable&Movable): The type of the elements in the span. Must implement the traitRepresentable.
Returns:
String: A string representation of the span.
write_to
write_to[U: Representable & Copyable & Movable, //](self: Span[U, origin], mut writer: T)
Write my_span.__str__() to a Writer.
Parameters:
- U (
Representable&Copyable&Movable): The type of the Span elements. Must have the traitRepresentable.
Args:
- writer (
T): The object to write to.
__repr__
__repr__[U: Representable & Copyable & Movable, //](self: Span[U, origin]) -> String
Returns a string representation of a Span.
Notes: Note that since we can't condition methods on a trait yet, the way to call this method is a bit special. Here is an example below:
var my_list = [1, 2, 3]
var my_span = Span(my_list)
print(my_span.__repr__())When the compiler supports conditional methods, then a simple
repr(my_span) will be enough.
Parameters:
- U (
Representable&Copyable&Movable): The type of the elements in the span. Must implement the traitRepresentable.
Returns:
String: A string representation of the span.
get_immutable
get_immutable(self) -> Span[T, origin_of((muttoimm origin._mlir_origin))]
Return an immutable version of this Span.
Returns:
Span: An immutable version of the same Span.
unsafe_get
unsafe_get(self, idx: T) -> ref [origin, address_space] T
Get a reference to the element at index without bounds checking.
Safety:
- This function does not do bounds checking and assumes the provided index is in: [0, len(self)). Not upholding this contract will result in undefined behavior.
- This function does not support wraparound for negative indices.
Args:
- idx (
T): The index of the element to get.
Returns:
ref: A reference to the element at the specified index.
unsafe_ptr
unsafe_ptr(self) -> LegacyUnsafePointer[T, address_space=address_space, mut=mut, origin=origin]
Retrieves a pointer to the underlying memory.
Returns:
LegacyUnsafePointer: The pointer to the underlying memory.
as_ref
as_ref(self) -> Pointer[T, origin, address_space]
Gets a Pointer to the first element of this span.
Returns:
Pointer: A Pointer pointing at the first element of this span.
copy_from
copy_from[_origin: MutOrigin, //](self: Span[T, _origin], other: Span[T, origin])
Performs an element wise copy from all elements of other into all elements of self.
Parameters:
- _origin (
MutOrigin): The inferred mutable origin of the data within the Span.
Args:
- other (
Span): TheSpanto copy all elements from.
fill
fill[_origin: MutOrigin, //](self: Span[T, _origin], value: T)
Fill the memory that a span references with a given value.
Parameters:
- _origin (
MutOrigin): The inferred mutable origin of the data within the Span.
Args:
- value (
T): The value to assign to each element.
unsafe_swap_elements
unsafe_swap_elements(self: Span[T, origin], a: Int, b: Int)
Swap the values at indices a and b without performing bounds checking.
Safety:
- Both
aandbmust be in: [0, len(self)).
Args:
swap_elements
swap_elements(self: Span[T, origin], a: Int, b: Int)
Swap the values at indices a and b.
Args:
Raises:
If a or b are larger than the length of the span.
__merge_with__
__merge_with__[other_type: AnyStruct[Span[T, origin, address_space=address_space]]](self) -> Span[T, origin_of((mutcast origin._mlir_origin), (mutcast origin._mlir_origin)), address_space=address_space]
Returns a pointer merged with the specified other_type.
Parameters:
- other_type (
AnyStruct): The type of the pointer to merge with.
Returns:
Span: A pointer merged with the specified other_type.
reverse
reverse[dtype: DType, O: MutOrigin, //](self: Span[Scalar[dtype], O])
Reverse the elements of the Span inplace.
Parameters:
apply
apply[dtype: DType, O: MutOrigin, //, func: fn[w: Int](SIMD[dtype, w]) capturing -> SIMD[dtype, w]](self: Span[Scalar[dtype], O])
Apply the function to the Span inplace.
Parameters:
apply[dtype: DType, O: MutOrigin, //, func: fn[w: Int](SIMD[dtype, w]) capturing -> SIMD[dtype, w], *, cond: fn[w: Int](SIMD[dtype, w]) capturing -> SIMD[bool, w]](self: Span[Scalar[dtype], O])
Apply the function to the Span inplace where the condition is True.
Parameters:
count
count[dtype: DType, //, func: fn[w: Int](SIMD[dtype, w]) capturing -> SIMD[bool, w]](self: Span[Scalar[dtype], origin]) -> UInt
Count the amount of times the function returns True.
Parameters:
- dtype (
DType): The DType. - func (
fn[w: Int](SIMD[dtype, w]) capturing -> SIMD[bool, w]): The function to evaluate.
Returns:
UInt: The amount of times the function returns True.
unsafe_subspan
unsafe_subspan(self, *, offset: Int, length: Int) -> Self
Returns a subspan of the current span.
Safety: This function does not do bounds checking and assumes the current span contains the specified subspan.
Args:
- offset (
Int): The starting offset of the subspan (self._data + offset). - length (
Int): The length of the new subspan.
Returns:
Self: A new span representing the specified subspan.
binary_search_by
binary_search_by[func: fn(T) -> Int](self: Span[T, origin]) -> Optional[Int]
Finds an element using binary search with a custom comparison function.
The comparison function should return:
- A negative value if the element is less than the target
- Zero if the element matches the target
- A positive value if the element is greater than the target
Notes:
This function assumes that self is sorted according to the ordering
defined by func. If not sorted, the result is unspecified.
Example:
var data: List[String] = ["a", "bb", "ccc"]
var span = Span(data)
# Search for "bb"
fn cmp(elem: String) -> Int:
if elem < "bb":
return -1
elif elem > "bb":
return 1
else:
return 0
var index = span.binary_search_by[cmp]()
if index:
print("Found at index: ", index.value())
else:
print("Not found")Parameters:
- func (
fn(T) -> Int): A function that takes an element and returns an Int representing the comparison result.
Returns:
Optional: Returns the index of the matching element if found, None otherwise.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!