Skip to content

Commit

Permalink
Move the Int.as_bytes() logic to SIMD, so we can call it with any sca…
Browse files Browse the repository at this point in the history
…lar type

Signed-off-by: Manuel Saelices <[email protected]>
  • Loading branch information
msaelices committed Dec 16, 2024
1 parent 776b4df commit 265b648
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 17 deletions.
17 changes: 1 addition & 16 deletions stdlib/src/builtin/int.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -1245,23 +1245,8 @@ struct Int(
Returns:
The byte array.
"""
alias type_len = D.sizeof()
var value = Scalar[D](self)

@parameter
if is_big_endian() and not big_endian:
value = byte_swap(value)
elif not is_big_endian() and big_endian:
value = byte_swap(value)

var ptr = UnsafePointer.address_of(value)
var list = List[Byte](capacity=type_len)

# TODO: Maybe this can be a List.extend(ptr, count) method
memcpy(list.unsafe_ptr(), ptr.bitcast[Byte](), type_len)
list.size = type_len

return list^
return value.as_bytes[big_endian]()

@always_inline("nodebug")
fn __mlir_index__(self) -> __mlir_type.index:
Expand Down
29 changes: 28 additions & 1 deletion stdlib/src/builtin/simd.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ from builtin.dtype import _uint_type_of_width
from builtin.format_int import _try_write_int
from builtin.io import _snprintf
from documentation import doc_private
from memory import UnsafePointer, bitcast, Span
from memory import UnsafePointer, bitcast, memcpy, Span

from utils import IndexList, StaticTuple
from utils._visualizers import lldb_formatter_wrapping_type
Expand Down Expand Up @@ -1910,6 +1910,33 @@ struct SIMD[type: DType, size: Int](
value = byte_swap(value)
return value

fn as_bytes[big_endian: Bool = False](self) -> List[Byte]:
"""Convert the integer to a byte array.
Parameters:
big_endian: Whether the byte array should be big-endian.
Returns:
The byte array.
"""
alias type_len = type.sizeof()
var value = self

@parameter
if is_big_endian() and not big_endian:
value = byte_swap(value)
elif not is_big_endian() and big_endian:
value = byte_swap(value)

var ptr = UnsafePointer.address_of(value)
var list = List[Byte](capacity=type_len)

# TODO: Maybe this can be a List.extend(ptr, count) method
memcpy(list.unsafe_ptr(), ptr.bitcast[Byte](), type_len)
list.size = type_len

return list^

fn _floor_ceil_trunc_impl[intrinsic: StringLiteral](self) -> Self:
constrained[
intrinsic == "llvm.floor"
Expand Down

0 comments on commit 265b648

Please sign in to comment.