Skip to content

Instantly share code, notes, and snippets.

@lsh
Created April 4, 2024 06:04
Show Gist options
  • Save lsh/f47fb85015d4197522d9c614e2a0f7de to your computer and use it in GitHub Desktop.
Save lsh/f47fb85015d4197522d9c614e2a0f7de to your computer and use it in GitHub Desktop.
A `Bytes` type that can be an owned `List` or used with a `Buffer`
from buffer import Buffer
from utils.variant import Variant
from collections.list import List
@value
struct Bytes[mutability: __mlir_type.i1, lifetime: AnyLifetime[mutability].type](Sized):
alias Variant = Variant[List[Int8], Buffer[DType.int8]]
var variant: Self.Variant
fn __len__(self) -> Int:
if self.variant.isa[List[Int8]]():
return len(self.variant.get[List[Int8]]()[])
else:
return len(self.variant.get[Buffer[DType.int8]]()[])
fn __getitem__(self, index: Int) -> Int8:
if self.variant.isa[String]():
return self.variant.get[List[Int8]]()[][index]
else:
return self.variant.get[Buffer[DType.int8]]()[][index]
fn __setitem__(inout self, index: Int, value: Int8):
if self.variant.isa[String]():
self.variant.get[List[Int8]]()[][index] = value
else:
self.variant.get[Buffer[DType.int8]]()[][index] = value
fn main():
var input = String("Abcdefghijklmnop").as_bytes()
var buf = Buffer[DType.int8](
DTypePointer[DType.int8](input.data.bitcast[Int8]().value),
len(input),
)
var bytes = Bytes[__mlir_attr.`1: i1`, __lifetime_of(input)](buf)
for i in range(len(bytes)):
print(chr(bytes[i].to_int()), end="")
print()
bytes[0] = ord("a")
for i in range(len(bytes)):
print(chr(bytes[i].to_int()), end="")
print()
bytes = Bytes[__mlir_attr.`1: i1`, __lifetime_of(input)](input)
for i in range(len(bytes)):
print(chr(bytes[i].to_int()), end="")
print()
bytes[0] = ord("a")
for i in range(len(bytes)):
print(chr(bytes[i].to_int()), end="")
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment