content
stringlengths 32
91.6k
| path
stringlengths 14
91
| fimified
bool 2
classes |
---|---|---|
<filename>compact-dict/string_dict/ahasher.mojo
# This code is based on https://github.com/tkaitchuck/aHash
from bit import rotate_bits_left, byte_swap
alias U256 = SIMD[DType.uint64, 4]
alias U128 = SIMD[DType.uint64, 2]
alias MULTIPLE = 6364136223846793005
alias ROT = 23
@always_inline
fn folded_multiply(s: UInt64, by: UInt64) -> UInt64:
var b1 = s * byte_swap(by)
var b2 = byte_swap(s) * (~by)
return b1 ^ byte_swap(b2)
@always_inline
fn read_small(data: DTypePointer[DType.uint8], length: Int) -> U128:
if length >= 2:
if length >= 4:
# len 4-8
var a = data.bitcast[DType.uint32]().load().cast[DType.uint64]()
var b = data.offset(length - 4).bitcast[DType.uint32]().load().cast[DType.uint64]()
return U128(a, b)
else:
var a = data.bitcast[DType.uint16]().load().cast[DType.uint64]()
var b = data.offset(length - 1).load().cast[DType.uint64]()
return U128(a, b)
else:
if length > 0:
var a = data.load().cast[DType.uint64]()
return U128(a, a)
else:
return U128(0, 0)
struct AHasher:
var buffer: UInt64
var pad: UInt64
var extra_keys: U128
fn __init__(inout self, key: U256):
var pi_key = key ^ U256(0x243f_6a88_85a3_08d3, 0x1319_8a2e_0370_7344, 0xa409_3822_299f_31d0, 0x082e_fa98_ec4e_6c89,)
self.buffer = pi_key[0]
self.pad = pi_key[1]
self.extra_keys = U128(pi_key[2], pi_key[3])
@always_inline
fn update(inout self, new_data: UInt64):
self.buffer = folded_multiply(new_data ^ self.buffer, MULTIPLE)
@always_inline
fn large_update(inout self, new_data: U128):
var combined = folded_multiply(
new_data[0] ^ self.extra_keys[0], new_data[1] ^ self.extra_keys[1]
)
self.buffer = rotate_bits_left[ROT]((self.buffer + self.pad) ^ combined)
@always_inline
fn short_finish(self) -> UInt64:
return self.buffer + self.pad
@always_inline
fn finish(self) -> UInt64:
var rot = self.buffer & 63
var folded = folded_multiply(self.buffer, self.pad)
return (folded << rot) | (folded >> (64 - rot))
@always_inline
fn write(inout self, data: DTypePointer[DType.uint8], length: Int):
self.buffer = (self.buffer + length) * MULTIPLE
if length > 8:
if length > 16:
var tail = data.offset(length - 16).bitcast[DType.uint64]().load[width=2]()
self.large_update(tail)
var offset = 0
while length - offset > 16:
var block = data.offset(offset).bitcast[DType.uint64]().load[width=2]()
self.large_update(block)
offset += 16
else:
var a = data.bitcast[DType.uint64]().load()
var b = data.offset(length - 8).bitcast[DType.uint64]().load()
self.large_update(U128(a, b))
else:
var value = read_small(data, length)
self.large_update(value)
@always_inline
fn ahash(s: String) -> UInt64:
var length = len(s)
var b = s.unsafe_ptr()
var hasher = AHasher(U256(0, 0, 0, 0))
if length > 8:
hasher.write(b, length)
else:
var value = read_small(b, length)
hasher.buffer = folded_multiply(value[0] ^ hasher.buffer, value[1] ^ hasher.extra_keys[1])
hasher.pad = hasher.pad + length
return hasher.finish()
| compact-dict/string_dict/ahasher.mojo | false |
from bit import pop_count, bit_width
from memory import memset_zero, memcpy
from collections import List
from .string_eq import eq
from .keys_container import KeysContainer
from .ahasher import ahash
struct Dict[
V: CollectionElement,
hash: fn(String) -> UInt64 = ahash,
KeyCountType: DType = DType.uint32,
KeyOffsetType: DType = DType.uint32,
destructive: Bool = True,
caching_hashes: Bool = True,
](Sized):
var keys: KeysContainer[KeyOffsetType]
var key_hashes: DTypePointer[KeyCountType]
var values: List[V]
var slot_to_index: DTypePointer[KeyCountType]
var deleted_mask: DTypePointer[DType.uint8]
var count: Int
var capacity: Int
fn __init__(inout self, capacity: Int = 16):
constrained[
KeyCountType == DType.uint8 or
KeyCountType == DType.uint16 or
KeyCountType == DType.uint32 or
KeyCountType == DType.uint64,
"KeyCountType needs to be an unsigned integer"
]()
self.count = 0
if capacity <= 8:
self.capacity = 8
else:
var icapacity = Int64(capacity)
self.capacity = capacity if pop_count(icapacity) == 1 else
1 << int(bit_width(icapacity))
self.keys = KeysContainer[KeyOffsetType](capacity)
@parameter
if caching_hashes:
self.key_hashes = DTypePointer[KeyCountType].alloc(self.capacity)
else:
self.key_hashes = DTypePointer[KeyCountType].alloc(0)
self.values = List[V](capacity=capacity)
self.slot_to_index = DTypePointer[KeyCountType].alloc(self.capacity)
memset_zero(self.slot_to_index, self.capacity)
@parameter
if destructive:
self.deleted_mask = DTypePointer[DType.uint8].alloc(self.capacity >> 3)
memset_zero(self.deleted_mask, self.capacity >> 3)
else:
self.deleted_mask = DTypePointer[DType.uint8].alloc(0)
fn __copyinit__(inout self, existing: Self):
self.count = existing.count
self.capacity = existing.capacity
self.keys = existing.keys
@parameter
if caching_hashes:
self.key_hashes = DTypePointer[KeyCountType].alloc(self.capacity)
memcpy(self.key_hashes, existing.key_hashes, self.capacity)
else:
self.key_hashes = DTypePointer[KeyCountType].alloc(0)
self.values = existing.values
self.slot_to_index = DTypePointer[KeyCountType].alloc(self.capacity)
memcpy(self.slot_to_index, existing.slot_to_index, self.capacity)
@parameter
if destructive:
self.deleted_mask = DTypePointer[DType.uint8].alloc(self.capacity >> 3)
memcpy(self.deleted_mask, existing.deleted_mask, self.capacity >> 3)
else:
self.deleted_mask = DTypePointer[DType.uint8].alloc(0)
fn __moveinit__(inout self, owned existing: Self):
self.count = existing.count
self.capacity = existing.capacity
self.keys = existing.keys^
self.key_hashes = existing.key_hashes
self.values = existing.values^
self.slot_to_index = existing.slot_to_index
self.deleted_mask = existing.deleted_mask
fn __del__(owned self):
self.slot_to_index.free()
self.deleted_mask.free()
self.key_hashes.free()
fn __len__(self) -> Int:
return self.count
@always_inline
fn __contains__(inout self, key: String) -> Bool:
return self._find_key_index(key) != 0
fn put(inout self, key: String, value: V):
if self.count / self.capacity >= 0.87:
self._rehash()
var key_hash = hash(key).cast[KeyCountType]()
var modulo_mask = self.capacity - 1
var slot = int(key_hash & modulo_mask)
while True:
var key_index = int(self.slot_to_index.load(slot))
if key_index == 0:
self.keys.add(key)
@parameter
if caching_hashes:
self.key_hashes.store(slot, key_hash)
self.values.append(value)
self.count += 1
self.slot_to_index.store(slot, SIMD[KeyCountType, 1](self.keys.count))
return
@parameter
if caching_hashes:
var other_key_hash = self.key_hashes[slot]
if other_key_hash == key_hash:
var other_key = self.keys[key_index - 1]
if eq(other_key, key):
self.values[key_index - 1] = value # replace value
@parameter
if destructive:
if self._is_deleted(key_index - 1):
self.count += 1
self._not_deleted(key_index - 1)
return
else:
var other_key = self.keys[key_index - 1]
if eq(other_key, key):
self.values[key_index - 1] = value # replace value
@parameter
if destructive:
if self._is_deleted(key_index - 1):
self.count += 1
self._not_deleted(key_index - 1)
return
slot = (slot + 1) & modulo_mask
@always_inline
fn _is_deleted(self, index: Int) -> Bool:
var offset = index >> 3
var bit_index = index & 7
return self.deleted_mask.offset(offset).load() & (1 << bit_index) != 0
@always_inline
fn _deleted(self, index: Int):
var offset = index >> 3
var bit_index = index & 7
var p = self.deleted_mask.offset(offset)
var mask = p.load()
p.store(mask | (1 << bit_index))
@always_inline
fn _not_deleted(self, index: Int):
var offset = index >> 3
var bit_index = index & 7
var p = self.deleted_mask.offset(offset)
var mask = p.load()
p.store(mask & ~(1 << bit_index))
@always_inline
fn _rehash(inout self):
var old_slot_to_index = self.slot_to_index
var old_capacity = self.capacity
self.capacity <<= 1
var mask_capacity = self.capacity >> 3
self.slot_to_index = DTypePointer[KeyCountType].alloc(self.capacity)
memset_zero(self.slot_to_index, self.capacity)
var key_hashes = self.key_hashes
@parameter
if caching_hashes:
key_hashes = DTypePointer[KeyCountType].alloc(self.capacity)
@parameter
if destructive:
var deleted_mask = DTypePointer[DType.uint8].alloc(mask_capacity)
memset_zero(deleted_mask, mask_capacity)
memcpy(deleted_mask, self.deleted_mask, old_capacity >> 3)
self.deleted_mask.free()
self.deleted_mask = deleted_mask
var modulo_mask = self.capacity - 1
for i in range(old_capacity):
if old_slot_to_index[i] == 0:
continue
var key_hash = SIMD[KeyCountType, 1](0)
@parameter
if caching_hashes:
key_hash = self.key_hashes[i]
else:
key_hash = hash(self.keys[int(old_slot_to_index[i] - 1)]).cast[KeyCountType]()
var slot = int(key_hash & modulo_mask)
# var searching = True
while True:
var key_index = int(self.slot_to_index.load(slot))
if key_index == 0:
self.slot_to_index.store(slot, old_slot_to_index[i])
break
# searching = False
else:
slot = (slot + 1) & modulo_mask
@parameter
if caching_hashes:
key_hashes[slot] = key_hash
@parameter
if caching_hashes:
self.key_hashes.free()
self.key_hashes = key_hashes
old_slot_to_index.free()
fn get(self, key: String, default: V) -> V:
var key_index = self._find_key_index(key)
if key_index == 0:
return default
@parameter
if destructive:
if self._is_deleted(key_index - 1):
return default
return self.values[key_index - 1]
fn delete(inout self, key: String):
@parameter
if not destructive:
return
var key_index = self._find_key_index(key)
if key_index == 0:
return
if not self._is_deleted(key_index - 1):
self.count -= 1
self._deleted(key_index - 1)
fn upsert(inout self, key: String, update: fn(value: Optional[V]) -> V):
var key_index = self._find_key_index(key)
if key_index == 0:
var value = update(None)
self.put(key, value)
else:
key_index -= 1
@parameter
if destructive:
if self._is_deleted(key_index):
self.values[key_index] = update(None)
return
self.values[key_index] = update(self.values[key_index])
fn clear(inout self):
self.values.clear()
self.keys.clear()
memset_zero(self.slot_to_index, self.capacity)
@parameter
if destructive:
memset_zero(self.deleted_mask, self.capacity >> 3)
self.count = 0
@always_inline
fn _find_key_index(self, key: String) -> Int:
var key_hash = hash(key).cast[KeyCountType]()
var modulo_mask = self.capacity - 1
var slot = int(key_hash & modulo_mask)
while True:
var key_index = int(self.slot_to_index.load(slot))
if key_index == 0:
return key_index
@parameter
if caching_hashes:
var other_key_hash = self.key_hashes[slot]
if key_hash == other_key_hash:
var other_key = self.keys[key_index - 1]
if eq(other_key, key):
return key_index
else:
var other_key = self.keys[key_index - 1]
if eq(other_key, key):
return key_index
slot = (slot + 1) & modulo_mask
fn debug(self):
print("Dict count:", self.count, "and capacity:", self.capacity)
print("KeyMap:")
for i in range(self.capacity):
var end = ", " if i < self.capacity - 1 else "\n"
print(self.slot_to_index.load(i), end=end)
print("Keys:")
self.keys.print_keys()
@parameter
if caching_hashes:
print("KeyHashes:")
for i in range(self.capacity):
var end = ", " if i < self.capacity - 1 else "\n"
if self.slot_to_index.load(i) > 0:
print(self.key_hashes.load(i), end=end)
else:
print(0, end=end)
| compact-dict/string_dict/dict.mojo | false |
<filename>compact-dict/string_dict/keys_container.mojo
from collections.vector import InlinedFixedVector
struct KeysContainer[KeyEndType: DType = DType.uint32](Sized):
var keys: DTypePointer[DType.uint8]
var allocated_bytes: Int
var keys_end: DTypePointer[KeyEndType]
var count: Int
var capacity: Int
fn __init__(inout self, capacity: Int):
constrained[
KeyEndType == DType.uint8 or
KeyEndType == DType.uint16 or
KeyEndType == DType.uint32 or
KeyEndType == DType.uint64,
"KeyEndType needs to be an unsigned integer"
]()
self.allocated_bytes = capacity << 3
self.keys = DTypePointer[DType.uint8].alloc(self.allocated_bytes)
self.keys_end = DTypePointer[KeyEndType].alloc(capacity)
self.count = 0
self.capacity = capacity
fn __copyinit__(inout self, existing: Self):
self.allocated_bytes = existing.allocated_bytes
self.count = existing.count
self.capacity = existing.capacity
self.keys = DTypePointer[DType.uint8].alloc(self.allocated_bytes)
memcpy(self.keys, existing.keys, self.allocated_bytes)
self.keys_end = DTypePointer[KeyEndType].alloc(self.allocated_bytes)
memcpy(self.keys_end, existing.keys_end, self.capacity)
fn __moveinit__(inout self, owned existing: Self):
self.allocated_bytes = existing.allocated_bytes
self.count = existing.count
self.capacity = existing.capacity
self.keys = existing.keys
self.keys_end = existing.keys_end
fn __del__(owned self):
self.keys.free()
self.keys_end.free()
@always_inline
fn add(inout self, key: String):
var prev_end = 0 if self.count == 0 else self.keys_end[self.count - 1]
var key_length = len(key)
var new_end = prev_end + key_length
var needs_realocation = False
while new_end > self.allocated_bytes:
self.allocated_bytes += self.allocated_bytes >> 1
needs_realocation = True
if needs_realocation:
var keys = DTypePointer[DType.uint8].alloc(self.allocated_bytes)
memcpy(keys, self.keys, int(prev_end))
self.keys.free()
self.keys = keys
memcpy(self.keys.offset(prev_end), DTypePointer(key.unsafe_ptr()), key_length)
var count = self.count + 1
if count >= self.capacity:
var new_capacity = self.capacity + (self.capacity >> 1)
var keys_end = DTypePointer[KeyEndType].alloc(self.allocated_bytes)
memcpy(keys_end, self.keys_end, self.capacity)
self.keys_end.free()
self.keys_end = keys_end
self.capacity = new_capacity
self.keys_end.store(self.count, new_end)
self.count = count
@always_inline
fn get(self, index: Int) -> StringRef:
if index < 0 or index >= self.count:
return ""
var start = 0 if index == 0 else int(self.keys_end[index - 1])
var length = int(self.keys_end[index]) - start
return StringRef(self.keys.offset(start), length)
@always_inline
fn clear(inout self):
self.count = 0
@always_inline
fn __getitem__(self, index: Int) -> StringRef:
return self.get(index)
@always_inline
fn __len__(self) -> Int:
return self.count
fn keys_vec(self) -> InlinedFixedVector[StringRef]:
var keys = InlinedFixedVector[StringRef](self.count)
for i in range(self.count):
keys.append(self[i])
return keys
fn print_keys(self):
print("(" + str(self.count) + ")[", end="")
for i in range(self.count):
var end = ", " if i < self.capacity - 1 else ""
print(self[i], end=end)
print("]")
| compact-dict/string_dict/keys_container.mojo | false |
<filename>compact-dict/string_dict/string_eq.mojo
@always_inline
fn eq(a: StringRef, b: String) -> Bool:
var l = len(a)
if l != len(b):
return False
var p1 = DTypePointer(a.data)
var p2 = DTypePointer(b.unsafe_ptr())
var offset = 0
alias step = 16
while l - offset >= step and (p1.load[width=step](offset) == p2.load[width=step](offset)).reduce_and():
offset += step
if l - offset >= step:
return False
while l - offset > 0 and p1.load(offset) == p2.load(offset):
offset += 1
return l - offset == 0
| compact-dict/string_dict/string_eq.mojo | false |
from max.graph import Graph, TensorType, Type
from max import engine
from tensor import Tensor
def main():
# 1. define add graph
graph = Graph(in_types=List[Type](TensorType(DType.float32, 1), TensorType(DType.float32, 1)))
out = graph[0] + graph[1]
graph.output(out)
graph.verify()
print("finall graph:", graph)
# 2. load and compile the graph
session = engine.InferenceSession()
model = session.load(graph)
print("input names are:")
for input_name in model.get_model_input_names():
print(input_name[])
# 3. Execute / run the graph with some inputs
print("set some input values:")
input0 = Tensor[DType.float32](List[Float32](1.0))
print("input0:", input0)
input1 = Tensor[DType.float32](List[Float32](1.0))
print("input1:", input1)
ret = model.execute("input0", input0^, "input1", input1^)
print("result:", ret.get[DType.float32]("output0"))
| devrel-extras/blogs/2405-max-graph-api-tutorial/add.mojo | false |
<filename>devrel-extras/blogs/2405-max-graph-api-tutorial/matmul.mojo
from max.graph import Graph, TensorType
from tensor import Tensor, TensorShape, randn
from random import seed
from max.engine import InferenceSession
def main():
graph = Graph(TensorType(DType.float32, "m", 2))
# create a constant tensor
constant_value = Tensor[DType.float32](TensorShape(2, 2), 42.0)
print("constant value:", constant_value)
# create a constant node
constant_symbol = graph.constant(constant_value)
# create a matmul node
mm = graph[0] @ constant_symbol
graph.output(mm)
# verify
graph.verify()
# load the graph
session = InferenceSession()
model = session.load(graph)
# generate random inputs
seed(42)
input0 = randn[DType.float32]((2, 2))
print("random 2x2 input0:", input0)
ret = model.execute("input0", input0^)
print("matmul 2x2 result:", ret.get[DType.float32]("output0"))
# with 3 x 2 matrix input
input0 = randn[DType.float32]((3, 2))
print("random 3x2 input0:", input0)
ret = model.execute("input0", input0^)
print("matmul 3x2 result:", ret.get[DType.float32]("output0"))
| devrel-extras/blogs/2405-max-graph-api-tutorial/matmul.mojo | false |
import sys
from pathlib import Path
from python import Python as py
from max.graph import Graph, TensorType, ops
from max import engine
from extensibility import Tensor as TensorExt, empty_tensor
from tensor import Tensor, TensorShape, TensorSpec
def load_model_weights(use_relu6: Bool) -> PythonObject:
np = py.import_module("numpy")
if use_relu6:
fin = py.evaluate('open("model_relu6_weights.npy", mode="rb")')
else:
fin = py.evaluate('open("model_weights.npy", mode="rb")')
model_weights = np.load(fin, allow_pickle=True).item() # note this is of type PythonObject
fin.close()
print("python type of model_weights:", py.type(model_weights))
for item in model_weights.items():
print(item[0], item[1].shape, py.type(item[1]))
return model_weights
@always_inline
fn numpy_data_pointer[type: DType](numpy_array: PythonObject) raises -> DTypePointer[type]:
return DTypePointer[type](
address=int(numpy_array.__array_interface__["data"][0])
)
@always_inline
fn memcpy_from_numpy(array: PythonObject, tensor: Tensor) raises:
var src = numpy_data_pointer[tensor.type](array)
var dst = tensor._ptr
var length = tensor.num_elements()
memcpy(dst, src, length)
@always_inline
fn numpy_to_tensor[type: DType](array: PythonObject) raises -> Tensor[type]:
var shape = List[Int]()
var array_shape = array.shape
for dim in array_shape:
shape.append(dim.__index__())
var out = Tensor[type](shape)
memcpy_from_numpy(array, out)
return out ^
def build_mnist_graph(
fc1w: Tensor[DType.float32],
fc1b: Tensor[DType.float32],
fc2w: Tensor[DType.float32],
fc2b: Tensor[DType.float32],
use_relu6: Bool
) -> Graph:
# Note: "batch" is a symbolic dim which is known ahead of time vs dynamic dim
graph = Graph(TensorType(DType.float32, "batch", 28 * 28))
# PyTorch linear is defined as: x W^T + b so we need to transpose the weights
fc1 = (graph[0] @ ops.transpose(graph.constant(fc1w), 1, 0)) + graph.constant(fc1b)
if use_relu6:
relu = ops.custom["relu6"](fc1, fc1.type())
else:
relu = ops.relu(fc1)
fc2 = (relu @ ops.transpose(graph.constant(fc2w), 1, 0)) + graph.constant(fc2b)
out = ops.softmax(fc2) # adding explicit softmax for inference prob
graph.output(out)
graph.verify()
return graph
def load_mnist_test_data() -> PythonObject:
torchvision = py.import_module("torchvision")
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=None, download=False)
return test_dataset
def preprocess(image: PythonObject) -> PythonObject:
transforms = py.import_module("torchvision.transforms")
image_tensor = transforms.ToTensor()(image)
image_tensor_normalized = transforms.Normalize((0.5,), (0.5,))(image_tensor)
reshaped_image = image_tensor_normalized.reshape(1, 28 * 28).numpy()
return reshaped_image
def main():
args = sys.argv()
if args[1] == "--use-relu6":
use_relu6 = True
else:
use_relu6 = False
weights_dict = load_model_weights(use_relu6)
fc1w = numpy_to_tensor[DType.float32](weights_dict["fc1.weight"])
fc1b = numpy_to_tensor[DType.float32](weights_dict["fc1.bias"])
fc2w = numpy_to_tensor[DType.float32](weights_dict["fc2.weight"])
fc2b = numpy_to_tensor[DType.float32](weights_dict["fc2.bias"])
mnist_graph = build_mnist_graph(fc1w^, fc1b^, fc2w^, fc2b^, use_relu6)
session = engine.InferenceSession()
if use_relu6:
model = session.load(mnist_graph, custom_ops_paths=Path("custom_ops.mojopkg"))
else:
model = session.load(mnist_graph)
for name in model.get_model_input_names():
print("input:", name[])
for name in model.get_model_output_names():
print("output:", name[])
correct = 0
total = 0
# use batch size of 1 in this example
test_dataset = load_mnist_test_data()
for i in range(len(test_dataset)):
item = test_dataset[i]
image = item[0]
label = item[1]
preprocessed_image = preprocess(image)
output = model.execute("input0", preprocessed_image)
probs = output.get[DType.float32]("output0")
predicted = probs.argmax(axis=1)
label_ = Tensor[DType.index](TensorShape(1), int(label))
correct += int(predicted == label_)
total += 1
print("Accuracy of the network on the 10000 test images:", 100 * correct / total, "%")
| devrel-extras/blogs/2405-max-graph-api-tutorial/mnist.mojo | false |
import math
from max.extensibility import Tensor, empty_tensor
from max import register
@register.op("relu6")
fn relu6[type: DType, rank: Int](x: Tensor[type, rank]) -> Tensor[type, rank]:
var output = empty_tensor[type](x.shape)
@always_inline
@parameter
fn _relu6[width: Int](i: StaticIntTuple[rank]) -> SIMD[type, width]:
var val = x.simd_load[width](i)
return math.min(math.max(0, val), 6)
output.for_each[_relu6]()
return output^
| devrel-extras/blogs/2405-max-graph-api-tutorial/custom_ops/relu6.mojo | false |
<filename>devrel-extras/blogs/2405-max-graph-api-tutorial/custom_ops/test_relu6.mojo
from max.extensibility import Tensor, empty_tensor
from custom_ops.relu6 import relu6
from testing import assert_equal
alias type = DType.float32
def test_relu6():
x = empty_tensor[type](StaticIntTuple[1](5))
x.store(0, Float32(-1))
x.store(1, Float32(0))
x.store(2, Float32(1))
x.store(3, Float32(6))
x.store(4, Float32(7))
expected = empty_tensor[type](StaticIntTuple[1](5))
expected.store(0, Float32(0))
expected.store(1, Float32(0))
expected.store(2, Float32(1))
expected.store(3, Float32(6))
expected.store(4, Float32(6))
assert_equal(relu6(x), expected)
# uncomment for testing and run `mojo test_relu6.mojo`
# def main():
# test_relu6()
| devrel-extras/blogs/2405-max-graph-api-tutorial/custom_ops/test_relu6.mojo | false |
import sys
from pathlib import Path, cwd
from tensor import Tensor, TensorShape, TensorSpec
from utils.index import Index
from max.engine import InferenceSession, Model as EngineModel
from max.engine._utils import handle_from_config, call_dylib_func
from max.graph.quantization import (
Float32Encoding,
Q4_0Encoding,
Q4_KEncoding,
Q6_KEncoding,
QuantizationEncoding,
)
from llama3.tokenizer import TikTokenEncoder
from llama3 import Llama3, KVCache, WeightedSampler
from weights.gguf import GGMLType, GGUFFile, GGUFArray
from weights.loadable_model import LlamaHParams
from weights.download import download_weights_to_cache
@value
struct Config:
"""Configuration for token generation runtime options."""
var batch_size: Int
var max_tokens: Int
var quantization_encoding: String
var temperature: Float32
var min_p: Float32
fn __init__(
inout self,
/,
batch_size: Int = 1,
max_tokens: Int = 64,
quantization_encoding: String = "q4_k",
temperature: Float32 = 0.5,
min_p: Float32 = 0.05,
):
self.batch_size = batch_size
self.max_tokens = max_tokens
self.quantization_encoding = quantization_encoding
self.temperature = temperature
self.min_p = min_p
struct Llama[Encoding: QuantizationEncoding = Float32Encoding]:
var _model: Llama3[Encoding]
var _session: InferenceSession
var _compiled_model: EngineModel
var _sampler: WeightedSampler
var tokenizer: TikTokenEncoder
var config: Config
def __init__(inout self, model_path: Path, config: Config = Config()):
print("loading the model", model_path)
self._model = Llama3[Encoding](model_path)
graph = self._model.build_graph("llm")
print("compiling the model", model_path)
self._session = InferenceSession()
self._compiled_model = self._session.load(graph)
self._sampler = WeightedSampler(config.temperature, config.min_p)
self.tokenizer = TikTokenEncoder.cl100k_base_llama3(
self._model.gguf["tokenizer.ggml.tokens"]._value.unsafe_get[
GGUFArray
]()[]
)
self.config = config
@staticmethod
def from_pretrained(url: String) -> Self:
cache_path = cwd().joinpath(".cache")
download_weights_to_cache(cache_path, url)
model_path = cache_path / String(url).split("/")[-1]
return Self(model_path)
def tokenize(self, text: String) -> List[Int]:
ret = List[Int]()
for enc in self.tokenizer.encode(text):
ret.append(enc[].id)
return ret
def _call(
self,
tokens: Tensor[DType.int64],
inout kv_cache: KVCache,
) -> Tensor[DType.float32]:
"""Execute the model predicting one new token."""
input_map = self._session.new_tensor_map()
input_map.borrow("input0", tokens)
input_map.borrow("input1", kv_cache.keys_view())
input_map.borrow("input2", kv_cache.values_view())
results = self._compiled_model.execute(input_map)
kv_cache.update(
results.buffer[DType.float32]("output1"),
results.buffer[DType.float32]("output2"),
)
return results.get[DType.float32]("output0")
def __call__(inout self, text: String) -> String:
encoded = self.tokenizer.encode(text)
tokens = Tensor[DType.int64](TensorShape(1, len(text)))
for i in range(len(encoded)):
tokens[Index(0, i)] = encoded[i].id
kv_cache = KVCache(self._model.hyperparams(), self.config.max_tokens, 1)
ret = String("")
for _ in range(encoded.size, self.config.max_tokens + 1):
logits = self._call(tokens, kv_cache)
token = self._sampler.sample(logits).selected
tokens = Tensor(TensorShape(1, 1), Int64(token))
ret += self.tokenizer.decode(token).token
_ = kv_cache^
return ret
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/llm.mojo | false |
from max.graph.quantization import Q4_KEncoding
from llm import Llama
def main():
llm = Llama[Q4_KEncoding].from_pretrained("https://huggingface.co/bartowski/Meta-Llama-3-8B-Instruct-GGUF/resolve/main/Meta-Llama-3-8B-Instruct-Q4_K_M.gguf")
prompt = "Tell me a dad joke"
print("Prompt:", prompt)
print("Response:", llm(prompt))
print("tokenize ids:")
for id in llm.tokenize(prompt):
print(id[])
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/main.mojo | false |
<filename>devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/tokenizer/regex.mojo
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""POSIX 2 regular expressions via regcomp/regexec."""
from sys.info import os_is_macos
from _mlir._c.ffi import MLIR_func
def set_locale_unicode():
empty_string = str("")
locale = external_call["setlocale", UnsafePointer[UInt8]](
0, Reference(empty_string.as_bytes_slice()[0])
) # LC_ALL
if not locale:
raise "didn't set locale"
struct ExecuteOption:
alias STARTEND = 4
struct CompileOption:
alias EXTENDED = 1
alias ICASE = 2
alias ENHANCED = 0o400
fn llvm_regcomp(ptr: UnsafePointer[_CRegex], pattern: String, mode: Int) -> Int:
return MLIR_func[
"llvm_regcomp",
fn (UnsafePointer[_CRegex], UnsafePointer[Int8], Int) -> Int,
]()(ptr, pattern.unsafe_ptr(), mode)
fn llvm_regexec(
ptr: UnsafePointer[_CRegex],
string: String,
inout pmatch: List[_CRegexMatch],
mode: Int,
) -> Int:
return MLIR_func[
"llvm_regexec",
fn (
UnsafePointer[_CRegex],
UnsafePointer[Int8],
Int,
UnsafePointer[_CRegexMatch],
Int,
) -> Int,
]()(ptr, string.unsafe_ptr(), len(pmatch), pmatch.unsafe_ptr(), mode)
fn llvm_regfree(ptr: UnsafePointer[_CRegex]):
return MLIR_func["llvm_regfree", fn (UnsafePointer[_CRegex]) -> NoneType]()(
ptr
)
fn llvm_regerror(
error: Int,
ptr: UnsafePointer[_CRegex],
message: UnsafePointer[UInt8],
max_size: Int,
) -> Int:
return MLIR_func[
"llvm_regerror",
fn (Int, UnsafePointer[_CRegex], UnsafePointer[UInt8], Int) -> Int,
]()(error, ptr, message, max_size)
struct _CRegex:
# This corresponds to the llvm_regex_t type definition.
var _magic: Int
var capture_groups: Int
var _re_endp: UnsafePointer[NoneType]
var _re_guts: UnsafePointer[NoneType]
var _initialized: Bool
fn __init__(inout self):
self._magic = 0
self.capture_groups = 0
self._re_endp = UnsafePointer[NoneType]()
self._re_guts = UnsafePointer[NoneType]()
self._initialized = False
fn __moveinit__(inout self, owned existing: Self):
# _CRegex can't be safely moved once it's initialized.
# We have to implement __move__ currently to satisfy Arc's Movable
# trait bounds.
self.__init__()
fn __del__(owned self):
if self._initialized:
llvm_regfree(self._ptr())
@staticmethod
def compile(pattern: String, options: Int = 0) -> Arc[Self]:
self = Arc(Self())
self[]._compile(pattern, options | CompileOption.EXTENDED)
return self
def _compile(inout self, pattern: String, options: Int):
err = llvm_regcomp(self._ptr(), pattern, options)
if err:
raise self._error(err)
self._initialized = True
def exec(self, string: String, start: Int = 0) -> List[_CRegexMatch]:
# This list should be able to be stack-allocated to avoid a heap
# allocation when there's no match. stack_allocation currently
# only supports static allocation sizes.
max_groups = self.capture_groups + 1
matches = List[_CRegexMatch](capacity=max_groups)
matches.append(_CRegexMatch(start, len(string)))
matches.size = max_groups
no_match = llvm_regexec(
self._ptr(), string, matches, ExecuteOption.STARTEND
)
if no_match:
return List[_CRegexMatch]()
return matches^
def _error(self, code: Int) -> String:
alias MAX_ERROR_LENGTH = 2048
message = UnsafePointer[UInt8].alloc(MAX_ERROR_LENGTH)
size = llvm_regerror(code, self._ptr(), message, MAX_ERROR_LENGTH)
return "regex error: " + String(message, size)
fn _ptr(self) -> UnsafePointer[Self]:
return UnsafePointer.address_of(self)
@value
struct _CRegexMatch:
var start: Int
var end: Int
fn __bool__(self) -> Bool:
return self.start != -1
fn __repr__(self) -> String:
return (
str("_Group(start=")
+ str(self.start)
+ ", end="
+ str(self.end)
+ ")"
)
@value
struct _MatchIter[
regex_lifetime: ImmutableLifetime,
string_lifetime: ImmutableLifetime,
]:
var regex: Reference[Regex, False, regex_lifetime]
var string: Reference[String, False, string_lifetime]
var start: Int
var next_match: Optional[Match[string_lifetime]]
# This is a workaround for not having negative lookaheads, expect this
# interface to change. This allows using capture groups to tell the regex
# to "match" only part of the match, and continue at the end of the capture
# group.
var negative_lookahead_hack: Bool
def __init__(
inout self,
regex: Reference[Regex, False, regex_lifetime],
string: Reference[String, False, string_lifetime],
negative_lookahead_hack: Bool = False,
):
self.regex = regex
self.string = string
self.start = 0
self.next_match = None
self.negative_lookahead_hack = negative_lookahead_hack
self._next()
fn __iter__(self) -> Self:
return self
def __next__(inout self) -> Match[string_lifetime]:
m = self.next_match.value()[]
self._next()
return m^
fn __len__(self) -> Int:
return int(Bool(self.next_match))
def _next(inout self):
m = self.regex[].find(self.string[], start=self.start)
self.next_match = m
if m and self.negative_lookahead_hack:
# End the regex at the end of the last capture group,
# or at the end of the match if none are populated.
max_end = self.start
for i in range(1, len(m.value()[]._groups)):
group = m.value()[]._groups[i]
if group and group.end > max_end:
max_end = group.end
if max_end == self.start:
max_end = m.value()[].end()
self.start = max_end
self.next_match.value()[]._groups[0].end = max_end
else:
self.start = m.value()[].end() if m else len(self.string[])
@value
struct Match[lifetime: ImmutableLifetime]:
var _string: Span[UInt8, False, lifetime]
var _groups: List[_CRegexMatch]
fn __getitem__(self, group: Int) -> StringSlice[False, lifetime]:
var m = self._groups[group]
return StringSlice(unsafe_from_utf8=self._string[m.start : m.end])
fn __str__(self) -> String:
return str(self[0])
fn __len__(self) -> Int:
return self.end() - self.start()
fn start(self) -> Int:
return self._groups[0].start
fn end(self) -> Int:
return self._groups[0].end
fn __repr__(self) -> String:
return (
str("Match(start=")
+ str(self.start())
+ ", end="
+ str(self.end())
+ ", match="
+ repr(str(self))
+ ")"
)
@value
struct Regex:
var _c: Arc[_CRegex]
def __init__(inout self, pattern: String, options: Int = 0):
self._c = _CRegex.compile(pattern, options)
def find(
self, string: String, start: Int = 0
) -> Optional[Match[__lifetime_of(string)]]:
groups = self._c[].exec(string, start=start)
if groups:
return Match(string.as_bytes_slice(), groups^)
return None
def findall(
self, string: String, negative_lookahead_hack: Bool = False
) -> _MatchIter[__lifetime_of(self), __lifetime_of(string)]:
return _MatchIter(self, string, negative_lookahead_hack)
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/tokenizer/regex.mojo | false |
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""TikToken implementation."""
from base64 import b64decode
from collections import Dict
from pathlib import Path
from .bpe import BPETokenizer, TokenWithID
from .regex import Match, Regex, CompileOption
from weights.gguf import GGUFArray, GGUFString
def _next_rune(inout span: Span[UInt8, _]) -> Int:
if not span[0] & 0x80:
result = int(span[0])
span = span[1:]
return int(result)
elif not span[0] & 0x20:
result = ((int(span[0]) & 0x1F) << 6) | (int(span[1]) & 0x3F)
span = span[2:]
return int(result)
elif not span[0] & 0x10:
result = (
((int(span[0]) & 0x0F) << 12)
| ((int(span[1]) & 0x3F) << 6)
| (int(span[2]) & 0x3F)
)
span = span[3:]
return int(result)
else:
result = (
((int(span[0]) & 0x07) << 18)
| ((int(span[1]) & 0x3F) << 12)
| ((int(span[2]) & 0x3F) << 6)
| (int(span[3]) & 0x3F)
)
span = span[4:]
return int(result)
def _runes(string: String) -> List[Int]:
span = string.as_bytes_slice()
runes = List[Int]()
while len(span):
runes.append(_next_rune(span))
return runes^
def _decode_token(string: String, decode_map: Dict[Int, UInt8]) -> String:
result = List[UInt8]()
for rune in _runes(string):
result.append(decode_map[rune[]])
result.append(0)
return result
def _decode_map() -> Dict[Int, UInt8]:
# I have no idea why this is the way it is.
decode_map = Dict[Int, UInt8]()
for i in range(256, 289): # 0-32
decode_map[i] = i - 256
for i in range(33, 127): # 33-126
decode_map[i] = i
for i in range(289, 323): # 127-160
decode_map[i] = i - 162
for i in range(161, 256): # 161-255
decode_map[i] = i
decode_map[323] = 173
return decode_map^
struct TikTokenEncoder:
var bpe: BPETokenizer
var regex: Regex
var special_tokens: Dict[String, Int]
def __init__(
inout self,
owned bpe: BPETokenizer,
owned regex: Regex,
owned special_tokens: Dict[String, Int],
):
self.bpe = bpe^
self.regex = regex^
self.special_tokens = special_tokens^
@staticmethod
def cl100k_base_llama3(path: Path) -> Self:
return Self.cl100k_base_llama3(BPETokenizer.from_tiktoken(path))
@staticmethod
def cl100k_base_llama3(tokens: GGUFArray) -> Self:
bpe = BPETokenizer()
decode_map = _decode_map()
for i in range(tokens.n):
encoded = str(tokens.data[i])
bpe.add_token(_decode_token(encoded, decode_map), i)
return Self.cl100k_base_llama3(bpe)
@staticmethod
def cl100k_base_llama3(owned bpe: BPETokenizer) -> Self:
special_tokens = Dict[String, Int]()
special_tokens["<|begin_of_text|>"] = 128000
special_tokens["<|end_of_text|>"] = 128001
for e in special_tokens.items():
bpe.add_token(e[].key, e[].value)
pattern = str("|").join(
"'[sdmt]|ll|ve|re",
"[^\r\n[:alnum:]]?[[:alpha:]]+",
"[[:digit:]]{1,3}",
" ?[^[:space:][:alnum:]]+[\r\n]*",
"[[:space:]]*[\r\n]",
"([[:space:]]+)[[:space:]]",
"[[:space:]]+",
)
return Self(bpe^, Regex(pattern, CompileOption.ICASE), special_tokens^)
def encode(
self,
string: String,
bos: Optional[String] = str("<|begin_of_text|>"),
eos: Optional[String] = None,
) -> List[TokenWithID]:
# Compared to Rust tiktoken, this does not currently implement
# - special tokens (not used in llama3)
# - multithreaded decoding
# multithreaded decoding is quite a bit more complex, as it requires
# both splitting the text across threads and merging afterwards, and also
# needs to know how to handle the boundary conditions between different segments
tokens = List[TokenWithID]()
if bos:
tokens += self.encode_special(bos.value()[])
for segment in self.regex.findall(string, negative_lookahead_hack=True):
ss = str(segment)
if token_id := self.bpe.token_ids.find(ss):
tokens += TokenWithID(ss^, token_id.value()[])
else:
tokens += self.bpe.encode(ss^)
if eos:
tokens += self.encode_special(eos.value()[])
return tokens
def encode_special(self, string: String) -> TokenWithID:
if special_id := self.special_tokens.find(string):
return TokenWithID(string, special_id.value()[])
return TokenWithID(string, self.bpe.token_ids[string])
def decode(self, token_id: Int) -> TokenWithID:
return TokenWithID(self.bpe.vocab[token_id].token, token_id)
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/tokenizer/tiktoken.mojo | false |
<filename>devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/token_sampler/token_sampler.mojo
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from tensor import Tensor
from utils import StaticTuple
@value
struct SamplerResult(Stringable):
"""Container for a token sampler decision. This struct retains some
context on what options remained after filtering (to aid in
rationalizing sampler behavior). The goal is to facilitate experimentation,
not raw performance."""
# Chosen token (vocabulary index)
var selected: Int
# Options the selected token was sampled from after filtering
var options: List[Int]
# List of the associated likelihoods (len(options) == len(likelihoods))
var likelihoods: List[Float32]
fn __init__(
inout self: Self,
selected: Int,
options: List[Int] = List[Int](),
likelihoods: List[Float32] = List[Float32](),
):
self.selected = selected
self.options = options
self.likelihoods = likelihoods
fn __str__(self) -> String:
var msg = "Selected: " + str(self.selected) + " from "
for i in range(len(self.options)):
msg += (
"["
+ str(self.options[i])
+ ", "
+ str(self.likelihoods[i])
+ "] "
)
return msg
trait TokenSampler:
"""A generic token sampler that takes in a list of logits and samples
an element based on the associated likelihoods."""
fn sample[dtype: DType](self, logits: Tensor[dtype]) -> SamplerResult:
...
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/token_sampler/token_sampler.mojo | false |
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from .token_sampler import TokenSampler, SamplerResult
from tensor import Tensor
from random import random_float64
import math
from utils.numerics import min_finite
@value
struct WeightedSampler(TokenSampler):
# Standard temperature parameter -- 1.0 is unmodified, 0.0 is effectively greedy sampling
var temperature: Float32
# min_p style filter (source: https://github.com/ggerganov/llama.cpp/pull/3841)
var min_p: Float32
fn __init__(inout self: Self, temperature: Float32, min_p: Float32 = 0.05):
self.temperature = temperature
self.min_p = min_p
fn sample[dtype: DType](self, logits: Tensor[dtype]) -> SamplerResult:
var normalization = Scalar[DType.float32](0)
# Add a floor to mitigate div0 if T=0.0 is passed in.
var temp_modified: SIMD[DType.float32, 1] = max(
Float32(1e-6), self.temperature
)
# Overflow mitigation.
# p_i = exp(logit_i / T) / (sum_j exp(logit_j / T))
# = exp(logit_max / T) / exp(logit_max / T) (...)
# = exp((logit_i-logit_max)/T) / (sum_j exp((logit_j-logit_max)/T))
var largest = min_finite[dtype]()
for i in range(logits.num_elements()):
if largest < logits[0, i]:
largest = logits[0, i]
for i in range(logits.num_elements()):
var intermediate: SIMD[DType.float32, 1] = (
logits[0, i] - largest
).cast[DType.float32]() / temp_modified
var p = math.exp(intermediate)
normalization += p
# Start filtering for min_p
var retained_idx = List[Int]()
var retained_p = List[Float32]()
var options = List[Int]()
var likelihoods = List[Float32]()
# Now run through again with the actual probabilities
for i in range(logits.num_elements()):
var intermediate: SIMD[DType.float32, 1] = (
logits[0, i] - largest
).cast[DType.float32]() / temp_modified
var p: Float32 = math.exp(intermediate) / normalization
if p >= (self.min_p / normalization):
retained_idx.append(i)
retained_p.append(p)
# Renormalize after filtering min_p
normalization = Scalar[DType.float32](0)
for v in range(len(retained_idx)):
normalization += retained_p[v]
# Simple O(N) weighted sampler
# Collect the considered tokens as we go for the SamplerResult
var u = random_float64()
var cdf = Scalar[dtype.float32](0.0)
for i in range(len(retained_idx)):
options.append(retained_idx[i])
likelihoods.append(
retained_p[i] / normalization.cast[DType.float32]()
)
cdf += retained_p[i] / normalization
if cdf > u:
return SamplerResult(retained_idx[i], options)
return SamplerResult(retained_idx[len(retained_idx) - 1], options)
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/token_sampler/weighted_sampler.mojo | false |
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""Token sampler strategies for Llama2
"""
| devrel-extras/blogs/2406-what-is-new-in-max-24.4/llama3/token_sampler/__init__.mojo | false |
import max.graph
from memory import memset_zero, memcpy
from sys.info import simdwidthof
from algorithm.functional import vectorize
from python import Python
# updated for Mojo 24.4
# replacing math functions that were removed from the standard library with simple wrappers
fn math_mul[dtype: DType, width: Int](l: SIMD[dtype, width], r:SIMD[dtype, width]) -> SIMD[dtype, width]:
return l*r
fn math_add[dtype: DType, width: Int](l: SIMD[dtype, width], r:SIMD[dtype, width]) -> SIMD[dtype, width]:
return l+r
fn math_sub[dtype: DType, width: Int](l: SIMD[dtype, width], r:SIMD[dtype, width]) -> SIMD[dtype, width]:
return l-r
fn math_abs[dtype: DType, width: Int](l: SIMD[dtype, width]) -> SIMD[dtype, width]:
return abs(l)
struct MojoArray[dtype: DType = DType.float64](Stringable):
var _ptr: DTypePointer[dtype]
var numel: Int
alias simd_width: Int = simdwidthof[dtype]()
# Initializers
fn __init__(inout self, numel: Int):
self._ptr = DTypePointer[dtype].alloc(numel)
self.numel = numel
memset_zero[dtype](self._ptr, numel)
fn __init__(inout self, numel: Int, _ptr: DTypePointer[dtype]):
self._ptr = _ptr
self.numel = numel
fn __init__(inout self, *data: Scalar[dtype]):
self.numel = len(data)
self._ptr = DTypePointer[dtype].alloc(len(data))
for i in range(len(data)):
self._ptr[i] = data[i]
fn __copyinit__(inout self, other: Self):
self._ptr = other._ptr
self.numel = other.numel
fn __getitem__(self, idx: Int) -> Scalar[dtype]:
return self._ptr.load[width=1](idx)
fn __neg__(self)->Self:
return self._elemwise_scalar_math[math_mul](-1.0)
fn __mul__(self, other: Self)->Self:
return self._elemwise_array_math[math_mul](other)
fn __mul__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math_mul](s)
fn __rmul__(self, s: Scalar[dtype])->Self:
return self*s
fn __add__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math_add](s)
fn __add__(self, other: Self)->Self:
return self._elemwise_array_math[math_add](other)
fn __radd__(self, s: Scalar[dtype])->Self:
return self+s
fn __sub__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math_sub](s)
fn __sub__(self, other: Self)->Self:
return self._elemwise_array_math[math_sub](other)
fn __rsub__(self, s: Scalar[dtype])->Self:
return -self+s
@staticmethod
fn from_numpy(np_array: PythonObject) raises->Self:
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_array.__array_interface__['data'][0].__index__()).value
)
)
var numel = int(np_array.shape[0])
var _ptr = DTypePointer[dtype].alloc(numel)
memcpy(_ptr, npArrayPtr, numel)
return Self(numel,_ptr)
fn to_numpy(self) raises->PythonObject:
var np = Python.import_module("numpy")
var np_arr = np.zeros(self.numel)
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_arr.__array_interface__['data'][0].__index__()).value
)
)
memcpy(npArrayPtr, self._ptr, self.numel)
return np_arr
fn __str__(self)->String:
var s:String = ""
s += "["
for i in range(self.numel):
if i>0:
s+=" "
s = s + str(self._ptr[i])
s = s +"]"
return s
fn sqrt(self)->Self:
return self._elemwise_transform[math.sqrt]()
fn cos(self)->Self:
return self._elemwise_transform[math.cos]()
fn sin(self)->Self:
return self._elemwise_transform[math.sin]()
fn abs(self)->Self:
return self._elemwise_transform[math_abs]()
fn __pow__(self, p: Scalar[dtype])->Self:
return self._elemwise_pow(p)
fn _elemwise_pow(self, p: Scalar[dtype]) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn tensor_scalar_vectorize[simd_width: Int](idx: Int):
new_array._ptr.store[width=simd_width](idx, pow(self._ptr.load[width=simd_width](idx), SIMD[dtype,simd_width].splat(p)))
vectorize[tensor_scalar_vectorize, simd_width](self.numel)
return new_array
fn _elemwise_transform[func: fn[dtype: DType, width: Int](SIMD[dtype, width])->SIMD[dtype, width]](self) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.store[width=simd_width](idx, func[dtype, simd_width](self._ptr.load[width=simd_width](idx)))
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn _elemwise_array_math[func: fn[dtype: DType, width: Int](SIMD[dtype, width],SIMD[dtype, width])->SIMD[dtype, width]](self, other: Self) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.store[width=simd_width](idx, func[dtype, simd_width](self._ptr.load[width=simd_width](idx), other._ptr.load[width=simd_width](idx)))
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn _elemwise_scalar_math[func: fn[dtype: DType, width: Int](SIMD[dtype, width],SIMD[dtype, width])->SIMD[dtype, width]](self, s: Scalar[dtype]) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.store[width=simd_width](idx, func[dtype, simd_width](self._ptr.load[width=simd_width](idx), SIMD[dtype, simd_width](s)))
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn main() raises:
var np = Python.import_module("numpy")
var plt = Python.import_module("matplotlib.pyplot")
var np_arr = np.arange(-2,2,0.01)
var x = MojoArray.from_numpy(np_arr)
var fig = plt.figure()
var ax = fig.add_subplot()
_ = ax.set_xlim([-3,3])
_ = ax.set_ylim([-3,3])
var a = MojoArray.from_numpy(np.linspace(0,20,100))
for i in range(a.numel):
var y = (x**2)**(1/3.) - 0.9*((3.3-(x*x)).sqrt())*(a[i]*3.14*x).sin()
_ = ax.cla()
var title = ax.set_title("Mojo β€οΈ Python")
_ = title.set_fontsize(20)
_ = ax.set_axis_off()
_ = ax.plot(x.to_numpy(),y.to_numpy(),'r')
_ = plt.pause(0.1)
_ = plt.draw()
| devrel-extras/blogs/mojo-calculating-and-plotting-a-valentines-day-heart/valentine.mojo | false |
import math, random
from algorithm import vectorize
from algorithm.functional import elementwise
from sys.intrinsics import _mlirtype_is_eq
from python import Python
struct DunderArray[dtype: DType = DType.float64](
Stringable, Intable, CollectionElement, Sized
):
var _ptr: DTypePointer[dtype]
var numel: Int
# Initializers
fn __init__(inout self, numel: Int):
self._ptr = DTypePointer[dtype].alloc(numel)
self.numel = numel
memset_zero[dtype](self._ptr, numel)
fn __init__(inout self, np_array: PythonObject) raises:
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index, 1](
np_array.__array_interface__["data"][0].__index__()
).value
)
)
self.numel = int(np_array.shape[0])
self._ptr = DTypePointer[dtype].alloc(self.numel)
memcpy(self._ptr, npArrayPtr, self.numel)
fn __init__(inout self, numel: Int, _ptr: DTypePointer[dtype]):
self._ptr = _ptr
self.numel = numel
fn __init__(inout self, *data: Scalar[dtype]):
self.numel = len(data)
self._ptr = DTypePointer[dtype].alloc(len(data))
for i in range(len(data)):
self._ptr[i] = data[i]
@staticmethod
fn rand(numel: Int) -> Self:
var _ptr = DTypePointer[dtype].alloc(numel)
random.rand(_ptr, numel)
return Self(numel, _ptr)
fn __copyinit__(inout self, other: Self):
self._ptr = other._ptr
self.numel = other.numel
fn __moveinit__(inout self, owned existing: Self):
self._ptr = existing._ptr
self.numel = existing.numel
existing.numel = 0
existing._ptr = DTypePointer[dtype]()
fn __del__(owned self):
self._ptr.free()
# Getter and setters
fn __getitem__(self, idx: Int) -> Scalar[dtype]:
return self._ptr.simd_load[1](idx)
fn __setitem__(inout self, elem: Int, val: Scalar[dtype]):
return self._ptr.simd_store[1](elem, val)
# Unary arithmetic operators
fn __neg__(self) -> Self:
return self * (-1.0)
fn __pos__(self) -> Self:
return self * (1.0)
fn __invert__(self) -> Self:
if _mlirtype_is_eq[Scalar[dtype], Bool]():
var new_array = Self(self.numel)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_array._ptr.simd_store[simd_width](
idx[0], ~self._ptr.simd_load[simd_width](idx[0])
)
elementwise[1, simdwidthof[dtype](), wrapper](self.numel)
return new_array
else:
print("Error: You can only invert Bool arrays")
return self
# Normal comparison operators
fn __lt__(self, other: Self) -> Bool:
return (self**2)._reduce_sum()[0] < (other**2)._reduce_sum()[0]
fn __le__(self, other: Self) -> Bool:
return (self**2)._reduce_sum()[0] <= (other**2)._reduce_sum()[0]
fn __eq__(self, other: Self) -> Bool:
return self._ptr == other._ptr
fn __ne__(self, other: Self) -> Bool:
return self._ptr != other._ptr
fn __gt__(self, other: Self) -> Bool:
return (self**2)._reduce_sum()[0] > (other**2)._reduce_sum()[0]
fn __ge__(self, other: Self) -> Bool:
return (self**2)._reduce_sum()[0] >= (other**2)._reduce_sum()[0]
# Normal, reflected and inplace arithmetic operators
fn __add__(self, s: Scalar[dtype]) -> Self:
return self._elemwise_scalar_math[math.add](s)
fn __add__(self, other: Self) -> Self:
return self._elemwise_array_math[math.add](other)
fn __radd__(self, s: Scalar[dtype]) -> Self:
return self + s
fn __iadd__(inout self, s: Scalar[dtype]):
self = self + s
fn __sub__(self, s: Scalar[dtype]) -> Self:
return self._elemwise_scalar_math[math.sub](s)
fn __sub__(self, other: Self) -> Self:
return self._elemwise_array_math[math.sub](other)
fn __rsub__(self, s: Scalar[dtype]) -> Self:
return -(self - s)
fn __isub__(inout self, s: Scalar[dtype]):
self = self - s
fn __mul__(self, s: Scalar[dtype]) -> Self:
return self._elemwise_scalar_math[math.mul](s)
fn __mul__(self, other: Self) -> Self:
return self._elemwise_array_math[math.mul](other)
fn __rmul__(self, s: Scalar[dtype]) -> Self:
return self * s
fn __imul__(inout self, s: Scalar[dtype]):
self = self * s
fn __matmul__(self, other: Self) -> Self:
return self._elemwise_array_math[math.mul](other)._reduce_sum()
fn __imatmul__(inout self, other: Self):
self = self.__matmul__(other)
fn __truediv__(self, s: Scalar[dtype]) -> Self:
return self._elemwise_scalar_math[math.div](s)
fn __truediv__(self, other: Self) -> Self:
return self._elemwise_array_math[math.div](other)
fn __rtruediv__(self, s: Scalar[dtype]) -> Self:
return self._r_elemwise_scalar_math[math.div](s)
fn __itruediv__(inout self, s: Scalar[dtype]):
self = self / s
fn __floordiv__(self, s: Scalar[dtype]) -> Self:
return (self / s)._elemwise_transform[math.floor]()
fn __floordiv__(self, other: Self) -> Self:
return (self / other)._elemwise_transform[math.floor]()
fn __rfloordiv__(self, s: Scalar[dtype]) -> Self:
return (s / self)._elemwise_transform[math.floor]()
fn __ifloordiv__(inout self, s: Scalar[dtype]):
self = self.__rfloordiv__(s)
fn __mod__(self, s: Scalar[dtype]) -> Self:
return self._elemwise_scalar_math[math.mod](s)
fn __mod__(self, other: Self) -> Self:
return self._elemwise_array_math[math.mod](other)
fn __rmod__(self, s: Scalar[dtype]) -> Self:
return self._r_elemwise_scalar_math[math.mod](s)
fn __imod__(inout self, s: Scalar[dtype]):
self = self.__mod__(s)
fn __pow__(self, p: Int) -> Self:
return self._elemwise_pow(p)
fn __ipow__(inout self, p: Int):
self = self.__pow__(p)
fn __lshift__(self, p: Int) -> Self:
if _mlirtype_is_eq[Scalar[dtype], Int32]():
var new_array = Self(self.numel)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_array._ptr.simd_store[simd_width](
idx[0], self._ptr.simd_load[simd_width](idx[0]) << p
)
elementwise[1, simdwidthof[dtype](), wrapper](self.numel)
return new_array
else:
print("Error: You can only shift int arrays")
return self
fn __rshift__(self, p: Int) -> Self:
if _mlirtype_is_eq[Scalar[dtype], Int32]():
var new_array = Self(self.numel)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_array._ptr.simd_store[simd_width](
idx[0], self._ptr.simd_load[simd_width](idx[0]) >> p
)
elementwise[1, simdwidthof[dtype](), wrapper](self.numel)
return new_array
else:
print("Error: You can only shift int arrays")
return self
fn __ilshift__(inout self, p: Int):
self = self.__lshift__(p)
fn __irshift__(inout self, p: Int):
self = self.__rshift__(p)
fn __and__(self, other: Self) -> Self:
if ~_mlirtype_is_eq[Scalar[dtype], Float64]():
var new_array = Self(self.numel)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_array._ptr.simd_store[simd_width](
idx[0],
self._ptr.simd_load[simd_width](idx[0])
& other._ptr.simd_load[simd_width](idx[0]),
)
elementwise[1, simdwidthof[dtype](), wrapper](self.numel)
return new_array
else:
print("Error: You can only AND int or bool arrays")
return self
fn __iand__(inout self, other: Self):
self = self.__and__(other)
fn __or__(self, other: Self) -> Self:
if ~_mlirtype_is_eq[Scalar[dtype], Float64]():
var new_array = Self(self.numel)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_array._ptr.simd_store[simd_width](
idx[0],
self._ptr.simd_load[simd_width](idx[0])
| other._ptr.simd_load[simd_width](idx[0]),
)
elementwise[1, simdwidthof[dtype](), wrapper](self.numel)
return new_array
else:
print("Error: You can only AND int or bool arrays")
return self
fn __ior__(inout self, other: Self):
self = self.__or__(other)
fn __xor__(self, other: Self) -> Self:
if ~_mlirtype_is_eq[Scalar[dtype], Float64]():
var new_array = Self(self.numel)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_array._ptr.simd_store[simd_width](
idx[0],
self._ptr.simd_load[simd_width](idx[0])
^ other._ptr.simd_load[simd_width](idx[0]),
)
elementwise[1, simdwidthof[dtype](), wrapper](self.numel)
return new_array
else:
print("Error: You can only AND int or bool arrays")
return self
fn __ixor__(inout self, other: Self):
self = self.__xor__(other)
fn __len__(self) -> Int:
return self.numel
fn __int__(self) -> Int:
return self.numel
fn __bool__(self) -> Bool:
return self.dtype == DType.bool
fn __str__(self) -> String:
var printStr: String = "["
var prec: Int = 4
for i in range(self.numel):
var val = self[i]
@parameter
if _mlirtype_is_eq[Scalar[dtype], Float64]():
var s: String = ""
var int_str: String
int_str = String(math.trunc(val).cast[DType.int32]())
if val < 0.0:
val = -val
var float_str: String
if math.mod(val, 1) == 0:
float_str = "0"
else:
float_str = String(math.mod(val, 1))[2 : prec + 2]
s = int_str + "." + float_str
if i == 0:
printStr += s
else:
printStr += " " + s
else:
if i == 0:
printStr += str(val)
else:
printStr += " " + str(val)
printStr += "]\n"
printStr += "Length:" + str(self.numel) + "," + " DType:" + str(dtype)
return printStr
fn to_numpy(self) raises -> PythonObject:
var np = Python.import_module("numpy")
var np_arr = np.zeros(self.numel)
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index, 1](
np_arr.__array_interface__["data"][0].__index__()
).value
)
)
memcpy(npArrayPtr, self._ptr, self.numel)
return np_arr
fn _reduce_sum(self) -> Self:
var reduced = Self(1)
alias simd_width: Int = simdwidthof[dtype]()
@parameter
fn vectorize_reduce[simd_width: Int](idx: Int) -> None:
reduced[0] += self._ptr.simd_load[simd_width](idx).reduce_add()
vectorize[vectorize_reduce, simd_width](self.numel)
return reduced
fn _elemwise_transform[
func: fn[dtype: DType, width: Int] (SIMD[dtype, width]) -> SIMD[dtype, width]
](self) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](
idx, func[dtype, simd_width](self._ptr.simd_load[simd_width](idx))
)
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn _elemwise_scalar_math[
func: fn[dtype: DType, width: Int] (
SIMD[dtype, width], SIMD[dtype, width]
) -> SIMD[dtype, width]
](self, s: Scalar[dtype]) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](
idx,
func[dtype, simd_width](
self._ptr.simd_load[simd_width](idx), SIMD[dtype, simd_width](s)
),
)
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn _r_elemwise_scalar_math[
func: fn[dtype: DType, width: Int] (
SIMD[dtype, width], SIMD[dtype, width]
) -> SIMD[dtype, width]
](self, s: Scalar[dtype]) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](
idx,
func[dtype, simd_width](
SIMD[dtype, simd_width](s), self._ptr.simd_load[simd_width](idx)
),
)
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn _elemwise_array_math[
func: fn[dtype: DType, width: Int] (
SIMD[dtype, width], SIMD[dtype, width]
) -> SIMD[dtype, width]
](self, other: Self) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](
idx,
func[dtype, simd_width](
self._ptr.simd_load[simd_width](idx),
other._ptr.simd_load[simd_width](idx),
),
)
vectorize[elemwise_vectorize, simd_width](self.numel)
return new_array
fn _elemwise_pow(self, p: Int) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(self.numel)
@parameter
fn tensor_scalar_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](
idx, math.pow(self._ptr.simd_load[simd_width](idx), p)
)
vectorize[tensor_scalar_vectorize, simd_width](self.numel)
return new_array
| devrel-extras/blogs/mojo-dunder/DunderArray.mojo | false |
<filename>devrel-extras/blogs/mojo-kmeans-from-python/bench_kmeans.mojo
from mojo_kmeans import Matrix, Kmeans
from mojo_kmeans.utils import list_to_matrix
from time import now
from python import Python
from benchmark import Unit, keep
import benchmark
def bench_mojo_kmeans(n_clusters: Int, borrowed data: Matrix[DType.float64]) -> Float64:
mojo_model = Kmeans(k=n_clusters, max_iterations=10, verbose=False, run_till_max_iter=True)
t = now()
_ = mojo_model.fit(data)
t_mojo = Float64(now()-t)/1_000_000
return t_mojo
def bench_python_kmeans(n_clusters: Int, borrowed data: PythonObject) -> Float64:
Python.add_to_path(".")
py_kmeans = Python.import_module("python_kmeans")
py_model = py_kmeans.Kmeans(k=n_clusters, max_iterations=10, verbose=False, run_till_max_iter=True)
t = now()
_ = py_model.fit(data)
t_py = Float64(now()-t)/1_000_000
return t_py
def get_dataset(n_clusters: PythonObject, n_samples: PythonObject, n_features: PythonObject) -> PythonObject:
sklearn_datasets = Python.import_module("sklearn.datasets")
data_numpy = sklearn_datasets.make_blobs(n_samples=n_samples,
cluster_std=8,
centers=n_clusters,
n_features=n_features,
return_centers=True,
random_state=int(now()/1e10))
return data_numpy
def main():
np = Python.import_module("numpy")
Python.add_to_path(".")
py_utils = Python.import_module("python_kmeans.utils")
clusters_range = np.arange(5,185,15)
samples_range = np.arange(2000,24000,2000)
features_range = np.arange(200,4000,200)
verbose = True
benchImageDir = "benchdir"
res1 = Matrix(int(len(clusters_range)),2)
for idx in range(int(len(clusters_range))):
data = get_dataset(clusters_range[idx],samples_range[0],features_range[0])[0]
mojo_data = Matrix.from_numpy(data)
res1[idx,0] = bench_mojo_kmeans(int(clusters_range[idx]),mojo_data)
res1[idx,1] = bench_python_kmeans(int(clusters_range[idx]),data)
x_label = "Numbers of Clusters"
fig_label = "Samples: "+str(samples_range[0])+" Features: "+str(features_range[0])
py_utils.plot_bench(res1.to_numpy(),
clusters_range,
x_label,
fig_label,
benchImageDir+"/num_clusters.png")
py_utils.plot_speedups(res1.to_numpy(),
clusters_range,
x_label,
fig_label,
benchImageDir+"/num_clusters_speedup.png")
print("Numbers of Clusters speedups:")
print(res1[:,1]/res1[:,0])
res2 = Matrix(int(len(samples_range)),2)
for idx in range(int(len(samples_range))):
data = get_dataset(clusters_range[5],samples_range[idx],features_range[0])[0]
mojo_data = Matrix.from_numpy(data)
res2[idx,0] = bench_mojo_kmeans(int(clusters_range[5]),mojo_data)
res2[idx,1] = bench_python_kmeans(int(clusters_range[5]),data)
x_label = "Number of Samples"
fig_label = "Clusters: "+str(clusters_range[5])+" Features: "+str(features_range[0])
py_utils.plot_bench(res2.to_numpy(),
samples_range,
x_label,
fig_label,
benchImageDir+"/num_samples.png")
py_utils.plot_speedups(res2.to_numpy(),
samples_range,
x_label,
fig_label,
benchImageDir+"/num_samples_speedup.png")
print("Number of Samples speedups:")
print(res2[:,1]/res2[:,0])
res3 = Matrix(int(len(features_range)),2)
for idx in range(int(len(features_range))):
data = get_dataset(clusters_range[0],samples_range[1],features_range[idx])[0]
mojo_data = Matrix.from_numpy(data)
res3[idx,0] = bench_mojo_kmeans(int(clusters_range[0]),mojo_data)
res3[idx,1] = bench_python_kmeans(int(clusters_range[0]),data)
x_label = "Number of Features"
fig_label = "Samples: "+str(samples_range[1])+" Clusters: "+str(clusters_range[0])
py_utils.plot_bench(res3.to_numpy(),
features_range,
x_label,
fig_label,
benchImageDir+"/num_features.png")
py_utils.plot_speedups(res3.to_numpy(),
features_range,
x_label,
fig_label,
benchImageDir+"/num_features_speedup.png")
print("Number of Features speedups:")
print(res3[:,1]/res3[:,0]) | devrel-extras/blogs/mojo-kmeans-from-python/bench_kmeans.mojo | false |
from mojo_kmeans import Matrix, Kmeans
from mojo_kmeans.utils import list_to_matrix
from time import now
from python import Python
def main():
Python.add_to_path(".")
py_kmeans = Python.import_module("python_kmeans")
py_utils = Python.import_module("python_kmeans.utils")
np = Python.import_module("numpy")
sklearn_datasets = Python.import_module("sklearn.datasets")
sklearn_cluster = Python.import_module("sklearn.cluster")
n_clusters = 10
n_samples = 3000
n_features = 200
plot_result = True
verbose = True
X = sklearn_datasets.make_blobs(n_samples=n_samples,
cluster_std=5,
centers=n_clusters,
n_features=n_features,
return_centers=True,
random_state=int(now()/1e10))
data = Matrix.from_numpy(X[0])
# Common arguments:
max_iterations = 100
print("\n======== Mojo Kmeans ========")
mojo_model = Kmeans(k=n_clusters)
t = now()
mojo_centroids = mojo_model.fit(data)
t_mojo = Float64(now()-t)/1_000_000
print('Mojo Kmeans complete (ms):',t_mojo)
print("\n======== Python Kmeans ========")
py_model = py_kmeans.Kmeans(k=n_clusters)
t = now()
py_centroids = py_model.fit(X[0])
t_py = Float64(now()-t)/1_000_000
print('Python Kmeans complete (ms):',t_py)
print("\n======== SKLearn Kmeans ========")
verbose_num = 1
if not verbose:
verbose_num = 0
sklearn_model = sklearn_cluster.KMeans(n_clusters=n_clusters,
max_iter=max_iterations,
verbose=verbose_num,
tol=0)
t = now()
sklearn_centroids = sklearn_model.fit(X[0])
t_sklearn = Float64(now()-t)/1_000_000
print('Python Kmeans complete (ms):',t_sklearn)
print()
print("Config:")
print("n_clusters =",n_clusters,"\nn_samples = ",n_samples,"\nn_features = ",n_features)
print()
print("Speedup Mojo vs. Python:",t_py/t_mojo)
print("Speedup Mojo vs. SKLearn:",t_sklearn/t_mojo)
print()
print("Comparing final inertia:")
print("Mojo kmeans final inertia:", mojo_model.inertia)
print("Python kmeans final inertia:", py_model.inertia)
print("SKlearn kmeans final inertia:", sklearn_model.inertia_)
if plot_result:
mojo_centroids_matrix = list_to_matrix[data.dtype](mojo_centroids).to_numpy()
py_utils.plot_clusters(X[0], X[1], mojo_centroids_matrix, py_centroids,X[2]) | devrel-extras/blogs/mojo-kmeans-from-python/run_kmeans.mojo | false |
from .matrix import Matrix
from .utils import list_to_matrix
from algorithm import vectorize, parallelize
from random import random_si64, random_float64, seed
from memory import memcpy
from sys import info
import math
from time import now
from python import Python
struct Kmeans[dtype: DType=DType.float64]():
var k: Int
var max_iterations: Int
var tol: Scalar[dtype]
var centroids: List[Matrix[dtype]]
var inertia: Scalar[dtype]
var verbose: Bool
var run_till_max_iter: Bool
alias simd_width: Int=4*simdwidthof[dtype]()
fn __init__(inout self,
k: Int=8,
max_iterations: Int=300,
tol: Scalar[dtype]=1e-4,
rng_seed: Int=42,
verbose: Bool=True,
run_till_max_iter: Bool=False):
self.k=k # Number of clusters
self.max_iterations=max_iterations # Maximum number of iterations to run the algorithm
self.tol=tol # Tolerance for convergence. Stop if the change in inertia is less than tol.
self.centroids=List[Matrix[dtype]](capacity=k) # List to store the centroids of clusters
self.inertia=0.0 # Measure of the total distance of each point to its assigned centroid
self.verbose=verbose # Controls whether to print detailed debug statements
self.run_till_max_iter=run_till_max_iter # Run till max_iterations even if converged
seed(rng_seed) # Seed for random number generation, for reproducibility
# Calculate squared Euclidean distance from each data point to each centroid
fn distance_norm(self, data: Matrix[dtype],
inout centroids_distances: Matrix[dtype]):
alias simd_width=self.simd_width
var simd_multiple=math.align_down(data.cols, simd_width)
@parameter
fn parallel_sqnorm(idx_centroid: Int):
var centroid=self.centroids[idx_centroid]
for idx_mat_row in range(data.rows):
var sq_norm=SIMD[dtype, simd_width].splat(0)
for idx_col in range(0, simd_multiple, simd_width):
sq_norm += math.pow(
data._matPtr.load[width=simd_width](idx_mat_row*data.cols+idx_col) -
centroid._matPtr.load[width=simd_width](idx_col),2)
for idx_col in range(simd_multiple, data.cols):
sq_norm[0] += math.pow(
data._matPtr.load[width=1](idx_mat_row*data.cols+idx_col) -
centroid._matPtr.load[width=1](idx_col),2
)
centroids_distances[idx_mat_row, idx_centroid]=sq_norm.reduce_add()
parallelize[parallel_sqnorm](len(self.centroids), info.num_performance_cores())
# Initialize centroids using the k-means++ algorithm to improve cluster quality
fn _kmeans_plus_plus(inout self, data: Matrix[dtype]) raises:
# Declare temporary variables
var probs: Matrix[dtype]
var cumulative_probs: Matrix[dtype]
# Add the first centroid randomly chosen from the data
self.centroids.append(data[int(random_si64(0,data.rows)),:])
# Create a full matrix for distance calculations; start with infinity
var centroids_distances=Matrix[dtype](data.rows, self.k, math.limit.inf[dtype]())
for idx_c in range(1, self.k):
# Update distances for all points relative to the new set of centroids
self.distance_norm(data, centroids_distances)
# Find the minimum distance to any centroid for each point
var min_distances=centroids_distances.min[axis=1]()
# Probability of selecting next centroid is proportional to squared distance
probs=min_distances / min_distances.sum()
# Cumulative probabilities for selection
cumulative_probs=probs.cumsum()
# Select the next centroid based on cumulative probabilities
var rand_prob=random_float64().cast[dtype]()
for i in range(len(cumulative_probs)):
if rand_prob < cumulative_probs[i]:
self.centroids.append(data[i,:])
break
# Lloyd's algorithm: Recompute centroids and assign points to the nearest cluster
fn _lloyds_iteration(inout self, data: Matrix[dtype],
inout centroids_distances: Matrix[dtype]) raises:
# Update distances based on current centroids
self.distance_norm(data, centroids_distances)
# Assign each point to the nearest centroid
var labels=centroids_distances.argmin(axis=1)
# Recalculate centroids as the mean of all points assigned to each centroid
for idx in range(self.k):
# Check if any points are assigned to this cluster
self.centroids[idx]=data.mean(where=labels==idx) if (labels==idx).sum() > 0 else self.centroids[idx]
# Compute new inertia as the sum of squared distances to the nearest centroid
self.inertia=(centroids_distances.min[axis=1]()).sum()
if self.verbose:
print(", inertia:", self.inertia)
# Main method to fit the k-means model to the provided data
fn fit(inout self, data: Matrix[dtype]) raises -> List[Matrix[dtype]]:
# Initialize distance matrix
var centroids_distances=Matrix[dtype](data.rows, self.k, math.limit.inf[dtype]())
# Initialize centroids using k-means++
self._kmeans_plus_plus(data)
var previous_inertia=self.inertia
for i in range(self.max_iterations):
if self.verbose:
print("Iteration:", i, end='')
previous_inertia=self.inertia
# Perform an iteration of Lloyd's algorithm
self._lloyds_iteration(data, centroids_distances)
if math.abs(previous_inertia - self.inertia) < self.tol and not self.run_till_max_iter:
print("Converged at iteration:",i,
"Inertia change less than tol:",self.tol,
"\n Final inertia:",self.inertia)
break
if i == self.max_iterations:
print("Converged at iteration:",i,"Max iterations reached",self.max_iterations)
return self.centroids | devrel-extras/blogs/mojo-kmeans-from-python/mojo_kmeans/kmeans.mojo | false |
from math import mul, div, mod, add, trunc, align_down, align_down_residual
from memory import memset_zero, memcpy
from sys.info import simdwidthof
from algorithm import vectorize
from algorithm.functional import elementwise
from algorithm.reduction import max, min, sum, cumsum, mean, argmin
from random import rand
from sys.intrinsics import strided_load
from python import Python
import benchmark
from benchmark import Unit
from testing import assert_true, assert_equal
from buffer import Buffer, NDBuffer
from buffer.list import DimList
struct Matrix[dtype: DType = DType.float64](Stringable, CollectionElement, Sized):
var _matPtr: DTypePointer[dtype]
var rows: Int
var cols: Int
alias simd_width: Int = 4*simdwidthof[dtype]()
@always_inline
fn __init__(inout self, rows: Int, cols:Int):
self._matPtr = DTypePointer[dtype].alloc(rows*cols)
self.rows = rows
self.cols = cols
memset_zero[dtype](self._matPtr, self.rows*self.cols)
fn __init__(inout self, rows: Int, cols:Int, val: Scalar[dtype]):
alias simd_width = self.simd_width
self._matPtr = DTypePointer[dtype].alloc(rows*cols)
self.rows = rows
self.cols = cols
@parameter
fn splat_val[simd_width: Int](idx: Int) -> None:
self._matPtr.store[width=simd_width](idx, self._matPtr.load[width=simd_width](idx).splat(val))
vectorize[splat_val, simd_width](self.rows*self.cols)
@always_inline
fn __init__(inout self, other: Self):
self.rows = other.rows
self.cols = other.cols
self._matPtr = DTypePointer[dtype].alloc(len(other))
memcpy(self._matPtr, other._matPtr, len(other))
@always_inline
fn __init__(inout self, elems: Int):
self._matPtr = DTypePointer[dtype].alloc(elems)
self.rows = 1
self.cols = elems
memset_zero[dtype](self._matPtr, self.rows*self.cols)
@always_inline
fn __init__(inout self, rows: Int, cols:Int, _matPtr: DTypePointer[dtype]):
self._matPtr = _matPtr
self.rows = rows
self.cols = cols
@always_inline
fn __init__(inout self, rows: Int, cols:Int, *data: Scalar[dtype]):
var data_len = len(data)
self.rows = rows
self.cols = cols
self._matPtr = DTypePointer[dtype].alloc(data_len)
for i in range(data_len):
self._matPtr[i] = data[i]
@always_inline
fn __init__(inout self, rows: Int, cols:Int, owned list: List[Scalar[dtype]]):
var list_len = len(list)
self.rows = rows
self.cols = cols
self._matPtr = DTypePointer[dtype].alloc(list_len)
for i in range(list_len):
self._matPtr[i] = list[i]
@always_inline
fn __init__(inout self, dims: StaticIntTuple[2], vals: List[Scalar[dtype]]):
var list_len = len(vals)
self.rows = dims[0]
self.cols = dims[1]
self._matPtr = DTypePointer[dtype].alloc(list_len)
for i in range(list_len):
self._matPtr[i] = vals[i]
@always_inline
fn __copyinit__(inout self, other: Self):
self.rows = other.rows
self.cols = other.cols
self._matPtr = DTypePointer[dtype].alloc(self.rows*self.cols)
memcpy(self._matPtr, other._matPtr, self.rows*self.cols)
fn __moveinit__(inout self, owned existing: Self):
self._matPtr = existing._matPtr
self.rows = existing.rows
self.cols = existing.cols
existing.rows = 0
existing.cols = 0
existing._matPtr = DTypePointer[dtype]()
fn __del__(owned self):
self._matPtr.free()
fn __setitem__(inout self, elem: Int, val: Scalar[dtype]):
self._matPtr.store[width=1](elem, val)
fn __setitem__(inout self, row: Int, col:Int, val: SIMD[dtype,1]):
return self._matPtr.store[width=1](row*self.cols+col, val)
@always_inline
fn __getitem__(self, idx: Int) -> SIMD[dtype, 1]:
return self._matPtr.load(idx)
@always_inline
fn __getitem__(self, x: Int, y: Int) -> SIMD[dtype,1]:
return self._matPtr.load(x * self.cols + y)
@always_inline
fn __getitem__(self, owned row_slice: Slice, col: Int) -> Self:
return self.__getitem__(row_slice, slice(col,col+1))
@always_inline
fn __getitem__(self, row: Int, owned col_slice: Slice) -> Self:
return self.__getitem__(slice(row,row+1),col_slice)
@always_inline
fn __getitem__(self, owned row_slice: Slice, owned col_slice: Slice) -> Self:
self._adjust_row_slice_(row_slice)
self._adjust_col_slice_(col_slice)
var src_ptr = self._matPtr
var dest_mat = Self(row_slice.__len__(),col_slice.__len__())
alias simd_width: Int = self.simd_width
for idx_rows in range(row_slice.__len__()):
src_ptr = self._matPtr.offset(row_slice[idx_rows]*self.cols+col_slice[0])
@parameter
fn slice_col_vectorize[simd_width: Int](idx: Int) -> None:
dest_mat._matPtr.store[width=simd_width](idx+idx_rows*col_slice.__len__(),src_ptr.simd_strided_load[width=simd_width](col_slice.step))
src_ptr = src_ptr.offset(simd_width*col_slice.step)
vectorize[slice_col_vectorize, simd_width](col_slice.__len__())
return dest_mat
@always_inline
fn _adjust_row_slice_(self, inout span: Slice):
if span.start < 0:
span.start = self.rows + span.start
if not span._has_end():
span.end = self.rows
elif span.end < 0:
span.end = self.rows+ span.end
if span.end > self.rows:
span.end = self.rows
fn _adjust_col_slice_(self, inout span: Slice):
if span.start < 0:
span.start = self.cols + span.start
if not span._has_end():
span.end = self.cols
elif span.end < 0:
span.end = self.cols + span.end
if span.end > self.cols:
span.end = self.cols
@always_inline
fn __len__(self) -> Int:
return self.rows*self.cols
@always_inline
fn __mul__(self, mat: Self)->Self:
return self._elemwise_tensor_tensor[mul](mat)
@always_inline
fn __add__(self, mat: Self)->Self:
return self._elemwise_tensor_tensor[add](mat)
@always_inline
fn __add__(self, val: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math.add](val)
@always_inline
fn __iadd__(inout self, other: Self):
alias simd_width: Int = self.simd_width
@parameter
fn tensor_tensor_vectorize[simd_width: Int](idx: Int) -> None:
self._matPtr.store[width=simd_width](idx, self._matPtr.load[width=simd_width](idx) + other._matPtr.load[width=simd_width](idx))
vectorize[tensor_tensor_vectorize, simd_width](len(self))
@always_inline
fn __truediv__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math.div](s)
@always_inline
fn __truediv__(self, mat: Self)->Self:
return self._elemwise_tensor_tensor[div](mat)
@always_inline
fn __pow__(self, p: Int)->Self:
return self._elemwise_pow(p)
@always_inline
fn __eq__(self, val: Int) -> Self:
alias simd_width = self.simd_width
var bool_float_array = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
var iters = SIMD[dtype, simd_width](0)
bool_float_array._matPtr.store[width=simd_width](idx, (self._matPtr.load[width=simd_width](idx) == val).select(iters+1,iters))
vectorize[elemwise_vectorize, self.simd_width](len(self))
return bool_float_array
@always_inline
fn __itruediv__(inout self, s: Scalar[dtype]):
alias simd_width = self.simd_width
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
self._matPtr.store[width=simd_width](idx, math.div[dtype, simd_width](self._matPtr.load[width=simd_width](idx), SIMD[dtype, simd_width](s)))
vectorize[elemwise_vectorize, simd_width](len(self))
fn _transpose_order(self) -> DTypePointer[dtype]:
var newPtr = DTypePointer[dtype].alloc(self.rows*self.cols)
alias simd_width: Int = self.simd_width
for idx_col in range(self.cols):
var tmpPtr = self._matPtr.offset(idx_col)
@parameter
fn convert[simd_width: Int](idx: Int) -> None:
newPtr.store[width=simd_width](idx+idx_col*self.rows, tmpPtr.simd_strided_load[width=simd_width](self.cols))
tmpPtr = tmpPtr.offset(simd_width*self.cols)
vectorize[convert, simd_width](self.rows)
return newPtr
fn center(self) -> Self:
alias simd_width = self.simd_width
var centered_data = Self(self.rows, self.cols)
var mean_array = self.mean[axis=0]()
print(mean_array)
for idx_mat_row in range(self.rows):
@parameter
fn center[simd_width: Int](idx: Int) -> None:
centered_data._matPtr.store[width=simd_width](idx_mat_row*self.cols+idx, self._matPtr.load[width=simd_width](idx_mat_row*self.cols+idx)-mean_array._matPtr.load[width=simd_width](idx))
vectorize[center, simd_width](len(mean_array))
return centered_data
@always_inline
fn transpose(self) -> Matrix[dtype]:
return Matrix[dtype](self.cols, self.rows, self._transpose_order())
@always_inline
fn fill_val(inout self, val: SIMD[dtype,1])->None:
alias simd_width = self.simd_width
@parameter
fn splat_val[simd_width: Int](idx: Int) -> None:
self._matPtr.store[width=simd_width](idx, self._matPtr.load[width=simd_width](idx).splat(val))
vectorize[splat_val, simd_width](self.rows*self.cols)
@always_inline
fn zero(inout self)->None:
memset_zero[dtype](self._matPtr, len(self))
@always_inline
fn sum(self) -> Scalar[dtype]:
var buf = Buffer[dtype](self._matPtr, len(self))
return sum(buf)
@always_inline
fn min[axis: Int = 1](self) -> Self:
var new_mat = Self(self.rows,1)
var self_buf = NDBuffer[dtype,2](self._matPtr, DimList(self.rows, self.cols))
var new_mat_buf = NDBuffer[dtype,2](new_mat._matPtr, DimList(new_mat.rows))
min[reduce_axis=axis](self_buf, new_mat_buf)
return new_mat
@always_inline
fn sqrt(self)->Self:
alias simd_width = self.simd_width
var new_mat = Self(self.rows,self.cols)
@parameter
fn wrapper[simd_width: Int, rank: Int = 1](idx: StaticIntTuple[rank]):
new_mat._matPtr.store[width=simd_width](idx[0], math.sqrt(self._matPtr.load[width=simd_width](idx[0])))
elementwise[wrapper, simd_width, 1](len(self))
return new_mat
@always_inline
fn mean[axis: Int = 1](self) -> Self:
var new_mat: Self
if axis==0:
new_mat = Self(self.rows)
else:
new_mat = Self(self.cols)
var self_buf = NDBuffer[dtype,2](self._matPtr, DimList(self.rows, self.cols))
var new_mat_buf = NDBuffer[dtype,2](new_mat._matPtr, DimList(len(new_mat)))
mean[reduce_axis=axis](self_buf, new_mat_buf)
return new_mat
@always_inline
fn mean(self, where: Matrix[DType.index]) -> Self:
var dest_mat = Self(1, self.cols)
var counter = 0.0
for idx in range(self.rows):
if int(where[idx]) == 1:
dest_mat += self[idx,:]
counter+=1
return dest_mat/counter
@always_inline
fn argmin(self, axis:Int=1) raises -> Matrix[DType.index]:
var labels_mat = Matrix[DType.index](self.rows,1)
var self_buf = NDBuffer[dtype,2](self._matPtr, DimList(self.rows, self.cols))
var labels_mat_buf = NDBuffer[DType.index,2](labels_mat._matPtr, DimList(labels_mat.rows, 1))
argmin(self_buf, -1, labels_mat_buf)
return labels_mat
@always_inline
fn cumsum(self) -> Self:
var cumsum_mat = Self(self.rows,self.cols)
var self_buf = Buffer[self.dtype](self._matPtr, len(self))
var cumsum_buf = Buffer[self.dtype](cumsum_mat._matPtr, len(self))
cumsum(cumsum_buf, self_buf)
return cumsum_mat
@staticmethod
fn rand(*dims: Int)->Self:
var _matPtr = DTypePointer[dtype].alloc(dims[0] * dims[1])
rand(_matPtr, dims[0] * dims[1])
return Self(dims[0],dims[1],_matPtr)
@staticmethod
fn from_numpy(np_array: PythonObject) raises -> Self:
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_array.__array_interface__['data'][0].__index__()).value
)
)
var rows = int(np_array.shape[0])
var cols = int(np_array.shape[1])
var _matPtr = DTypePointer[dtype].alloc(rows*cols)
memcpy(_matPtr, npArrayPtr, rows*cols)
var out = Self(rows,cols,_matPtr)
return out ^
fn to_numpy(self) raises -> PythonObject:
var np = Python.import_module("numpy")
var np_arr = np.zeros((self.rows,self.cols))
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_arr.__array_interface__['data'][0].__index__()).value
)
)
memcpy(npArrayPtr, self._matPtr, len(self))
return np_arr ^
fn print_linear(self):
print("[",end="")
for i in range(self.rows*self.cols):
if i>0:
print(" ",end="")
print(self._matPtr[i],end="")
print("]\n")
fn __str__(self) -> String:
var rank:Int = 2
var prec:Int = 4
var printStr:String = ""
if self.rows == 1:
rank = 1
var rows:Int=0
var cols:Int=0
if rank==0 or rank>3:
print("Error: Tensor rank should be: 1,2, or 3. Tensor rank is ", rank)
return ""
if rank==1:
rows = 1
cols = self.cols
if rank==2:
rows = self.rows
cols = self.cols
var val:Scalar[dtype]=0.0
var ctr: Int = 0
printStr+=""
for i in range(rows):
if rank>1:
if i==0:
printStr+="["
else:
printStr+="\n "
printStr+="["
for j in range(cols):
if rank==1:
val = self[j]
if rank==2:
val = self[i,j]
if dtype != DType.bool and dtype != DType.index:
var int_str: String
if val >= 0.0:
int_str = " "+str(trunc(val).cast[DType.index]())
else:
# val = math.abs(val)
int_str = str(trunc(val).cast[DType.index]())
var float_str: String = ""
if mod(val,1)==0:
float_str = "0"
else:
try:
float_str = str(mod(val,1)).split('.')[-1][0:4]
except:
return ""
var s: String = int_str+"."+float_str
if j==0:
printStr+=s
else:
printStr+=" "+s
else:
if j==0:
printStr+=str(val)
else:
printStr+=" "+str(val)
printStr+="]"
if rank>1:
printStr+="]"
printStr+="\n"
if rank>2:
printStr+="]"
printStr+="Matrix: "+str(self.rows)+'x'+str(self.cols)+" | "+"DType:"+str(dtype)+"\n"
return printStr
@always_inline
fn _elemwise_scalar_math[func: fn[dtype: DType, width: Int](SIMD[dtype, width],SIMD[dtype, width])->SIMD[dtype, width]](self, s: Scalar[dtype]) -> Self:
alias simd_width: Int = self.simd_width
var new_mat = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_mat._matPtr.store[width=simd_width](idx, func[dtype, simd_width](self._matPtr.load[width=simd_width](idx), SIMD[dtype, simd_width](s)))
vectorize[elemwise_vectorize, simd_width](len(self))
return new_mat
@always_inline
fn _elemwise_tensor_tensor[func: fn[dtype: DType, width: Int](SIMD[dtype, width],SIMD[dtype, width])->SIMD[dtype, width]](self, mat: Self) -> Self:
alias simd_width: Int = self.simd_width
var new_mat = Self(len(self))
@parameter
fn tensor_tensor_vectorize[simd_width: Int](idx: Int) -> None:
new_mat._matPtr.store[width=simd_width](idx, func[dtype, simd_width](self._matPtr.load[width=simd_width](idx), mat._matPtr.load[width=simd_width](idx)))
vectorize[tensor_tensor_vectorize, simd_width](len(self))
return new_mat
@always_inline
fn _elemwise_pow(self, p: Int) -> Self:
alias simd_width = self.simd_width
var new_mat = Self(self.rows,self.cols)
@parameter
fn pow_vectorize[simd_width: Int](idx: Int) -> None:
new_mat._matPtr.store[width=simd_width](idx, math.pow(self._matPtr.load[width=simd_width](idx), p))
vectorize[pow_vectorize, simd_width](len(self))
return new_mat | devrel-extras/blogs/mojo-kmeans-from-python/mojo_kmeans/matrix.mojo | false |
from .matrix import Matrix
fn list_to_matrix[dtype: DType](lst: List[Matrix[dtype]]) -> Matrix[dtype]:
var new_mat = Matrix[dtype](len(lst),len(lst[0]))
var tmpPtr = new_mat._matPtr
for arr in lst:
memcpy(tmpPtr, arr[]._matPtr, len(arr[]))
tmpPtr += len(arr[])
return new_mat | devrel-extras/blogs/mojo-kmeans-from-python/mojo_kmeans/utils.mojo | false |
from .kmeans import *
from .matrix import * | devrel-extras/blogs/mojo-kmeans-from-python/mojo_kmeans/__init__.mojo | false |
<filename>devrel-extras/blogs/mojo-pi-calculation/mojo_pi.mojo
import math
from memory import memset_zero, memcpy
from sys.info import simdwidthof
from algorithm import vectorize
from algorithm.functional import elementwise
from python import Python
from random import rand
struct MojoArray[dtype: DType = DType.float64](Stringable, Sized):
var _ptr: DTypePointer[dtype]
var numel: Int
alias simd_width: Int = simdwidthof[dtype]()
# Initializers
fn __init__(inout self, numel: Int):
self._ptr = DTypePointer[dtype].alloc(numel)
self.numel = numel
memset_zero[dtype](self._ptr, numel)
fn __init__(inout self, numel: Int, _ptr: DTypePointer[dtype]):
self._ptr = _ptr
self.numel = numel
fn __init__(inout self, *data: Scalar[dtype]):
self.numel = len(data)
self._ptr = DTypePointer[dtype].alloc(len(data))
for i in range(len(data)):
self._ptr[i] = data[i]
@staticmethod
fn rand(numel: Int)->Self:
var _ptr = DTypePointer[dtype].alloc(numel)
rand(_ptr, numel)
return Self(numel,_ptr)
fn __copyinit__(inout self, other: Self):
self._ptr = other._ptr
self.numel = other.numel
fn __getitem__(self, idx: Int) -> Scalar[dtype]:
return self._ptr.simd_load[1](idx)
fn __setitem__(self, idx: Int, val: Scalar[dtype]):
return self._ptr.simd_store[1](idx, val)
fn __neg__(self)->Self:
return self._elemwise_scalar_math[math.mul](-1.0)
fn __mul__(self, other: Self)->Self:
return self._elemwise_array_math[math.mul](other)
fn __mul__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math.mul](s)
fn __rmul__(self, s: Scalar[dtype])->Self:
return self*s
fn __add__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math.add](s)
fn __add__(self, other: Self)->Self:
return self._elemwise_array_math[math.add](other)
fn __radd__(self, s: Scalar[dtype])->Self:
return self+s
fn __sub__(self, s: Scalar[dtype])->Self:
return self._elemwise_scalar_math[math.sub](s)
fn __sub__(self, other: Self)->Self:
return self._elemwise_array_math[math.sub](other)
fn __rsub__(self, s: Scalar[dtype])->Self:
return -self+s
fn __len__(self) -> Int:
return self.numel
fn __le__(self, val: Scalar[dtype]) -> Self:
var bool_float_array = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
var iters = SIMD[dtype, simd_width](0)
bool_float_array._ptr.simd_store[simd_width](idx, (self._ptr.simd_load[simd_width](idx) <= val).select(iters+1,iters))
vectorize[elemwise_vectorize, self.simd_width](len(self))
return bool_float_array
fn __gt__(self, val: Scalar[dtype]) -> Self:
var bool_float_array = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
var iters = SIMD[dtype, simd_width](0)
bool_float_array._ptr.simd_store[simd_width](idx, (self._ptr.simd_load[simd_width](idx) > val).select(iters+1,iters))
vectorize[elemwise_vectorize, self.simd_width](len(self))
return bool_float_array
@staticmethod
fn from_numpy(np_array: PythonObject) raises->Self:
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_array.__array_interface__['data'][0].__index__()).value
)
)
var numel = int(np_array.shape[0])
var _ptr = DTypePointer[dtype].alloc(numel)
memcpy(_ptr, npArrayPtr, numel)
return Self(numel,_ptr)
fn to_numpy(self) raises->PythonObject:
var np = Python.import_module("numpy")
var np_arr = np.zeros(len(self))
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_arr.__array_interface__['data'][0].__index__()).value
)
)
memcpy(npArrayPtr, self._ptr, len(self))
return np_arr
fn __str__(self)->String:
var s:String = ""
s += "["
for i in range(len(self)):
if i>0:
s+=" "
s+=self._ptr[i]
s+="]"
return s
fn sqrt(self)->Self:
return self._elemwise_transform[math.sqrt]()
fn sum(self)->Scalar[dtype]:
var s = SIMD[dtype, self.simd_width](0)
@parameter
fn vectorize_reduce[simd_width: Int](idx: Int) -> None:
s += self._ptr.simd_load[self.simd_width](idx)
vectorize[vectorize_reduce, self.simd_width](len(self))
return s.reduce_add()
fn __pow__(self, p: Scalar[dtype])->Self:
return self._elemwise_pow(p)
fn _elemwise_pow(self, p: Scalar[dtype]) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(len(self))
@parameter
fn tensor_scalar_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](idx, math.pow[dtype,dtype,simd_width](self._ptr.simd_load[simd_width](idx), SIMD[dtype,simd_width].splat(p)))
vectorize[tensor_scalar_vectorize, simd_width](len(self))
return new_array
fn _elemwise_transform[func: fn[dtype: DType, width: Int](SIMD[dtype, width])->SIMD[dtype, width]](self) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](idx, func[dtype, simd_width](self._ptr.simd_load[simd_width](idx)))
vectorize[elemwise_vectorize,simd_width](len(self))
return new_array
fn _elemwise_array_math[func: fn[dtype: DType, width: Int](SIMD[dtype, width],SIMD[dtype, width])->SIMD[dtype, width]](self, other: Self) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](idx, func[dtype, simd_width](self._ptr.simd_load[simd_width](idx), other._ptr.simd_load[simd_width](idx)))
vectorize[elemwise_vectorize, simd_width](len(self))
return new_array
fn _elemwise_scalar_math[func: fn[dtype: DType, width: Int](SIMD[dtype, width],SIMD[dtype, width])->SIMD[dtype, width]](self, s: Scalar[dtype]) -> Self:
alias simd_width: Int = simdwidthof[dtype]()
var new_array = Self(len(self))
@parameter
fn elemwise_vectorize[simd_width: Int](idx: Int) -> None:
new_array._ptr.simd_store[simd_width](idx, func[dtype, simd_width](self._ptr.simd_load[simd_width](idx), SIMD[dtype, simd_width](s)))
vectorize[elemwise_vectorize, simd_width](len(self))
return new_array
def main():
alias N = 1000000
plt = Python.import_module("matplotlib.pyplot")
fig = plt.figure()
fig.set_size_inches(8, 8)
ax = fig.add_subplot()
ax.set_xlim([-0.5,0.5])
ax.set_ylim([-0.5,0.5])
for i in range(0,N,1000):
x = MojoArray.rand(i)-0.5
y = MojoArray.rand(i)-0.5
r = (x**2 + y**2).sqrt()
inside = r <= 0.5
pi = 4.*inside.sum()/i
ax.cla()
title = ax.set_title("Mojo β€οΈ Pi\n"+r"$\pi$="+str(pi)[:5]+" Iter:"+str(i))
ax.set_xlim([-0.5,0.5])
ax.set_ylim([-0.5,0.5])
title.set_fontsize(24)
col = inside.to_numpy()
ax.scatter(x.to_numpy(),y.to_numpy(),4,col)
plt.pause(0.2)
ax.set_aspect('equal')
plt.draw() | devrel-extras/blogs/mojo-pi-calculation/mojo_pi.mojo | false |
<filename>devrel-extras/blogs/mojo-row-major-column-major/row_col_matrix.mojo
from math import mod, trunc, align_down, align_down_residual
from memory import memset_zero, memcpy
from sys.info import simdwidthof
from algorithm import vectorize
from algorithm.functional import elementwise
from random import rand
from sys.intrinsics import strided_load
from python import Python
import benchmark
from benchmark import Unit
from testing import assert_true, assert_equal
struct MojoMatrix[dtype: DType = DType.float64, is_row_major: Bool=True]():
var _matPtr: DTypePointer[dtype]
var rows: Int
var cols: Int
alias simd_width: Int = 4*simdwidthof[dtype]()
@always_inline
fn __init__(inout self, rows: Int, cols:Int):
self._matPtr = DTypePointer[dtype].alloc(rows*cols)
self.rows = rows
self.cols = cols
memset_zero[dtype](self._matPtr, self.rows*self.cols)
@always_inline
fn __init__(inout self, rows: Int, cols:Int, _matPtr: DTypePointer[dtype]):
self._matPtr = _matPtr
self.rows = rows
self.cols = cols
@always_inline
fn __init__(inout self, rows: Int, cols:Int, *data: Scalar[dtype]):
var data_len = len(data)
self.rows = rows
self.cols = cols
self._matPtr = DTypePointer[dtype].alloc(data_len)
for i in range(data_len):
self._matPtr[i] = data[i]
@always_inline
fn __init__(inout self, rows: Int, cols:Int, owned list: List[Scalar[dtype]]):
var list_len = len(list)
self.rows = rows
self.cols = cols
self._matPtr = DTypePointer[dtype].alloc(list_len)
for i in range(list_len):
self._matPtr[i] = list[i]
@always_inline
fn __init__(inout self, dims: StaticIntTuple[2], vals: List[Scalar[dtype]]):
var list_len = len(vals)
self.rows = dims[0]
self.cols = dims[1]
self._matPtr = DTypePointer[dtype].alloc(list_len)
for i in range(list_len):
self._matPtr[i] = vals[i]
@always_inline
fn __copyinit__(inout self, other: Self):
self._matPtr = other._matPtr
self.rows = other.rows
self.cols = other.cols
@always_inline
fn __getitem__(self, idx: Int) -> SIMD[dtype,1]:
return self._matPtr.load(idx)
@always_inline
fn __getitem__(self, x: Int, y: Int) -> SIMD[dtype,1]:
return self._matPtr.load(x * self.cols + y)
@always_inline
fn __len__(self) -> Int:
return self.rows*self.cols
fn _transpose_order(self) -> DTypePointer[dtype]:
var newPtr = DTypePointer[dtype].alloc(self.rows*self.cols)
alias simd_width: Int = self.simd_width
for idx_col in range(self.cols):
var tmpPtr = self._matPtr.offset(idx_col)
@parameter
fn convert[simd_width: Int](idx: Int) -> None:
newPtr.store[width=simd_width](idx+idx_col*self.rows, tmpPtr.simd_strided_load[width=simd_width](self.cols))
tmpPtr = tmpPtr.offset(simd_width*self.cols)
vectorize[convert, simd_width](self.rows)
return newPtr
@always_inline
fn to_colmajor(self) raises -> MojoMatrix[dtype,False]:
assert_true(self.is_row_major == True, "Matrix must be in row-major format, to convert to column-major.")
return MojoMatrix[dtype, False](self.rows, self.cols, self._transpose_order())
@always_inline
fn transpose(self) -> MojoMatrix[dtype, is_row_major]:
return MojoMatrix[dtype, is_row_major](self.cols, self.rows, self._transpose_order())
@always_inline
fn mean(self, owned cols_list:List[Int]) -> Self:
var new_mat = Self(1,len(cols_list))
alias simd_width: Int = self.simd_width
var simd_sum = SIMD[dtype, simd_width](0)
var simd_multiple = align_down(self.rows, simd_width)
for idx_col in range(len(cols_list)):
simd_sum = simd_sum.splat(0)
if is_row_major:
var tmpPtr = self._matPtr.offset(cols_list[idx_col])
for idx_row in range(0, simd_multiple, simd_width):
simd_sum+=tmpPtr.simd_strided_load[width=simd_width](self.cols)
tmpPtr += simd_width*self.cols
for idx_row in range(simd_multiple, self.rows):
simd_sum[0] += tmpPtr.simd_strided_load[width=1](self.cols)
tmpPtr += self.cols
new_mat._matPtr[idx_col] = simd_sum.reduce_add()
else:
for idx_row in range(0, simd_multiple, simd_width):
simd_sum+=self._matPtr.load[width=simd_width](self.rows*cols_list[idx_col]+idx_row)
for idx_row in range(simd_multiple, self.rows):
simd_sum[0] += self._matPtr.load[width=1](self.rows*cols_list[idx_col]+idx_row)
new_mat._matPtr[idx_col] = simd_sum.reduce_add()
new_mat._matPtr[idx_col] /= self.rows
return new_mat
@staticmethod
fn from_numpy(np_array: PythonObject) raises -> Self:
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_array.__array_interface__['data'][0].__index__()).value
)
)
var rows = int(np_array.shape[0])
var cols = int(np_array.shape[1])
var _matPtr = DTypePointer[dtype].alloc(rows*cols)
memcpy(_matPtr, npArrayPtr, rows*cols)
return Self(rows,cols,_matPtr)
fn to_numpy(self) raises -> PythonObject:
var np = Python.import_module("numpy")
var np_arr = np.zeros((self.rows,self.cols))
var npArrayPtr = DTypePointer[dtype](
__mlir_op.`pop.index_to_pointer`[
_type = __mlir_type[`!kgen.pointer<scalar<`, dtype.value, `>>`]
](
SIMD[DType.index,1](np_arr.__array_interface__['data'][0].__index__()).value
)
)
memcpy(npArrayPtr, self._matPtr, len(self))
return np_arr
fn print_linear(self):
print("[",end="")
for i in range(self.rows*self.cols):
if i>0:
print(" ",end="")
print(self._matPtr[i],end="")
print("]\n")
fn __str__(self) -> String:
var rank:Int = 2
var prec:Int = 4
var printStr:String = ""
if self.rows == 1:
rank = 1
var rows:Int=0
var cols:Int=0
if rank==0 or rank>3:
print("Error: Tensor rank should be: 1,2, or 3. Tensor rank is ", rank)
return ""
if rank==1:
rows = 1
cols = self.cols
if rank==2:
rows = self.rows
cols = self.cols
var val:Scalar[dtype]=0.0
var ctr: Int = 0
printStr+=""
for i in range(rows):
if rank>1:
if i==0:
printStr+="["
else:
printStr+="\n "
printStr+="["
for j in range(cols):
if rank==1:
val = self[j]
if rank==2:
if is_row_major:
val = self[i,j]
else:
val = self._matPtr[i+j*rows]
var int_str: String
if val >= 0.0:
int_str = str(trunc(val).cast[DType.index]())
else:
int_str = "-"+str(trunc(val).cast[DType.index]())
val = -val
var float_str: String = ""
if mod(val,1)==0:
float_str = "0"
else:
try:
float_str = str(mod(val,1)).split('.')[-1]
except:
return ""
var s: String = int_str+"."+float_str
if j==0:
printStr+=s
else:
printStr+=" "+s
printStr+="]"
if rank>1:
printStr+="]"
printStr+="\n"
if rank>2:
printStr+="]"
var row_col_str: String
if is_row_major:
row_col_str = "Row Major"
else:
row_col_str = "Column Major"
printStr+="Matrix: "+str(self.rows)+'x'+str(self.cols)+" | "+"DType:"+str(dtype)+" | "+row_col_str+"\n"
return printStr
| devrel-extras/blogs/mojo-row-major-column-major/row_col_matrix.mojo | false |
<filename>devrel-extras/tweetorials/bitops/main.mojo
from math.bit import ctlz, cttz, bit_and, bit_not
from math import reduce_bit_count, rotate_bits_left
from testing import assert_equal
def main():
print("shift left 1 << 2:", 1 << 2, "shift right 3 >> 1:", 3 >> 1) # 4 and 1, resp.
print(
"rotate bits left/right in usigned SIMD",
rotate_bits_left[shift=1](SIMD[DType.uint8, 2](1, 2)),
) # [2, 4]
print("count leading zeros in binary '00000001'", ctlz(Int8(1))) # 7
print("count trailing zeros in binary '00000001'", cttz(Int8(1))) # 0
# `ctlz` and `cttz` work with integer types
assert_equal(ctlz(Int32(1)), ctlz(UInt32(1)))
# also SIMD vectors
print("count leading zeros:", ctlz(SIMD[DType.int8, 4](0, 1, 2, 3))) # [8, 7, 6, 6]
print("count leading zeros:", cttz(SIMD[DType.int8, 4](0, 1, 2, 3))) # [8, 0, 1, 0]
# Check for power of 2 using bit counts
def is_power_of_two_count(x: SIMD) -> SIMD[DType.bool, x.size]:
return ctlz(x) + cttz(x) == x.type.bitwidth() - 1
# More efficient way to check for power of 2 `x & (x - 1) == 0`
# while checking for sign
def is_power_of_two(x: SIMD) -> SIMD[DType.bool, x.size]:
# x & (x - 1) is the same as bit_and(x, x - 1)
# Note: x != 0 checks for sign
return (x & (x - 1) == 0) & (x != 0)
assert_equal(
is_power_of_two(SIMD[DType.int8, 4](-1, 0, 1, 2)),
SIMD[DType.bool, 4](False, False, True, True),
)
assert_equal(
is_power_of_two_count(SIMD[DType.int8, 4](-1, 0, 1, 2)),
SIMD[DType.bool, 4](False, False, True, True),
)
# Now given only `bit_and` i.e. `&` and `bit_not` i.e. `~`,
# we can implement `bit_or`, `bit_xor` and `bit_xnor`
def bit_or[
type: DType, size: Int
](a: SIMD[type, size], b: SIMD[type, size]) -> SIMD[type, size]:
# De Morgan's law: A β¨ B = Β¬(Β¬A β§ Β¬B)
# the same `bit_not(bit_and(bit_not(a), bit_not(b)))`
return ~(~a & ~b)
def bit_xor[
type: DType, size: Int
](a: SIMD[type, size], b: SIMD[type, size]) -> SIMD[type, size]:
# Exclusive OR: A β B = (A β§ Β¬B) β¨ (Β¬A β§ B)
# the same `bit_or(bit_and(a, bit_not(b)), bit_and(bit_not(a), b))`
return bit_or((a & ~b), (~a & b))
def bit_xnor[
type: DType, size: Int
](a: SIMD[type, size], b: SIMD[type, size]) -> SIMD[type, size]:
# XOR negation: A β B = Β¬ (A β B)
return ~bit_xor(a, b)
# number of 1s in bit XNOR of two vectors
def hamming_distance[
type: DType, size: Int
](a: SIMD[type, size], b: SIMD[type, size]) -> Int:
return reduce_bit_count(bit_xor(a, b))
# 0xFFFFFFFF bit representation is: 11111111 11111111 11111111 11111111
# 0x0F0F0F0F bit representation is: 00001111 00001111 00001111 00001111
# XNOR of 0xFFFFFFFF and 0x0F0F0F0F is: 11110000 11110000 11110000 11110000
# which has 16 ones
alias ui8 = DType.uint8
assert_equal(hamming_distance[ui8, 4](0xFFFFFFFF, 0x0F0F0F0F), 16)
assert_equal(hamming_distance[ui8, 4](0x00000000, 0x0F0F0F0F), 16)
genome1 = SIMD[ui8, 4].splat(0b11001010) # [202, 202, 202, 202]
genome2 = SIMD[ui8, 4].splat(0b10101010) # [170, 170, 170, 170]
genome3 = SIMD[ui8, 4](
0b11110000, 0b11100000, 0b11000000, 0b10000000
) # [240, 224, 192, 128]
def calculate_diversity(population: List[SIMD[ui8, 4]]) -> Float32:
n = len(population)
if n <= 1:
return 0.0
total_distance = 0.0
count = n * (n - 1) / 2
for i in range(n):
for j in range(i + 1, n):
total_distance += hamming_distance(population[i], population[j])
return total_distance / count
population = List[SIMD[ui8, 4]](genome1, genome2, genome3)
print(
"diversity of population", calculate_diversity(population)
) # 11.333333015441895
| devrel-extras/tweetorials/bitops/main.mojo | false |
from sys.ffi import external_call
from testing import assert_raises
alias c_char = UInt8
alias c_int = Int32
alias c_long = UInt64
alias c_void = UInt8
alias c_size_t = Int
alias SEEK_SET = 0
alias SEEK_END = 2
@register_passable("trivial")
struct FILE:
...
def fclose(stream: Pointer[FILE]):
debug_assert(stream != Pointer[FILE](), "File must be opened first")
ret = _fclose(stream)
if ret:
raise Error("File cannot be closed")
return
fn _fclose(stream: Pointer[FILE]) -> c_int:
return external_call["fclose", c_int, Pointer[FILE]](stream)
def fopen(path: String, mode: String) -> Pointer[FILE]:
path_ptr = _as_char_ptr(path)
mode_ptr = _as_char_ptr(mode)
stream = _fopen(path_ptr, mode_ptr)
if stream == Pointer[FILE]():
raise Error("Cannot open the file")
mode_ptr.free()
path_ptr.free()
return stream
fn _fopen(path: Pointer[c_char], mode: Pointer[c_char]) -> Pointer[FILE]:
return external_call[
"fopen",
Pointer[FILE],
Pointer[c_char],
Pointer[c_char],
](path, mode)
fn _as_char_ptr(s: String) -> Pointer[c_char]:
var nelem = len(s)
var ptr = Pointer[c_char]().alloc(nelem + 1) # +1 for null termination
for i in range(len(s)):
ptr.store(i, ord(s[i]))
ptr.store(nelem, 0) # null-terminate the string
return ptr
fn _fseek(stream: Pointer[FILE], offset: c_long, whence: c_int) -> c_int:
return external_call["fseek", c_int, Pointer[FILE], c_long, c_int](
stream, offset, whence
)
def fseek(stream: Pointer[FILE], offset: UInt64 = 0, whence: Int32 = SEEK_END):
debug_assert(stream != Pointer[FILE](), "File must be opened first")
ret = _fseek(stream, offset, whence)
if ret:
fclose(stream)
raise Error("Error seeking in file")
return
fn ftell(stream: Pointer[FILE]) raises -> c_long:
debug_assert(stream != Pointer[FILE](), "File must be opened")
var ret = external_call["ftell", c_long, Pointer[FILE]](stream)
if ret == -1:
raise Error("ftell failed")
return ret
fn _fread(
ptr: Pointer[c_void],
size: c_size_t,
nitems: c_size_t,
stream: Pointer[FILE],
) -> c_int:
return external_call[
"fread",
c_size_t,
Pointer[c_void],
c_size_t,
c_size_t,
Pointer[FILE],
](ptr, size, nitems, stream)
def fread(stream: Pointer[FILE], buf_read_size: Int = 1024) -> String:
debug_assert(stream != Pointer[FILE](), "File must be opened first")
# Choosing a large buffer for the sake of example.
# Exercise: Implement `read_file_to_end` in case
# the size is greater than the buffer size
buf = Pointer[c_char]().alloc(buf_read_size + 1) # +1 for null termination
count = _fread(buf.bitcast[c_void](), 1, buf_read_size, stream)
if count <= 0:
if count < 0:
fclose(stream)
raise Error("Cannot read data")
else:
print("End of file reached")
buf.store(count, 0) # null-terminate
# String owns the ptr so not need to call `free`
# String len is Int and count is Int32
return String(buf.bitcast[Int8](), int(count) + 1) # +1 include null-termintor
def main():
try:
fp = fopen("test.txt", "r")
fseek(fp)
size = ftell(fp)
print("file size in bytes:", size) # 36 bytes
# Reposition to the start of the file
fseek(fp, whence=SEEK_SET)
print(fread(fp))
_ = fclose(fp)
except:
print("Error has occured")
with assert_raises():
fp = fopen("test.txt", "r")
fclose(fp)
fclose(fp)
with assert_raises():
# test notexist
_ = fopen("notexist.txt", "r")
with assert_raises():
# test fseek and ftell fail cases
fp = fopen("test.txt", "r")
fseek(fp, -100)
_ = ftell(fp)
fclose(fp)
with assert_raises():
# test null ptr
null_ptr = Pointer[FILE]()
fclose(null_ptr)
_ = ftell(null_ptr)
fseek(null_ptr)
_ = fread(null_ptr)
| devrel-extras/tweetorials/ffi/external_call/fn_wrappers.mojo | false |
<filename>devrel-extras/tweetorials/ffi/external_call/raw0.mojo
from sys.ffi import external_call
alias c_char = UInt8
@register_passable("trivial")
struct FILE:
...
fn fopen(path: Pointer[c_char], mode: Pointer[c_char]) -> Pointer[FILE]:
return external_call[
"fopen",
Pointer[FILE],
Pointer[c_char],
Pointer[c_char],
](path, mode)
alias c_int = Int32
fn fclose(stream: Pointer[FILE]) -> c_int:
return external_call["fclose", c_int, Pointer[FILE]](stream)
fn as_char_ptr(s: String) -> Pointer[c_char]:
var nelem = len(s)
var ptr = Pointer[c_char]().alloc(nelem + 1) # +1 for null termination
for i in range(len(s)):
ptr.store(i, ord(s[i]))
ptr.store(nelem, 0) # null-terminate the string
return ptr
def main():
path_ptr = as_char_ptr("test.txt")
mode_ptr = as_char_ptr("r")
fp = fopen(path_ptr, mode_ptr)
if fp == Pointer[FILE]():
print("Error opening file")
return
_ = fclose(fp)
mode_ptr.free()
path_ptr.free()
| devrel-extras/tweetorials/ffi/external_call/raw0.mojo | false |
<filename>devrel-extras/tweetorials/ffi/external_call/raw1.mojo
from sys.ffi import external_call
alias c_char = UInt8
alias c_int = Int32
@register_passable("trivial")
struct FILE:
...
fn fopen(path: Pointer[c_char], mode: Pointer[c_char]) -> Pointer[FILE]:
return external_call[
"fopen",
Pointer[FILE],
Pointer[c_char],
Pointer[c_char],
](path, mode)
fn fclose(stream: Pointer[FILE]) -> c_int:
return external_call["fclose", c_int, Pointer[FILE]](stream)
fn as_char_ptr(s: String) -> Pointer[c_char]:
var nelem = len(s)
var ptr = Pointer[c_char]().alloc(nelem + 1) # +1 for null termination
for i in range(len(s)):
ptr.store(i, ord(s[i]))
ptr.store(nelem, 0) # null-terminate the string
return ptr
alias c_long = UInt64
fn fseek(stream: Pointer[FILE], offset: c_long, whence: c_int) -> c_int:
return external_call["fseek", c_int, Pointer[FILE], c_long, c_int](
stream, offset, whence
)
fn ftell(stream: Pointer[FILE]) -> c_long:
return external_call["ftell", c_long, Pointer[FILE]](stream)
alias c_void = UInt8
alias c_size_t = Int
fn fread(
ptr: Pointer[c_void],
size: c_size_t,
nitems: c_size_t,
stream: Pointer[FILE],
) -> c_int:
return external_call[
"fread",
c_size_t,
Pointer[c_void],
c_size_t,
c_size_t,
Pointer[FILE],
](ptr, size, nitems, stream)
def main():
path_ptr = as_char_ptr("test.txt")
mode_ptr = as_char_ptr("r")
fp = fopen(path_ptr, mode_ptr)
if fp == Pointer[FILE]():
print("Error opening file")
return
alias SEEK_END = 2
if fseek(fp, 0, SEEK_END):
print("Error seeking in file")
_ = fclose(fp)
return
size = ftell(fp)
if size == -1:
print("Error in ftell")
_ = fclose(fp)
return
print("file size in bytes:", size) # 36 bytes
# Reposition to the start of the file
alias SEEK_SET = 0
if fseek(fp, 0, SEEK_SET):
print("Error repositioning to the start of the file")
_ = fclose(fp)
return
# Choosing a large buffer for the sake of example.
# Exercise: Implement `read_file_to_end` in case
# the size is greater than the buffer size
buf_read_size = 1024
buf = Pointer[c_char]().alloc(buf_read_size + 1) # +1 for null termination
count = fread(buf.bitcast[c_void](), 1, buf_read_size, fp)
if count <= 0:
if count < 0:
_ = fclose(fp)
print("Cannot read data")
else:
print("End of file reached")
buf.store(count, 0) # null-terminate
# String owns the ptr so not need to call `free`
# String len is Int and count is Int32
print(String(buf.bitcast[Int8](), int(count) + 1)) # +1 include null-termintor
_ = fclose(fp)
mode_ptr.free()
path_ptr.free()
| devrel-extras/tweetorials/ffi/external_call/raw1.mojo | false |
fn external_call[
callee: StringLiteral, return_type: AnyRegType
]() -> return_type:
...
fn external_call[
callee: StringLiteral, return_type: AnyRegType, T0: AnyRegType
](arg0: T0) -> return_type:
...
fn external_call[
callee: StringLiteral,
return_type: AnyRegType,
T0: AnyRegType,
T1: AnyRegType,
](arg0: T0, arg1: T1) -> return_type:
...
| devrel-extras/tweetorials/ffi/external_call/signatures.mojo | false |
<filename>devrel-extras/tweetorials/ffi/external_call/struct_wrapper.mojo
from sys.ffi import external_call
from testing import assert_raises
alias c_char = UInt8
alias c_int = Int32
alias c_long = UInt64
alias c_void = UInt8
alias c_size_t = Int
alias SEEK_SET = 0
alias SEEK_END = 2
@register_passable("trivial")
struct FILE:
...
struct FileHandle:
var handle: Pointer[FILE]
fn __init__(inout self, path: String, mode: String) raises:
var path_ptr = self._as_char_ptr(path)
var mode_ptr = self._as_char_ptr(mode)
# https://man7.org/linux/man-pages/man3/fopen.3.html
var handle = external_call["fopen", Pointer[FILE]](
path_ptr, mode_ptr
)
mode_ptr.free()
path_ptr.free()
if handle == Pointer[FILE]():
raise Error("Error opening file")
self.handle = handle
@staticmethod
fn _as_char_ptr(s: String) -> Pointer[c_char]:
var nelem = len(s)
var ptr = Pointer[c_char]().alloc(nelem + 1) # +1 for null termination
for i in range(len(s)):
ptr.store(i, ord(s[i]))
ptr.store(nelem, 0) # null-terminate the string
return ptr
fn fclose(self) raises:
"""Safe and idiomatic wrapper https://man7.org/linux/man-pages/man3/fclose.3.html."""
debug_assert(self.handle != Pointer[FILE](), "File must be opened first")
var ret = external_call["fclose", c_int, Pointer[FILE]](self.handle)
if ret:
raise Error("Error in closing the file")
return
fn fseek(self, offset: UInt64 = 0, whence: Int32 = SEEK_END) raises:
"""Safe and idiomatic wrapper https://man7.org/linux/man-pages/man3/fseek.3.html."""
debug_assert(self.handle != Pointer[FILE](), "File must be opened first")
var ret = external_call["fseek", c_int, Pointer[FILE], c_long, c_int](
self.handle, offset, whence
)
if ret:
self.fclose()
raise Error("Error seeking in file")
return
fn ftell(self) raises -> UInt64:
"""Safe and idiomatic wrapper https://man7.org/linux/man-pages/man3/ftell.3p.html."""
debug_assert(self.handle != Pointer[FILE](), "File must be opened")
var ret = external_call["ftell", c_long, Pointer[FILE]](self.handle)
if ret == -1:
self.fclose()
raise Error("ftell failed")
return ret
@staticmethod
fn _fread(
ptr: Pointer[c_void],
size: c_size_t,
nitems: c_size_t,
stream: Pointer[FILE],
) -> c_int:
return external_call[
"fread",
c_size_t,
Pointer[c_void],
c_size_t,
c_size_t,
Pointer[FILE],
](ptr, size, nitems, stream)
fn fread(self, buf_read_size: Int = 1024) raises -> String:
"""Safe and idiomatic wrapper https://man7.org/linux/man-pages/man3/fread.3p.html."""
debug_assert(self.handle != Pointer[FILE](), "File must be opened first")
# Choosing a large buffer for the sake of example.
# Exercise: Implement `read_file_to_end` in case
# the size is greater than the buffer size
var buf = Pointer[c_char]().alloc(buf_read_size + 1) # +1 for null termination
var count = self._fread(buf.bitcast[c_void](), 1, buf_read_size, self.handle)
if count <= 0:
if count < 0:
self.fclose()
raise Error("Cannot read data")
else:
print("End of file reached")
buf.store(count, 0) # null-terminate
# String owns the ptr so not need to call `free`
# String len is Int and count is Int32
return String(buf.bitcast[Int8](), int(count) + 1) # +1 include null-termintor
fn fopen(path: String, mode: String = "r") raises -> FileHandle:
return FileHandle(path, mode)
def main():
try:
file = fopen("test.txt")
file.fseek(0)
size = file.ftell()
print("file size in bytes:", size) # 36 bytes
file.fseek(whence=SEEK_SET)
print(file.fread())
file.fclose()
except:
print("Error has occured")
# test double close
with assert_raises():
file = fopen("test.txt")
file.fclose()
file.fclose()
with assert_raises():
# test notexist
_ = fopen("notexist.txt")
with assert_raises():
# test fseek and ftell fail cases (and multi close)
file = fopen("test.txt")
file.fseek(-100)
_ = file.ftell()
file.fseek(whence=SEEK_SET)
_ = file.fread()
file.fclose()
| devrel-extras/tweetorials/ffi/external_call/struct_wrapper.mojo | false |
<filename>devrel-extras/tweetorials/higher-order-functions/hof.mojo
def main():
def echo(
func: def (String) -> String, s: String
) -> String:
return func(s)
def greet(name: String) -> String:
return "Hello, " + name
print(echo(greet, "world!")) # Hello, world!
# def is just syntax sugar for fn that makes the function able
# to throw and changes argument mutability for you.
# This is useful when working with dynamic and untyped logic,
# because untyped code can throw and do unpredictable things.
# fn is useful when you want control and certainty
fn echo_fn(
func: fn (String) -> String, s: String
) -> String:
return func(s)
fn greet_fn(name: String) -> String:
return "Hello, " + name
print(echo_fn(greet_fn, "world (fn)!")) # Hello, world (fn)!
# higher order map function
def map(
func: def (Int) -> Int, lst: List[Int]
) -> List[Int]:
ret = List[Int]()
for i in range(len(lst)):
ret.append(func(lst[i]))
return ret
def plus_one(x: Int) -> Int:
return x + 1
# starting with lst
lst = List[Int](0, 1, 2, 3, 4)
plus_one_lst = map(plus_one, lst) # [1, 2, 3, 4, 5]
# higher order filter function
def filter(
func: def (Int) -> Bool, lst: List[Int]
) -> List[Int]:
ret = List[Int]()
for i in range(len(lst)):
if func(lst[i]):
ret.append(lst[i])
return ret
def is_even(n: Int) -> Bool:
return n % 2 == 0
evens = filter(is_even, plus_one_lst) # [2, 4]
# higher order reduce function
def reduce(
func: def (Int, Int) -> Int,
lst: List[Int],
init: Int,
) -> Int:
acc = init
for i in range(len(lst)):
acc = func(acc, lst[i])
return acc
def add(x: Int, y: Int) -> Int:
return x + y
evens_sum = reduce(add, evens, 0)
print("Sum of evens is:", evens_sum)
def multiply(x: Int, y: Int) -> Int:
return x * y
evens_mul = reduce(multiply, evens, 1)
print("Multiple of evens is:", evens_mul)
| devrel-extras/tweetorials/higher-order-functions/hof.mojo | false |
from testing import assert_equal, assert_not_equal, assert_false
from sys.info import alignof
@value
@register_passable("trivial")
struct MyType(Stringable):
var x: Int
var y: SIMD[DType.float32, 4]
fn __str__(self) -> String:
return "MyType { " + str(self.x) + ", " + str(self.y) + " }"
def main():
# Unsafe Pointer
print("Create null pointer")
ptr = Pointer[Int]()
# or via
null_ptr = Pointer[Int]().get_null()
assert_equal(ptr, null_ptr, "ptr must be null")
print("ptr:", ptr) # 0x0
print("int(ptr):", int(ptr)) # 0
assert_equal(hex(int(ptr)), ptr, "hex representations must match")
print("Size of Int in bytes:", sizeof[Int]()) # 8 bytes
print("Int alignment in bytes:", alignof[Int]()) # 8 bytes
print("Size of Pointer[Int] in bytes:", sizeof[Pointer[Int]]()) # 8 bytes on x86-64
print("Pointer[Int] alignment in bytes:", alignof[Pointer[Int]]()) # 8 bytes
ptr = ptr.alloc(2) # heap allocates for 2 Ints (with 8 bytes alignment) and returns a new pointer
ptr.store(42)
assert_not_equal(ptr, null_ptr, "ptr is not null")
print("ptr.load():", ptr.load()) # 42
ptr2 = ptr.offset(1) # returns a new pointer ptr2 shifted by 1
ptr2.store(-42)
print("ptr2.load():", ptr2.load()) # -42
print("ptr.free() deallocates Int from heap but it doesn't become a null pointer")
ptr.free()
print("Note ptr2 has also been freed")
assert_not_equal(ptr, null_ptr, "ptr is not null")
print(
"Be careful: ptr.load() is UB and may load some random value each time the program is run:", ptr.load()
)
my_ptr = Pointer[MyType]()
print("Size of MyType in bytes:", sizeof[MyType]()) # 32 bytes
print("Size of Pointer[MyType] in bytes:", sizeof[Pointer[MyType]]()) # 8 bytes
print("MyType alignment in bytes:", alignof[MyType]()) # 16 bytes
print("Pointer[MyType] alignment in bytes:", alignof[Pointer[MyType]]()) # 8 bytes
# let's use a different alignment than the default 32 which is the size of `MyType`
my_ptr = my_ptr.alloc(1, alignment=31)
# in above we have allocated 62 bytes to ensure alignment.
y = SIMD[DType.float32, 4]()
for i in range(4):
y[i] = i
my_ptr.store(MyType(42, y))
print("my_ptr.load():", my_ptr.load()) # MyType { 42, [0.0, 1.0, 2.0, 3.0] }
my_ptr.free()
alias dtype = DType.int8
alias simd_width = simdwidthof[dtype]()
print("SIMD width for DType.int8:", simd_width) # 64 on my machine
my_dptr = DTypePointer[dtype].alloc(simd_width)
# fills with zero
memset_zero(my_dptr, simd_width)
print("Load a single element via .load():", my_dptr.load()) # 0
print("Load a simd vector via .load() with offset 0:", my_dptr.load[width=simd_width](0)) # [0, ..., 0]
vec = SIMD[dtype, simd_width]()
for i in range(simd_width):
vec[i] = i
my_dptr.store[width=simd_width](0, vec)
print(my_dptr.load[width=simd_width]()) # [0, 1, ..., 63]
my_dptr.free()
| devrel-extras/tweetorials/pointers/pointers.mojo | false |
from python import Python as py
from python.object import PythonObject
fn main() raises:
# When you use Python objects in your Mojo code,
# Mojo adds the PythonObject wrapper around the Python object
var py_lst: PythonObject = []
print("empty py_lst: ", py_lst) # []
for i in range(5):
py_lst.append(i)
print("py_lst:", py_lst) # [0, 1, 2, 3, 4]
print("python type:", py.type(py_lst)) # <class 'list'>
print(py.type([0, 1, 2, 3, 4])) # <class 'list'>
# Note without specifying `PythonObject` it's Mojo's ListLiteral
var mojo_lst = [0, 1, 2, 3, 4]
# which can be turned to python list
print("py.type(mojo_lst)", py.type(mojo_lst)) # <class 'list'>
# check identity with `is_type` same as python `is`
print("Are py.type(mojo_lst) and py.type(py_lst) the same type? ")
print(py.is_type(py.type(mojo_lst), py.type(py_lst))) # True
# Python Dictionary.
# This is not the same as python's `dict()` or `{}`
var d = py.dict()
d["hello"] = "world"
print(d["hello"]) # world
# make python dict via py.evaluate
var py_dict = py.evaluate("{'py_hello': 'py_world'}")
print("py_dict: ", py_dict) # py_dict: {'py_hello': 'py_world'}
# Note this assignment doesn't work:
# py_dict["py_hello"] = "py_bye"
# instead can do
print("Using `__getattr__('__setitem__')` to set the new value")
py_dict.__getattr__("__setitem__")("py_hello", "py_bye")
print("py_dict['py_hello'] = ", py_dict['py_hello']) # py_dict['py_hello'] = py_bye
| devrel-extras/tweetorials/py-obj/py.mojo | false |
import math
from python import Python
from testing import assert_equal, assert_not_equal
def main():
# Int32 is Scalar[DType.int32]
a = Int32(42)
b = Scalar[DType.int32](42)
assert_equal(a, b)
# Scalar[DType.int32] is SIMD[DType.int32, 1]
c = SIMD[DType.int32, 1](42)
assert_equal(b, c)
# initialize a SIMD vector of size (power of 2)
d = SIMD[DType.int32, 4](0, 1, 2, 3)
e = SIMD[DType.int32, 4]().splat(10) # [10, 10, 10, 10]
print(
d * e, d / e, d % e, d**e
) # [0, 10, 20, 30] [0, 0, 0, 0] [0, 1, 2, 3] [0, 1, 1024, 59049]
# shuffle takes a mask of permutation indices and permutes d accordingly
print(d.shuffle[1, 3, 2, 0]()) # [1, 3, 2, 0]
# joining / concatenating two SIMD vectors
print(d.join(e)) # [0, 1, 2, 3, 10, 10, 10, 10]
dd = d.cast[DType.bool]() # [False, True, True, True]
ee = ~e.cast[DType.bool]() # [False, False, False, False]
print(
dd & ee, dd | ee, dd ^ ee
) # [False, False, False, False] [False, True, True, True] [False, False, False, False]
# interleave combines two SIMD vectors into one by taking
# one element from the first and another from the second
# weaving the vectors together
print(d.interleave(e)) # [0, 10, 1, 10, 2, 10, 3, 10]
# deinterleave reverses it
new = d.interleave(e).deinterleave()
assert_equal(new[0], d)
assert_equal(new[1], e)
# dot product using SIMD `__mul__` and `reduce_add`
def dot_product(x: SIMD, y: SIMD[x.type, x.size]) -> Scalar[x.type]:
return (x * y).reduce_add()
assert_equal(dot_product(a, b), 42 * 42)
assert_equal(dot_product(d, e), 60)
# absolute value using `select`
def abs(x: SIMD) -> SIMD[x.type, x.size]:
# exercise: can this be more efficient
# depending on `type` i.e. unsigned or floats?
return (x >= 0).select(x, -x)
assert_equal(
abs(SIMD[DType.float32, 4](-1, -2, 0, 1)),
SIMD[DType.float32, 4](1, 2, 0, 1),
)
# softmax using `reduce_max`, `math.exp` and `reduce_add`
def softmax(x: SIMD) -> SIMD[x.type, x.size]:
xm = x - x.reduce_max()
exps = math.exp(xm)
return exps / exps.reduce_add()
# vector attention softmax(qk^T)v
def vector_attention[
size: Int
](
q: SIMD[DType.float32, size],
k: SIMD[DType.float32, size],
v: SIMD[DType.float32, size],
) -> SIMD[DType.float32, size]:
scale_factor = 1 / math.sqrt(len(k))
return softmax(dot_product(q, k) * scale_factor) * v
ret = vector_attention(
SIMD[DType.float32, 4](-4, 0.25, 3.14, 4),
SIMD[DType.float32, 4](1.1, -0.1, -9, 1),
SIMD[DType.float32, 4](1, 0.2, 3, 4),
)
print(ret) # [1.0, 0.2000, 3.0, 4.0]
# compare to torch scaled dot product attention
torch = Python.import_module("torch")
ret_pt = torch.nn.functional.scaled_dot_product_attention(
torch.tensor([-4, 0.25, 3.14, 4]).unsqueeze(0),
torch.tensor([1.1, -0.1, -9, 1]).unsqueeze(0),
torch.tensor([1, 0.2, 3, 4]).unsqueeze(0),
)
print(ret_pt.squeeze(0)) # tensor([1.0000, 0.2000, 3.0000, 4.0000])
| devrel-extras/tweetorials/simd/simd.mojo | false |
<filename>devrel-extras/tweetorials/variant/variant.mojo
from utils.variant import Variant
@value
struct Quit(CollectionElement):
fn display(self) -> String:
return "Quit"
@value
struct Move(CollectionElement):
var x: Int
var y: Int
fn display(self) -> String:
return "Move" + "(" + str(self.x) + ", " + str(self.y) + ")"
alias Message = Variant[Quit, Move]
fn visitor(msg: Message) raises -> String:
if msg.isa[Quit]():
return msg.get[Quit]().display()
elif msg.isa[Move]():
return msg.get[Move]().display()
else:
return Error("Unknown variant")
fn main() raises:
var m1 = Message(Quit())
var m2 = Message(Move(1, 2))
print(visitor(m1))
print(visitor(m2))
| devrel-extras/tweetorials/variant/variant.mojo | false |
<filename>devrel-extras/tweetorials/vectorize-parallelize/main.mojo
def main():
alias size = 10
alias type = DType.int32
alias simd_width = simdwidthof[type]()
# on my machine it is 4 i.e. 4 x int32 which is 128 SIMD register
print("simd_width:", simd_width)
x = DTypePointer[type].alloc(size)
for i in range(size):
x[i] = 42
# Note: x.load returns SIMD[type, width]
print("initialized x:", x.load[width=size]()) # [42, ..., 42]
print("manual SIMD print")
simd_multiple = size - size % simd_width # 10 - 10 % 4 = 8
for offset in range(0, simd_multiple, simd_width):
print(
"offset =",
offset,
"width =",
simd_width,
":",
x.load[width=simd_width](offset),
)
# outputs:
# offset = 0 width = 4 : [42, 42, 42, 42]
# offset = 4 width = 4 : [42, 42, 42, 42]
for offset in range(simd_multiple, size):
print(
"offset =",
offset,
"width = 1",
":",
x.load[width=1](),
)
# outputs:
# offset = 8 width = 1 : 42
# offset = 9 width = 1 : 42
# offset = 10 width = 1 : 42
print("vectorized SIMD print")
from algorithm import vectorize
# Note: Type of `offset` is `Int` which is used for indexing
@parameter
fn print_it[width: Int](offset: Int):
print(
"offset =",
offset,
"width =",
width,
":",
x.load[width=width](offset=offset),
)
vectorize[print_it, simd_width](size)
# outputs:
# offset = 0 width = 4 : [42, 42, 42, 42]
# offset = 4 width = 4 : [42, 42, 42, 42]
# offset = 8 width = 1 : 42
# offset = 9 width = 1 : 42
# Notice how much `vectorize` simplifies and
# takes care of the remainder
# `range(simd_multiple, size)` above and adjusts `width`
y = DTypePointer[type].alloc(size)
for j in range(size):
y[j] = -42
print("initialized y:", y.load[width=size]()) # [-42, ..., -42]
z = DTypePointer[type].alloc(size)
# initialize with 0
memset_zero(z, size)
@parameter
fn elementwise_sum[width: Int](offset: Int):
# elementwise sum formula is:
var x_simd_chunk = x.load[width=width](offset=offset)
print(
"[x] ",
"offset =",
offset,
"width = ",
width,
":",
x_simd_chunk,
)
var y_simd_chunk = y.load[width=width](offset=offset)
print(
"[y] ",
"offset =",
offset,
"width = ",
width,
":",
y_simd_chunk,
)
var val = x_simd_chunk + y_simd_chunk # SIMD sum
print(
"[x + y]",
"offset =",
offset,
"width = ",
width,
":",
val,
)
print("==============================================================")
z.store[width=width](offset=offset, val=val)
vectorize[elementwise_sum, simd_width](size)
# outputs:
# [x] offset = 0 width = 4 : [42, 42, 42, 42]
# [y] offset = 0 width = 4 : [-42, -42, -42, -42]
# [x + y] offset = 0 width = 4 : [0, 0, 0, 0]
# ==============================================================
# [x] offset = 4 width = 4 : [42, 42, 42, 42]
# [y] offset = 4 width = 4 : [-42, -42, -42, -42]
# [x + y] offset = 4 width = 4 : [0, 0, 0, 0]
# ==============================================================
# [x] offset = 8 width = 1 : 42
# [y] offset = 8 width = 1 : -42
# [x + y] offset = 8 width = 1 : 0
# ==============================================================
# [x] offset = 9 width = 1 : 42
# [y] offset = 9 width = 1 : -42
# [x + y] offset = 9 width = 1 : 0
# ==============================================================
print("elementwise sum result:", z.load[width=size]()) # [0, ..., 0]
# don't forget to free the allocated pointers
z.free()
y.free()
x.free()
import math
from algorithm import parallelize
alias large_size = size * size # 100
xx = DTypePointer[type].alloc(large_size)
# xx is [0, 1, ..., 99]
for i in range(large_size):
xx[i] = i
yy = DTypePointer[type].alloc(large_size)
# yy is [10, 10, ..., 10]
for i in range(large_size):
yy[i] = 10
zz = DTypePointer[type].alloc(large_size)
# initialize with 0
memset_zero(zz, large_size)
num_work_items = 2
print("num_work_items =", num_work_items)
chunk_size = math.div_ceil(large_size, num_work_items) # 50
print("chunk_size =", chunk_size)
# divides xx, yy into two arrayes of 50 elements each (xx_1, xx_2) and (yy_1, yy_2)
# and performs the vectorized elementwise sum using 2 threads in parallel
# i.e. (xx_1 + yy_1) and (xx_2 + yy_2) in parallel
# +-----------------------------------------+
# | Parallel Elementwise Sum |
# +-----------------------------------------+
# | |
# | +----------------+ |
# | | Thread 1 | |
# | | | |
# | Array 1 | xx_1 + yy_1 -> zz_1 |
# | | [0:50] | |
# | +----------------+ |
# | |
# | +----------------+ |
# | | Thread 2 | |
# | | | |
# | Array 2 | xx_2 + yy_2 -> zz_2 |
# | | [50:100] | |
# | +----------------+ |
# | |
# +-----------------------------------------+
# | Result: zz = [zz_1, zz_2] |
# | [10, 11, ..., 109] |
# +-----------------------------------------+
@parameter
fn parallel_elementwise_sum(thread_id: Int):
# NOTE: for parallelize do not include any
# I/O such as print which is not thread-safe
var start = thread_id * chunk_size
var end = math.min(start + chunk_size, large_size)
@parameter
fn _elementwise_sum[width: Int](offset: Int):
var val = xx.load[width=width](offset=start + offset) + yy.load[width=width](offset=start + offset)
zz.store[width=width](offset=start + offset, val=val)
vectorize[_elementwise_sum, simd_width](end - start)
parallelize[parallel_elementwise_sum](num_work_items)
print("parallel elementwise sum result:", zz.load[width=large_size]())
# output:
# [10, 11, ..., 109]
# don't forget to free the pointers
zz.free()
yy.free()
xx.free()
| devrel-extras/tweetorials/vectorize-parallelize/main.mojo | false |
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2023, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from math import mod, trunc
from tensor import Tensor
fn tensorprint[type: DType](t: Tensor[type]) -> None:
var rank = t.rank()
var dim0: Int = 0
var dim1: Int = 0
var dim2: Int = 0
if rank == 0 or rank > 3:
print("Error: Tensor rank should be: 1,2, or 3. Tensor rank is ", rank)
return
if rank == 1:
dim0 = 1
dim1 = 1
dim2 = t.dim(0)
if rank == 2:
dim0 = 1
dim1 = t.dim(0)
dim2 = t.dim(1)
if rank == 3:
dim0 = t.dim(0)
dim1 = t.dim(1)
dim2 = t.dim(2)
var val: SIMD[type, 1] = 0.0
for i in range(dim0):
if i == 0 and rank == 3:
print("[")
else:
if i > 0:
print()
for j in range(dim1):
if rank != 1:
if j == 0:
print_no_newline(" [")
else:
print_no_newline("\n ")
print_no_newline("[")
for k in range(dim2):
if rank == 1:
val = t[k]
if rank == 2:
val = t[j, k]
if rank == 3:
val = t[i, j, k]
var int_str = String(trunc(val).cast[DType.int32]())
var float_str = String(mod(val, 1))
var s = int_str + "." + float_str[2:6]
if k == 0:
print_no_newline(s)
else:
print_no_newline(" ", s)
print_no_newline("]")
if rank > 1:
print_no_newline("]")
print()
if rank == 3:
print("]")
print(
"Tensor shape:",
t.shape().__str__(),
", Tensor rank:",
rank,
",",
"DType:",
type.__str__(),
)
print()
fn main():
var t = Tensor[DType.float32](2, 2)
tensorprint(t)
| devrel-extras/videos/introduction-to-tensors/tensorutils.mojo | false |
<filename>devrel-extras/videos/introduction-to-tensors/__init__.mojo
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2023, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from .tensorutils import tensorprint
| devrel-extras/videos/introduction-to-tensors/__init__.mojo | false |
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2023, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from python import Python
fn main() raises:
var torch = Python.import_module("torch")
var x = torch.linspace(0, 10, 100)
var y = torch.sin(x)
plot(x, y)
def plot(x: PythonObject, y: PythonObject) -> None:
var plt = Python.import_module("matplotlib.pyplot")
plt.plot(x.numpy(), y.numpy())
plt.xlabel("x")
plt.ylabel("y")
plt.title("Plot of y = sin(x)")
plt.grid(True)
plt.show()
| devrel-extras/videos/mojo-plotter/main.mojo | false |
<filename>devrel-extras/workshops/mojo-for-python-developers/tensorprint.mojo
# *Copyright 2023 Modular, Inc: Licensed under the Apache License v2.0 with LLVM Exceptions.*
from tensor import Tensor, TensorShape, TensorSpec
from math import trunc, mod
fn tensorprint[type: DType](t: Tensor[type])->None:
let rank = t.rank()
var dim0:Int=0
var dim1:Int=0
var dim2:Int=0
if rank==0 or rank>3:
print("Error: Tensor rank should be: 1,2, or 3. Tensor rank is ", rank)
return
if rank==1:
dim0 = 1
dim1 = 1
dim2 = t.dim(0)
if rank==2:
dim0 = 1
dim1 = t.dim(0)
dim2 = t.dim(1)
if rank==3:
dim0 = t.dim(0)
dim1 = t.dim(1)
dim2 = t.dim(2)
var val:SIMD[type, 1]=0.0
for i in range(dim0):
if i==0 and rank==3:
print("[")
else:
if i>0:
print()
for j in range(dim1):
if rank!=1:
if j==0:
print_no_newline(" [")
else:
print_no_newline("\n ")
print_no_newline("[")
for k in range(dim2):
if rank==1:
val = t[k]
if rank==2:
val = t[j,k]
if rank==3:
val = t[i,j,k]
let int_str: String
if val > 0 or val == 0:
int_str = String(trunc(val).cast[DType.int32]())
else:
val = -val
int_str = "-"+String(trunc(val).cast[DType.int32]())
let float_str = String(mod(val,1))
let s = int_str+"."+float_str[2:6]
if k==0:
print_no_newline(s)
else:
print_no_newline(" ",s)
print_no_newline("]")
if rank>1:
print_no_newline("]")
print()
if rank==3:
print("]")
print("Tensor shape:",t.shape().__str__(),", Tensor rank:",rank,",","DType:", type.__str__()) | devrel-extras/workshops/mojo-for-python-developers/tensorprint.mojo | false |
<filename>dynamic_vector.mojo/all_tests.mojo
from tests.test_dynamic_vector import all_tests as test_dynamic_vector
from tests.test_dynamic_vector_slice import (
all_tests as test_dynamic_vector_slice,
)
from time import now
fn main() raises:
var start = now()
test_dynamic_vector()
var end = now()
print("All Dynamcic Vector tests passed in ", (end - start) / 1e6, "ms")
print()
var start2 = now()
test_dynamic_vector_slice()
var end2 = now()
print(
"All Dynamcic Vector Slice tests passed in ",
(end2 - start2) / 1e6,
"ms",
)
print()
print("total time: ", (end2 - start2 + end - start) / 1e6, "ms")
| dynamic_vector.mojo/all_tests.mojo | false |
<filename>dynamic_vector.mojo/slice_demo.mojo
from dynamic_vector import DynamicVector, DynamicVectorSlice
fn print_vec(vec: DynamicVector[Int], name: String) -> None:
print(name, "(size =", len(vec), end=") [")
for i in range(len(vec)):
if i == len(vec) - 1:
print(vec[i], end="]\n")
else:
print(vec[i], end=", ")
fn print_slice(vec: DynamicVectorSlice[Int], name: String) raises -> None:
print(name, "(size =", len(vec), end=") [")
for i in range(len(vec)):
if i == len(vec) - 1:
print(vec[i], end="]\n")
else:
print(vec[i], end=", ")
fn main() raises:
var vec = DynamicVector[Int](capacity=32)
for i in range(16):
vec.push_back(i)
print_vec(vec, "original vec")
# vec[0::2] doesn't work because of #1871 (https://github.com/modularml/mojo/issues/1871)
var slice_1 = vec.__getitem__(Slice(0, 16, 2))
print_slice(slice_1, "slice_1 = vec[0::2]")
var slice_2 = slice_1[0::2]
print_slice(slice_2, "slice_2 = slice_1[0::2]")
print()
slice_2[2] = 1000
print("after slice_2[2] = 1000")
print_slice(slice_2, "slice_2 = slice_1[0::2]")
print_slice(slice_1, "slice_1 = vec[0::2]")
print_vec(vec, "original vec")
print()
var tmp = DynamicVector[Int](capacity=2)
tmp.push_back(100)
tmp.push_back(200)
# Workaround for syntax sugar issues. Should become vec[1:3] = tmp.
var tmp_slice = DynamicVectorSlice[Int](Reference(vec), Slice(0, len(vec)))
tmp_slice.__setitem__(Slice(1, 3), tmp)
print("after vec[1:3] = [100, 200]")
print_vec(vec, "original vec")
| dynamic_vector.mojo/slice_demo.mojo | false |
<filename>dynamic_vector.mojo/vector_benchmark.mojo
from dynamic_vector import DynamicVector, DynamicVectorSlice
from collections import List
from random import randint, randn, random_si64
from benchmark import run
@always_inline
fn vector_of_vectors(size: Int = 256) -> Float64:
var vec_outer = List[List[Int]](capacity=size)
for i in range(size):
var vec_inner = List[Int](capacity=size)
for j in range(size):
vec_inner.append(j)
vec_outer.append(vec_inner)
@always_inline
@parameter
fn wrapper():
for i in range(size):
var val = int(random_si64(0, 100))
for j in range(size):
vec_outer[i][j] = val
var report = run[wrapper](min_runtime_secs=0.2, max_runtime_secs=1.0)
print("Std lib vector of vectors:", report.mean("ms"), "milliseconds")
_ = (vec_outer,)
return report.mean()
@always_inline
fn vector_of_vectors_2(size: Int = 256) -> Float64:
var vec_outer = DynamicVector[DynamicVector[Int]](capacity=size)
for i in range(size):
var vec_inner = DynamicVector[Int](capacity=size)
for j in range(size):
vec_inner.push_back(j)
vec_outer.push_back(vec_inner)
@always_inline
@parameter
fn wrapper():
for i in range(size):
var val = int(random_si64(0, 100))
for j in range(size):
vec_outer[i][j] = val
var report = run[wrapper](min_runtime_secs=0.2, max_runtime_secs=1.0)
print(
"Reference based vector of vectors:", report.mean("ms"), "milliseconds"
)
_ = (vec_outer,)
return report.mean()
fn main():
print("update every element one by one in 256 x 256 vector of vectors.")
print()
var time_one = vector_of_vectors()
var time_two = vector_of_vectors_2()
print(
"__setitem__ with References is ",
time_one / time_two,
"times faster than the std lib version.",
)
| dynamic_vector.mojo/vector_benchmark.mojo | false |
<filename>dynamic_vector.mojo/verbose.mojo
from dynamic_vector import DynamicVector, DynamicVectorSlice
from collections.list import List
struct Verbose(CollectionElement):
var value: Int
var hidden_id: Int
fn __init__(inout self, value: Int):
print("init", value)
self.value = value
self.hidden_id = value + 100
fn print(self, name: String):
print(name, "value:", self.value, "hidden_id", self.hidden_id)
fn __copyinit__(inout self, other: Self):
print(
"copyinit with value:", other.value, "hidden_id:", other.hidden_id
)
self.value = other.value
self.hidden_id = other.hidden_id
fn __moveinit__(inout self, owned other: Self):
print("moveinit with value:", other.value, "hidden_id", other.hidden_id)
self.value = other.value
self.hidden_id = other.hidden_id
fn __del__(owned self):
print("del with value:", self.value, "hidden_id", self.hidden_id)
fn get_value(self) -> Int:
return self.value
fn set_value(inout self, new_value: Int):
self.value = new_value
fn main():
print("show init, copy, move, and delete for objects in vector of vectors.")
print()
print("build std lib 2x2 vector of vectors")
var outer_1 = List[List[Verbose]](capacity=2)
for i in range(2):
var inner = List[Verbose](capacity=2)
for j in range(2):
inner.append(Verbose(j))
outer_1.append(inner)
print("finished building std lib vector of vectors")
print()
print("build reference based 2x2 vector of vectors")
var outer_2 = DynamicVector[DynamicVector[Verbose]](capacity=2)
for i in range(2):
var inner = DynamicVector[Verbose](capacity=2)
for j in range(2):
inner.push_back(Verbose(j + 2))
outer_2.push_back(inner)
print("finished building reference based vector of vectors")
print()
print("update one value in std lib vector of vectors")
outer_1[1][1].value = 1000
print("finished update in std lib vector of vectors")
print()
print("fetch from std lib vector of vectors")
print(
"confirm std lib vector of vectors update at [1][1]:",
outer_1[1][1].value,
)
print("finished fetch from std lib vector of vectors")
print()
print("update one value in reference based vector of vectors")
outer_2[1][1].value = 2000
print("finished update in reference based vector of vectors")
print()
print("fetch from reference based vector of vectors")
print(
"confirm reference based vector of vectors update at [1][1]:",
outer_2[1][1].value,
)
print("finished fetch from reference based vector of vectors")
print()
print("verbose cleanup")
_ = (outer_1, outer_2)
| dynamic_vector.mojo/verbose.mojo | false |
<filename>dynamic_vector.mojo/dynamic_vector/dynamic_vector.mojo
from memory import UnsafePointer
from memory.unsafe_pointer import (
destroy_pointee,
initialize_pointee,
move_from_pointee,
move_pointee,
)
from algorithm.swap import swap
from utils.variant import Variant
import math
alias i1 = __mlir_type.i1
alias i1_1 = __mlir_attr.`1: i1`
alias i1_0 = __mlir_attr.`0: i1`
alias NoneOrInt = Variant[NoneType, Int]
alias MAX_FINITE = math.limit.max_finite[DType.int64]().__int__()
struct DynamicVector[T: CollectionElement](Sized, CollectionElement):
var data: UnsafePointer[T]
var size: Int
var capacity: Int
@always_inline
fn __init__(inout self, *, capacity: Int):
self.capacity = capacity
self.data = UnsafePointer[T].alloc(capacity)
self.size = 0
@always_inline
fn __del__(owned self):
for i in range(self.size):
destroy_pointee(self.data + i)
self.data.free()
@always_inline
fn __copyinit__(inout self, other: Self):
self.capacity = other.capacity
self.size = other.size
self.data = UnsafePointer[T].alloc(self.capacity)
for i in range(self.size):
var new_value = other[i]
initialize_pointee(self.data + i, new_value)
@always_inline
fn __moveinit__(inout self, owned other: Self):
self.capacity = other.capacity
self.size = other.size
self.data = other.data
other.data = UnsafePointer[T]()
other.size = 0
other.capacity = 0
fn append(inout self, owned value: T):
if self.size == self.capacity:
self.reserve(self.capacity * 2)
self.data[self.size] = value^
self.size += 1
fn push_back(inout self, owned value: T):
self.append(value^)
@always_inline
fn pop_back(inout self) -> T:
self.size -= 1
return move_from_pointee(self.data + self.size)
fn __refitem__(
inout self,
index: Int,
) -> Reference[T, __mlir_attr.`1: i1`, __lifetime_of(self)]:
return (self.data + index)[]
@always_inline
fn reserve(inout self, new_capacity: Int):
if new_capacity <= self.capacity:
return
var new_data = UnsafePointer[T].alloc(new_capacity)
for i in range(self.size):
move_pointee(src=self.data + i, dst=new_data + i)
self.data.free()
self.data = new_data
self.capacity = new_capacity
@always_inline
fn resize(inout self, new_size: Int, value: T):
if new_size > self.size:
if new_size > self.capacity:
self.reserve(new_size)
for _ in range(self.size, new_size):
self.append(value)
elif new_size < self.size:
for i in range(new_size, self.size):
destroy_pointee(self.data + i)
self.size = new_size
@always_inline
fn clear(inout self):
for i in range(self.size):
destroy_pointee(self.data + i)
self.size = 0
@always_inline
fn extend(inout self, owned other: Self):
self.reserve(self.size + len(other))
for i in range(len(other)):
move_pointee(src=other.data + i, dst=self.data + self.size + i)
self.size += len(other)
other.size = 0
@always_inline
fn reverse(inout self):
var a = self.data
var b = self.data + self.size - 1
while a < b:
# a[0] and b[0] is using AnyPointer.__refitem__ and automatic dereference
swap[T](a[0], b[0])
a = a + 1
b = b - 1
# This is only required if self is in an alias.
# Otherwise it tries next __getitem__ where self is inout so an immuatable alias there causes error.
@always_inline
fn __getitem__(self, index: Int) -> T:
return self.data[index]
@always_inline
fn __getitem__(
inout self, _slice: Python3Slice
) raises -> DynamicVectorSlice[T, __lifetime_of(self)]:
return DynamicVectorSlice[T](Reference(self), _slice)
@always_inline
fn __len__(self) -> Int:
return self.size
@always_inline
fn __iter__(
inout self,
) -> _DynamicVectorIter[T, i1_1, __lifetime_of(self)]:
return _DynamicVectorIter[T, i1_1, __lifetime_of(self)](Reference(self))
@always_inline
fn steal_data(inout self) -> UnsafePointer[T]:
var res = self.data
self.data = UnsafePointer[T]()
self.size = 0
self.capacity = 0
return res
# Avoid __init__(Ref, Slice, Size) initializer because we calculate size.
@register_passable
struct DynamicVectorSlice[T: CollectionElement, L: MutLifetime](
Sized, CollectionElement
):
var data: Reference[DynamicVector[T], i1_1, L]
var _slice: Slice
var size: Int
@always_inline
fn __init__(
inout self,
data: Reference[DynamicVector[T], i1_1, L],
_slice: Python3Slice,
) raises:
self.data = data
self._slice = _slice.to_numeric_slice(len(data[]))
self.size = len(self._slice)
@always_inline
fn __init__(
inout self,
other: Self,
_slice: Python3Slice,
) raises:
self.data = other.data
self._slice = Self.adapt_slice(_slice, other._slice, len(other))
self.size = len(self._slice)
fn __copyinit__(inout self, other: Self):
self.data = other.data
self._slice = other._slice
self.size = other.size
@always_inline
fn __refitem__(self, index: Int) -> Reference[T, i1_1, L]:
return self.data[].data.__refitem__(self._slice[index])
@always_inline
fn __getitem__(inout self, _slice: Python3Slice) raises -> Self:
return Self(self, _slice)
@always_inline
fn __len__(self) -> Int:
return self.size
@always_inline
fn to_vector(self) raises -> DynamicVector[T]:
var res = DynamicVector[T](capacity=len(self))
for i in range(len(self)):
res.append(self[i])
return res
@always_inline
@staticmethod
fn adapt_slice(
_slice: Python3Slice, base_slice: Slice, size: Int
) raises -> Slice:
"""Helper function adapt the received slice to correct indices of the underlying vector.
Args:
_slice: The desired slice specified in current slice indices.
base_slice: The _slice field of the current slice.
size: The size of the current slice being sliced.
Returns:
A new slice with indices of the underlying vector.
"""
var result_slice = _slice.to_numeric_slice(size)
# bound results to be within the previous slice bounds
var upper_bound_exclusive = base_slice.end if base_slice.step > 0 else base_slice.start + 1
var lower_bound_exclusive = base_slice.start - 1 if base_slice.step > 0 else base_slice.end
# convert to indices of the base_slice
result_slice.start = base_slice[result_slice.start]
result_slice.end = base_slice[result_slice.end]
# Detetermine step and direction of resulting slice
result_slice.step *= base_slice.step
# bounds checks with adjustment for inclusive bound on start
if result_slice.step > 0:
result_slice.start = math.max(
lower_bound_exclusive + 1, result_slice.start
)
result_slice.end = math.min(upper_bound_exclusive, result_slice.end)
else:
result_slice.start = math.min(
upper_bound_exclusive - 1, result_slice.start
)
result_slice.end = math.max(lower_bound_exclusive, result_slice.end)
return result_slice
@always_inline
fn __setitem__(
inout self, _slice: Python3Slice, owned values: DynamicVectorSlice[T]
) raises:
var target_slice = DynamicVectorSlice[T](self, _slice)
if len(target_slice) != len(values):
raise Error(
String("slice assignment size mismatch: received ")
+ len(values)
+ "new values but destination expects "
+ len(target_slice)
)
for i in range(len(target_slice)):
target_slice[i] = values[i]
@always_inline
fn __setitem__(
inout self, _slice: Slice, owned value: DynamicVector[T]
) raises:
self.__setitem__(
_slice,
DynamicVectorSlice[T](
Reference(value), Python3Slice(0, len(value), 1)
),
)
@always_inline
fn __iter__(inout self) -> _DynamicVectorSliceIter[T, L]:
return _DynamicVectorSliceIter[T, L](self)
# Useful print method for debugging
# Static with T = Int because T might not be Stringable
@staticmethod
fn to_string(
inout vec: DynamicVectorSlice[Int], name: String
) raises -> String:
var res = String(name + " (size = " + len(vec) + ") [")
for val in vec:
res += String(val[]) + ", "
return res[:-2] + "]"
# Useful print method for debugging
# Static with T = String because T might not be Stringable
@staticmethod
fn to_string(
inout vec: DynamicVectorSlice[String], name: String
) raises -> String:
var res = String(name + " (size = " + len(vec) + ") [")
for val in vec:
res += val[] + ", "
return res[:-2] + "]"
@value
struct _DynamicVectorIter[
T: CollectionElement, mutability: i1, lifetime: AnyLifetime[mutability].type
](CollectionElement, Sized):
var index: Int
var src: Reference[DynamicVector[T], mutability, lifetime]
@always_inline
fn __init__(
inout self, src: Reference[DynamicVector[T], mutability, lifetime]
):
self.index = 0
self.src = src
# TODO: Check if this can be simplified after #1921 was fixed.
# Mojo #1921: https://github.com/modularml/mojo/issues/1921#event-12066222345
@always_inline
fn __next__(inout self) -> Reference[T, i1_0, lifetime]:
var ptr = self.src[].data
var res = ptr.__refitem__(self.index)
self.index += 1
return res
@always_inline
fn __len__(self) -> Int:
return len(self.src[]) - self.index
@value
struct _DynamicVectorSliceIter[T: CollectionElement, lifetime: MutLifetime](
CollectionElement, Sized
):
var index: Int
var src: DynamicVectorSlice[T, lifetime]
@always_inline
fn __init__(inout self, src: DynamicVectorSlice[T, lifetime]):
self.index = 0
self.src = src
@always_inline
fn __next__(inout self) -> Reference[T, i1_1, lifetime]:
var res = self.src.__refitem__(self.index)
self.index += 1
return res
@always_inline
fn __len__(self) -> Int:
return len(self.src) - self.index
@value
struct Python3Slice:
"""Slice that preserves empty inputs as None for correct handling of [::-1] etc.
"""
var start: NoneOrInt
var end: NoneOrInt
var step: NoneOrInt
fn __init__(inout self, slice: Slice):
debug_assert(slice.start >= 0, "Slice start must not be negative.")
debug_assert(slice.end >= 0, "Slice end must not be negative.")
self.start = slice.start
self.end = slice.end
self.step = slice.step
fn __init__(inout self, start: Int, end: Int):
self.start = start
self.end = end
self.step = 1
fn __init__(inout self, end: Int):
self.start = None
self.end = end
self.step = 1
fn _has_step(self) -> Bool:
return self.step.isa[Int]()
fn _has_start(self) -> Bool:
return self.start.isa[Int]()
fn _has_end(self) -> Bool:
return self.end.isa[Int]()
fn to_numeric_slice(self, size: Int = MAX_FINITE) raises -> Slice:
"""Create a new slice with all indices converted to valid numeric indices.
Nones are replaced with upper and lower bounds based on size. Negative indices are
converted to indices from the right. With negative step, if end starts as None it will
be set to -1 for exclusive bound.
Args:
size: The length of the vector being sliced. Defaults to maximum finite Int64 value.
Returns:
A new slice with indices converted based on size.
"""
var step = 1 if not self._has_step() else self.step.get[Int]()[]
if step == 0:
raise Error("Step cannot be zero")
var default_start = 0 if step > 0 else size - 1
var default_end = size if step > 0 else -1
var start = default_start
var end = default_end
if self._has_start():
start = self.start.get[Int]()[]
if start < 0:
start += size
if self._has_end():
end = self.end.get[Int]()[]
if end < 0:
end += size
if step < 0:
start = math.min(start, default_start)
else:
end = math.min(end, default_end)
return Slice(start, end, step)
| dynamic_vector.mojo/dynamic_vector/dynamic_vector.mojo | false |
from dynamic_vector.dynamic_vector import *
| dynamic_vector.mojo/dynamic_vector/__init__.mojo | false |
from dynamic_vector import DynamicVector, DynamicVectorSlice, Python3Slice
from testing import assert_equal
from tests.test_utils import MojoTest, append_values
@parameter
fn assert_equal_with_message(
test: MojoTest, actual: Int, expected: Int, label: String
) raises:
test.assert_equal(
actual,
expected,
label + " - Expected: " + expected + ", Actual: " + actual,
)
@value
struct Settable(CollectionElement):
var value: Int
fn set_value(inout self, v: Int):
self.value = v
fn get_value(self) -> Int:
return self.value
fn test_create_dynamic_vector() raises:
var test = MojoTest("create DynamicVector")
var v = DynamicVector[Int](capacity=2)
test.assert_true(len(v) == 0, "initial size")
test.assert_true(v.capacity == 2, "initial capacity")
fn test_push_back() raises:
var test = MojoTest("push_back")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2, 3)
test.assert_equal(len(v), 3, "size")
test.match_values(v, 1, 2, 3)
test.assert_equal(v.capacity, 4, "capacity")
fn test_append() raises:
var test = MojoTest("append")
var v = DynamicVector[String](capacity=2)
append_values(v, "abc", "def", "ghi")
test.assert_equal(len(v), 3, "size")
test.match_values(v, "abc", "def", "ghi")
test.assert_equal(v.capacity, 4, "capacity")
fn test_append_zero_capacity() raises:
var test = MojoTest("append_zero_capacity")
var v = DynamicVector[Int](capacity=0)
v.append(1)
test.assert_equal(len(v), 1, "size after append")
test.assert_equal(v[0], 1, "v[0]")
fn test_resize_larger() raises:
var test = MojoTest("resize")
var v = DynamicVector[Int](capacity=1)
v.resize(2, 7)
test.assert_equal(len(v), 2, "size")
test.match_values(v, 7, 7)
test.assert_equal(v.capacity, 2, "capacity")
fn test_resize_smaller() raises:
var test = MojoTest("resize smaller")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
v.resize(1, 0)
test.assert_equal(len(v), 1, "size")
test.assert_equal(v[0], 1, "v[0]")
test.assert_equal(v.capacity, 2, "capacity")
fn test_resize_current_size() raises:
var test = MojoTest("resize_current_size")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
v.resize(len(v), 0)
test.assert_equal(len(v), 2, "size")
test.match_values(v, 1, 2)
fn test_pop_back() raises:
var test = MojoTest("pop_back")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2, 3)
var val = v.pop_back()
test.assert_equal(len(v), 2, "size")
test.assert_equal(val, 3, "first popped value")
val = v.pop_back()
test.assert_equal(len(v), 1, "size 1")
test.assert_equal(val, 2, "second popped value")
val = v.pop_back()
test.assert_equal(len(v), 0, "size 0")
test.assert_equal(val, 1, "third popped value")
fn test_pop_back_empty() raises:
var test = MojoTest("pop_back_empty")
var v = DynamicVector[Int](capacity=2)
var val = v.pop_back()
test.assert_true(True, "pop_back on empty did not crash")
fn test_capacity_increase() raises:
var test = MojoTest("capacity increase")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2, 3)
test.assert_equal(v.capacity, 4, "capacity")
v.push_back(4)
test.match_values(v, 1, 2, 3, 4)
fn test_getitem() raises:
var test = MojoTest("getitem")
var v = DynamicVector[Settable](capacity=2)
v.push_back(Settable(1))
v.push_back(Settable(2))
var a = v[0]
a.set_value(100)
test.assert_equal(a.get_value(), 100, "value")
test.assert_equal(v[0].get_value(), 1, "value")
fn test_setitem() raises:
var test = MojoTest("setitem")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
v[0] = 3
test.match_values(v, 3, 2)
fn test_getitem_setitem_valid_index() raises:
var test = MojoTest("getitem_setitem_valid_index")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
var item = v[1]
test.assert_equal(item, 2, "v[1]")
v[1] = 3
test.assert_equal(v[1], 3, "v[1]")
fn test_copyinit() raises:
var test = MojoTest("copyinit")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
var v2 = v
test.assert_equal(len(v2), 2, "size")
test.match_values(v2, 1, 2)
v2[0] = 3
test.assert_equal(v2[0], 3, "v2[0]")
test.assert_equal(v[0], 1, "v[0]")
fn test_moveinit() raises:
var test = MojoTest("moveinit")
var v = DynamicVector[Int](capacity=2)
var orig_ptr = v.data
append_values(v, 1, 2)
var v2 = v^
test.assert_equal(len(v2), 2, "size")
test.match_values(v2, 1, 2)
v2[0] = 3
test.assert_equal(v2[0], 3, "v2[0]")
test.assert_true(orig_ptr == v2.data, "data pointer is the same")
fn test_delete() raises:
var test = MojoTest("delete")
var v = DynamicVector[Int](capacity=2)
v.push_back(1)
var ptr = v.data
test.assert_equal(ptr[0], 1, "before free ptr[0]")
_ = v # last use of v
test.assert_true(ptr[0] != 1, "after free pointer does not have value")
fn test_refitem() raises:
var test = MojoTest("refitem")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
var ref = v.__refitem__(0)
alias x = ref.mlir_ref_type
test.assert_equal(ref[], 1, "v[0]")
fn test_slice() raises:
var test = MojoTest("slice")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2, 3)
var slice = v.__getitem__(Python3Slice(1, 3))
test.assert_equal(len(slice), 2, "slice length")
test.assert_equal(slice[1], 3, "slice[1]")
slice[0] = 4
test.assert_equal(v[1], 4, "original element")
fn test_clear() raises:
var test = MojoTest("clear")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
v.clear()
test.assert_equal(len(v), 0, "size")
test.assert_equal(v.capacity, 2, "capacity")
fn test_append_after_clear() raises:
var test = MojoTest("append_after_clear")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
v.clear()
test.assert_equal(len(v), 0, "size after clear")
append_values(v, 3, 4)
test.assert_equal(len(v), 2, "size after append")
test.match_values(v, 3, 4)
fn test_extend() raises:
var test = MojoTest("extend")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
var v2 = DynamicVector[Int](capacity=2)
append_values(v2, 3, 4)
v.extend(v2)
test.assert_equal(len(v), 4, "size")
test.match_values(v, 1, 2, 3, 4)
test.assert_equal(v.capacity, 4, "capacity")
fn test_extend_with_self() raises:
var test = MojoTest("extend_with_self")
var v = DynamicVector[Int](capacity=2)
append_values(v, 1, 2)
v.extend(v)
test.assert_equal(len(v), 4, "size after extend with self")
test.match_values(v, 1, 2, 1, 2)
fn test_reverse_even() raises:
var test = MojoTest("reverse")
var v = DynamicVector[String](capacity=5)
append_values(v, "a", "b", "c", "d", "e")
v.reverse()
test.match_values(v, "e", "d", "c", "b", "a")
fn test_reverse_odd() raises:
var test = MojoTest("reverse")
var v = DynamicVector[String](capacity=5)
append_values(v, "a", "b", "c", "d")
v.reverse()
test.match_values(v, "d", "c", "b", "a")
fn test_iter() raises:
var test = MojoTest("iter")
var v = DynamicVector[Int](capacity=5)
append_values(v, 1, 2, 3, 4)
var sum = 0
for i in v:
sum += i[]
test.assert_equal(sum, 10, "sum")
fn test_iter_next() raises:
var test = MojoTest("iter __next__")
var v = DynamicVector[Int](capacity=5)
append_values(v, 1, 2, 3, 4)
var iter = v.__iter__()
test.assert_equal(len(iter), 4, "iter length")
var val = iter.__next__()
test.assert_equal(val[], 1, "first value")
test.assert_equal(len(iter), 3, "iter length")
fn test_steal_data() raises:
var test = MojoTest("steal_data")
var v = DynamicVector[Int](capacity=2)
var orig_data = v.data
append_values(v, 1, 2)
var data = v.steal_data()
test.assert_equal(len(v), 0, "vector size")
test.assert_equal(v.capacity, 0, "vector capacity")
test.assert_true(not v.data, "vector data is null")
test.assert_equal(data, orig_data, "stolen pointer")
fn test_as_alias() raises:
var test = MojoTest("assigmnet to alias")
@parameter
fn create_vector() -> DynamicVector[Int]:
var v = DynamicVector[Int](capacity=2)
v.append(1)
v.append(2)
return v
alias vec = create_vector()
test.assert_equal(len(vec), 2, "vector length")
# compile time error without defining __getitem__ to avoid using __refitem__
test.assert_equal(vec[0], 1, "alias access")
fn all_tests() raises:
test_create_dynamic_vector()
test_push_back()
test_append()
test_append_zero_capacity()
test_resize_larger()
test_resize_smaller()
test_resize_current_size()
test_pop_back()
test_pop_back_empty()
test_capacity_increase()
test_getitem()
test_setitem()
test_getitem_setitem_valid_index()
test_copyinit()
test_moveinit()
test_delete()
test_refitem()
test_slice()
test_clear()
test_append_after_clear()
test_extend()
test_extend_with_self()
test_reverse_even()
test_reverse_odd()
test_iter()
test_iter_next()
test_steal_data()
test_as_alias()
| dynamic_vector.mojo/tests/test_dynamic_vector.mojo | false |
<filename>dynamic_vector.mojo/tests/test_dynamic_vector_slice.mojo
from dynamic_vector import DynamicVector, DynamicVectorSlice, Python3Slice
from tests.test_utils import MojoTest, append_values
fn test_create_slice() raises:
var test = MojoTest("create")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(1, 3))
test.assert_equal(len(slice), 2, "size")
test.assert_equal(slice[0], "b", "slice[0]")
test.assert_equal(slice[1], "c", "slice[1]")
fn test_start_equals_length() raises:
var test = MojoTest("start equals length")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(4, 4))
test.assert_equal(len(slice), 0, "size")
fn test_zero_length_slice() raises:
var test = MojoTest("zero length slice")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(2, 2))
test.assert_equal(len(slice), 0, "size")
fn test_modify_vector_affects_slice() raises:
var test = MojoTest("modify vector affects slice")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(1, 3))
vec[1] = "x"
test.assert_equal(slice[0], "x", "slice element")
fn test_bounds() raises:
var test = MojoTest("basic bounds")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(1, 3))
test.match_slice(slice._slice, Slice(1, 3, 1), "basic bounds")
test.match_values(slice, "b", "c")
# Can only test open ended slice with [1::1] syntax, so create second slice
# TODO: test directly on DynamicVector when sugar syntax is fixed
fn test_no_end() raises:
var test = MojoTest("no end")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var preslice = DynamicVectorSlice[String](
Reference(vec), Python3Slice(0, 4)
)
var slice = preslice[1::1]
test.match_slice(slice._slice, Slice(1, 4, 1), "no end")
test.match_values(slice, "b", "c", "d")
fn test_negative_end() raises:
var test = MojoTest("negative end")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(-1))
test.match_slice(slice._slice, Slice(0, 3, 1), "negative end")
test.match_values(slice, "a", "b", "c")
fn test_negative_start() raises:
var test = MojoTest("negative start")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(-2, 3))
test.match_slice(slice._slice, Slice(2, 3, 1), "negative start")
fn test_stride() raises:
var test = MojoTest("strided bounds")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](
Reference(vec), Python3Slice(1, 4, 2)
)
test.match_slice(slice._slice, Slice(1, 4, 2), "strided bounds")
test.match_values(slice, "b", "d")
fn test_negative_stride() raises:
var test = MojoTest("negative stride")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](
Reference(vec), Python3Slice(-1, 0, -1)
)
test.match_slice(slice._slice, Slice(3, 0, -1), "negative stride")
test.match_values(slice, "d", "c", "b")
fn test_negative_stride_sugared() raises:
var test = MojoTest("negative stride sugared")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](
Reference(vec), Python3Slice(0, 4, 1)
)
var slice2 = slice[::-1]
test.match_slice(slice2._slice, Slice(3, -1, -1), "negative stride sugared")
test.match_values(slice2, "d", "c", "b", "a")
fn test_chained_negative_stride_sugared() raises:
var test = MojoTest("chained negative stride sugared")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](
Reference(vec), Python3Slice(0, 4, 1)
)
var slice2 = slice[::-1]
var slice3 = slice2[:2:-1]
test.match_slice(slice3._slice, Slice(0, 1, 1), "negative stride sugared")
test.match_values(slice3, "a")
fn test_chained_slices() raises:
var test = MojoTest("chained slices")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice1 = DynamicVectorSlice[String](Reference(vec), Python3Slice(0, 4))
var slice2 = slice1[1:3]
test.assert_equal(len(slice2), 2, "size")
test.assert_equal(slice2[0], "b", "first element")
fn test_chained_strided_slices() raises:
var test = MojoTest("chained strided slices")
var vec = DynamicVector[String](capacity=16)
append_values(
vec,
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
)
var slice1 = DynamicVectorSlice[String](
Reference(vec), Python3Slice(0, 16, 2)
)
test.match_slice(slice1._slice, Slice(0, 16, 2), "multiple slices 1")
var slice2 = slice1[1::3]
test.match_slice(slice2._slice, Slice(2, 16, 6), "multiple slices 2")
var slice3 = slice2[1::2]
test.match_slice(slice3._slice, Slice(8, 16, 12), "multiple slices 3")
test.match_values(slice3, "i")
fn test_chained_strided_slices_with_negative_strides() raises:
var test = MojoTest("chained strided slices with negative strides")
var vec = DynamicVector[String](capacity=16)
append_values(
vec,
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
)
var slice1 = DynamicVectorSlice[String](
Reference(vec), Python3Slice(15, None, -2)
)
test.match_slice(slice1._slice, Slice(15, -1, -2), "multiple slices 1")
var slice2 = slice1[1::3]
test.match_slice(slice2._slice, Slice(13, -1, -6), "multiple slices 2")
var slice3 = slice2[1::-2]
test.match_slice(slice3._slice, Slice(7, 14, 12), "multiple slices 3")
test.match_values(slice3, "h")
fn test_setitem() raises:
var test = MojoTest("setitem")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(1, 3))
slice[0] = "x"
slice[1] = "y"
test.match_values(slice, "x", "y")
test.match_values(vec, "a", "x", "y", "d")
# TODO: this could be vec[0:2] = vec2[0:2]
fn test_assignment_from_slice() raises:
var test = MojoTest("assignment from slice")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var vec2 = DynamicVector[String](capacity=2)
append_values(vec2, "y", "z")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(0, 2))
slice.__setitem__(
Python3Slice(0, 2),
DynamicVectorSlice[String](Reference(vec2), Python3Slice(0, 2)),
)
test.match_values(vec, "y", "z", "c", "d")
# TODO: this could be vec[1:3] = vec2
fn test_assignment_from_vector() raises:
var test = MojoTest("assignment from vector")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var vec2 = DynamicVector[String](capacity=2)
append_values(vec2, "y", "z")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(1, 3))
slice.__setitem__(Slice(0, 2), vec2)
test.match_values(vec, "a", "y", "z", "d")
fn test_iter() raises:
var test = MojoTest("iter")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(1, 3))
var res = String("")
for i in slice:
res += i[]
test.assert_equal(res, "bc", "concatenated result")
fn test_iterate_empty_slice() raises:
var test = MojoTest("iterate empty slice")
var vec = DynamicVector[String](capacity=4)
append_values(vec, "a", "b", "c", "d")
var slice = DynamicVectorSlice[String](Reference(vec), Python3Slice(2, 2))
var count = 0
for item in slice:
count += 1
test.assert_equal(count, 0, "iteration count")
fn all_tests() raises:
test_create_slice()
test_start_equals_length()
test_zero_length_slice()
test_modify_vector_affects_slice()
test_bounds()
test_no_end()
test_negative_end()
test_negative_start()
test_stride()
test_negative_stride()
test_negative_stride_sugared()
test_chained_negative_stride_sugared()
test_chained_slices()
test_chained_strided_slices()
test_chained_strided_slices_with_negative_strides()
test_setitem()
test_assignment_from_slice()
test_assignment_from_vector()
test_iter()
test_iterate_empty_slice()
| dynamic_vector.mojo/tests/test_dynamic_vector_slice.mojo | false |
import testing
from dynamic_vector import DynamicVector, DynamicVectorSlice
@value
struct MojoTest:
"""
A utility struct for testing.
"""
var test_name: String
fn __init__(inout self, test_name: String):
self.test_name = test_name
print("# " + test_name)
fn assert_true(self, cond: Bool, message: String):
"""
Wraps testing.assert_true.
"""
try:
testing.assert_true(cond, message)
except e:
print(e)
fn assert_equal(self, a: Int, b: Int, label: String):
"""
Wraps testing.assert_equal.
"""
try:
testing.assert_equal(
a,
b,
String("Actual ")
+ label
+ " '"
+ a
+ "', expected '"
+ b
+ "'.",
)
except e:
print(e)
fn assert_equal(self, a: String, b: String, label: String):
"""
Wraps testing.assert_equal.
"""
try:
testing.assert_equal(
a,
b,
String("Actual ")
+ label
+ " '"
+ a
+ "', expected '"
+ b
+ "'.",
)
except e:
print(e)
fn match_values(
self, vec: DynamicVector[Int], *values: Int, first_index: Int = 0
):
try:
var count = len(values)
for i in range(first_index, first_index + count):
testing.assert_true(
vec[i] == values[i - first_index],
String("Mismatch at index ")
+ String(i)
+ ": expected "
+ values[i - first_index]
+ ", got "
+ vec[i],
)
except e:
print(e)
fn match_values(
self, vec: DynamicVector[String], *values: String, first_index: Int = 0
):
try:
var count = len(values)
for i in range(first_index, first_index + count):
testing.assert_true(
vec[i] == values[i - first_index],
String("Mismatch at index ")
+ String(i)
+ ": expected "
+ values[i - first_index]
+ ", got "
+ vec[i],
)
except e:
print(e)
fn match_values(
self,
vec: DynamicVectorSlice[String],
*values: String,
first_index: Int = 0,
):
try:
var count = len(values)
for i in range(first_index, first_index + count):
testing.assert_true(
vec[i] == values[i - first_index],
String("Mismatch at index ")
+ String(i)
+ ": expected "
+ values[i - first_index]
+ ", got "
+ vec[i],
)
except e:
print(e)
fn match_slice(self, result: Slice, expected: Slice, name: String):
try:
testing.assert_true(
result == expected,
String(
name
+ " - expected slice ("
+ expected.start
+ ", "
+ expected.end
+ ", "
+ expected.step
+ ") got ("
+ result.start
+ ", "
+ result.end
+ ", "
+ result.step
+ ")"
),
)
except e:
print(e)
fn append_values(inout v: DynamicVector[String], *vals: String) raises:
for i in range(len(vals)):
v.append(vals[i])
fn append_values(inout v: DynamicVector[Int], *vals: Int) raises:
for i in range(len(vals)):
v.append(vals[i])
| dynamic_vector.mojo/tests/test_utils/utils.mojo | false |
<filename>dynamic_vector.mojo/tests/test_utils/__init__.mojo
from tests.test_utils.utils import *
| dynamic_vector.mojo/tests/test_utils/__init__.mojo | false |
from time import now
from gojo.strings import StringBuilder
from gojo.bytes.buffer import Buffer
# from gojo.io import STDWriter
fn test_string_builder() raises:
print("Testing new string builder performance")
# Create a string from the buffer
var new_builder_write_start_time = now()
var new_builder = StringBuilder()
for _ in range(10000):
_ = new_builder.write_string(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod"
" tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim"
" veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea"
" commodo consequat. Duis aute irure dolor in reprehenderit in voluptate"
" velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint"
" occaecat cupidatat non proident, sunt in culpa qui officia deserunt"
" mollit anim id est laborum."
)
var new_builder_write_execution_time = now() - new_builder_write_start_time
var new_builder_start_time = now()
var new_output = str(new_builder)
var new_builder_execution_time = now() - new_builder_start_time
print("StringBuilder buffer len", len(new_output), "\n")
var new_builder_render_start_time = now()
var new_output_render = str(new_builder.render())
var new_builder_render_execution_time = now() - new_builder_render_start_time
print("StringBuilder buffer len", len(new_output_render), "\n")
# print(new_output_render)
# Create a string using the + operator
print("Testing string concatenation performance")
var vec = List[String]()
for i in range(10000):
vec.append(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod"
" tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim"
" veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea"
" commodo consequat. Duis aute irure dolor in reprehenderit in voluptate"
" velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint"
" occaecat cupidatat non proident, sunt in culpa qui officia deserunt"
" mollit anim id est laborum."
)
var concat_start_time = now()
var concat_output: String = ""
for i in range(len(vec)):
concat_output += vec[i]
var concat_execution_time = now() - concat_start_time
print("Concat len", len(concat_output))
print("Testing new buffer performance")
# Create a string from the buffer
var new_buffer_write_start_time = now()
var new_buffer = Buffer()
for _ in range(10000):
_ = new_buffer.write_string(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod"
" tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim"
" veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea"
" commodo consequat. Duis aute irure dolor in reprehenderit in voluptate"
" velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint"
" occaecat cupidatat non proident, sunt in culpa qui officia deserunt"
" mollit anim id est laborum."
)
var new_buffer_write_execution_time = now() - new_buffer_write_start_time
var new_buffer_start_time = now()
var new_buffer_output = str(new_buffer.render())
var new_buffer_execution_time = now() - new_buffer_start_time
print("New buffer len", len(new_output), "\n")
print("\nWrite times:")
print("StringBuilder:", "(", new_builder_write_execution_time, "ns)")
print("BufferNew:", "(", new_buffer_write_execution_time, "ns)")
print("\nExecution times:")
print("StringBuilder:", "(", new_builder_execution_time, "ns)")
print("StringBuilder Render:", "(", new_builder_render_execution_time, "ns)")
print("String concat:", "(", concat_execution_time, "ns)")
print("BufferNew:", "(", new_buffer_execution_time, "ns)")
print("\nTotal Execution times:")
print("StringBuilder:", "(", new_builder_execution_time + new_builder_write_execution_time, "ns)")
print("StringBuilder Render:", "(", new_builder_render_execution_time + new_builder_write_execution_time, "ns)")
print("String concat:", "(", concat_execution_time, "ns)")
print(
": StringBuilder is ",
str(concat_execution_time // (new_builder_execution_time + new_builder_write_execution_time)) + "x faster",
": StringBuilder Render is ",
str(concat_execution_time // (new_builder_render_execution_time + new_builder_write_execution_time))
+ "x faster",
": BufferNew is ",
str(concat_execution_time // (new_buffer_execution_time + new_buffer_write_execution_time)) + "x faster",
)
# fn test_std_writer_speed() raises:
# """STDWriter is roughly 6-7x faster currently."""
# var print_start_time = now()
# for i in range(1, 10000):
# print(i)
# var print_execution_time = now() - print_start_time
# # Create stdout writer
# var writer = STDWriter(1)
# var writer_start_time = now()
# for i in range(1, 10000):
# _ = writer.write_string(str(i))
# var writer_execution_time = now() - writer_start_time
# print("\n\nprint execution time (s): " + str((print_execution_time) / 1e9))
# print("writer execution time (s): " + str((writer_execution_time) / 1e9))
# print("Writer is ", str(print_execution_time // writer_execution_time) + "x faster")
fn main() raises:
# test_std_writer_speed()
test_string_builder()
# print("Testing new string builder performance")
# # Create a string from the buffer
# var new_builder_write_start_time = now()
# var new_builder = VectorizedStringBuilder()
# for _ in range(10000):
# _ = new_builder.write_string(
# "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod"
# " tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim"
# " veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea"
# " commodo consequat. Duis aute irure dolor in reprehenderit in voluptate"
# " velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint"
# " occaecat cupidatat non proident, sunt in culpa qui officia deserunt"
# " mollit anim id est laborum."
# )
# var new_builder_write_execution_time = now() - new_builder_write_start_time
# print("StringBuilder:", "(", new_builder_write_execution_time, "ns)")
# var new_builder_start_time = now()
# var new_output = str(new_builder)
# var new_builder_execution_time = now() - new_builder_start_time
# print(len(new_output))
# print(new_output)
# print("StringBuilder:", "(", new_builder_execution_time, "ns)")
| gojo/benchmarks/test_performance.mojo | false |
from gojo.bytes import buffer
from gojo.bufio import Reader, Scanner, scan_words
fn print_words(owned text: String):
# Create a reader from a string buffer
var buf = buffer.new_buffer(text^)
var r = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner[split=scan_words](r^)
while scanner.scan():
print(scanner.current_token())
fn print_lines(owned text: String):
# Create a reader from a string buffer
var buf = buffer.new_buffer(text^)
var r = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner(r^)
while scanner.scan():
print(scanner.current_token())
fn main():
var text = String("Testing this string!")
var text2 = String("Testing\nthis\nstring!")
print_words(text^)
print_lines(text2^)
| gojo/examples/scanner/scan_text.mojo | false |
from gojo.net import Socket, HostPort, dial_tcp, TCPAddr
from gojo.syscall import SocketType
import gojo.io
fn main() raises:
# Create UDP Connection
alias message = String("dial")
alias host = "127.0.0.1"
alias port = 8081
for _ in range(10):
var connection = dial_tcp("tcp", host, port)
var bytes_written: Int
var err: Error
bytes_written, err = connection.write(
String("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n").as_bytes()
)
if err:
raise err
if bytes_written == 0:
print("No bytes sent to peer.")
return
# Read the response from the connection
var response = List[UInt8](capacity=4096)
var bytes_read: Int = 0
bytes_read, err = connection.read(response)
if err and str(err) != io.EOF:
raise err
if bytes_read == 0:
print("No bytes received from peer.")
return
response.append(0)
print("Message received:", String(response^))
# Cleanup the connection
err = connection.close()
if err:
raise err
| gojo/examples/tcp/dial_client.mojo | false |
from gojo.net import TCPAddr, get_ip_address, dial_tcp
from gojo.syscall import ProtocolFamily
fn main() raises:
# Connect to example.com on port 80 and send a GET request
var connection = dial_tcp("tcp", TCPAddr(get_ip_address("www.example.com"), 80))
var bytes_written: Int = 0
var err = Error()
bytes_written, err = connection.write(
String("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n").as_bytes()
)
if err:
raise err
if bytes_written == 0:
print("No bytes sent to peer.")
return
# Read the response from the connection
var response = List[UInt8](capacity=4096)
var bytes_read: Int = 0
bytes_read, err = connection.read(response)
if err:
raise err
if bytes_read == 0:
print("No bytes received from peer.")
return
response.append(0)
print(String(response^))
# Cleanup the connection
err = connection.close()
if err:
raise err
| gojo/examples/tcp/get_request.mojo | false |
<filename>gojo/examples/tcp/listener_server.mojo
from gojo.net import TCPAddr, get_ip_address, listen_tcp, HostPort
import gojo.io
fn main() raises:
var listener = listen_tcp("udp", TCPAddr("127.0.0.1", 12000))
while True:
var connection = listener.accept()
# Read the contents of the message from the client.
var bytes = List[UInt8](capacity=4096)
var bytes_read: Int
var err: Error
bytes_read, err = connection.read(bytes)
if str(err) != io.EOF:
raise err
bytes.append(0)
var message = String(bytes^)
print("Message Received:", message)
message = message.upper()
# Send a response back to the client.
var bytes_sent: Int
bytes_sent, err = connection.write(message.as_bytes())
print("Message sent:", message, bytes_sent)
| gojo/examples/tcp/listener_server.mojo | false |
from gojo.net import Socket, HostPort
from gojo.syscall import SocketType
import gojo.io
fn main() raises:
# Create TCP Socket
var socket = Socket()
alias message = String("test")
alias host = "127.0.0.1"
alias port = 8082
# Bind client to port 8082
socket.bind(host, port)
# Send 10 test messages
var err = socket.connect(host, 8081)
if err:
raise err
var bytes_sent: Int
bytes_sent, err = socket.write(message.as_bytes())
print("Message sent:", message)
var bytes = List[UInt8](capacity=16)
var bytes_read: Int
bytes_read, err = socket.read(bytes)
if str(err) != io.EOF:
raise err
bytes.append(0)
var response = String(bytes^)
print("Message received:", response)
_ = socket.shutdown()
_ = socket.close()
| gojo/examples/tcp/socket_client.mojo | false |
<filename>gojo/examples/tcp/socket_server.mojo
from gojo.net import Socket, HostPort
from gojo.syscall import SocketOptions
import gojo.io
fn main() raises:
var socket = Socket()
socket.set_socket_option(SocketOptions.SO_REUSEADDR, 1)
alias host = "127.0.0.1"
alias port = 8081
# Bind server to port 8081
socket.bind(host, port)
socket.listen()
print("Listening on", socket.local_address_as_tcp())
while True:
# Accept connections from clients and serve them.
var connection = socket.accept()
print("Serving", connection.remote_address_as_tcp())
# Read the contents of the message from the client.
var bytes = List[UInt8](capacity=4096)
var bytes_read: Int
var err: Error
bytes_read, err = connection.read(bytes)
if str(err) != io.EOF:
raise err
bytes.append(0)
var message = String(bytes^)
print("Message Received:", message)
message = message.upper()
# Send a response back to the client.
var bytes_sent: Int
bytes_sent, err = connection.write(message.as_bytes())
print("Message sent:", message, bytes_sent)
err = connection.close()
if err:
raise err
| gojo/examples/tcp/socket_server.mojo | false |
from gojo.net import Socket, HostPort, dial_udp, UDPAddr
from gojo.syscall import SocketType
import gojo.io
fn main() raises:
# Create UDP Connection
alias message = String("dial")
alias host = "127.0.0.1"
alias port = 12000
var udp = dial_udp("udp", host, port)
# Send 10 test messages
for _ in range(10):
var bytes_sent: Int
var err: Error
bytes_sent, err = udp.write_to(message.as_bytes(), host, port)
print("Message sent:", message, bytes_sent)
var bytes = List[UInt8](capacity=16)
var bytes_received: Int
var remote: HostPort
bytes_received, remote, err = udp.read_from(bytes)
if str(err) != io.EOF:
raise err
bytes.append(0)
var response = String(bytes^)
print("Message received:", response)
| gojo/examples/udp/dial_client.mojo | false |
<filename>gojo/examples/udp/listener_server.mojo
from gojo.net import UDPAddr, get_ip_address, listen_udp, HostPort
import gojo.io
fn main() raises:
var listener = listen_udp("udp", UDPAddr("127.0.0.1", 12000))
while True:
var dest = List[UInt8](capacity=16)
var bytes_read: Int
var remote: HostPort
var err: Error
bytes_read, remote, err = listener.read_from(dest)
if err:
raise err
dest.append(0)
var message = String(dest^)
print("Message received:", message)
message = message.upper()
var bytes_sent: Int
bytes_sent, err = listener.write_to(message.as_bytes(), UDPAddr(remote.host, remote.port))
print("Message sent:", message)
| gojo/examples/udp/listener_server.mojo | false |
from gojo.net import Socket, HostPort
from gojo.syscall import SocketType
import gojo.io
fn main() raises:
# Create UDP Socket
var socket = Socket(socket_type=SocketType.SOCK_DGRAM)
alias message = String("test")
alias host = "127.0.0.1"
alias port = 12000
# Send 10 test messages
for _ in range(10):
var bytes_sent: Int
var err: Error
bytes_sent, err = socket.send_to(message.as_bytes(), host, port)
print("Message sent:", message)
var bytes: List[UInt8]
var remote: HostPort
bytes, remote, err = socket.receive_from(1024)
if str(err) != io.EOF:
raise err
bytes.append(0)
var response = String(bytes^)
print("Message received:", response)
| gojo/examples/udp/socket_client.mojo | false |
from gojo.net import Socket, HostPort
from gojo.syscall import SocketType
import gojo.io
fn main() raises:
var socket = Socket(socket_type=SocketType.SOCK_DGRAM)
alias host = "127.0.0.1"
alias port = 12000
socket.bind(host, port)
print("Listening on", socket.local_address_as_udp())
while True:
var bytes: List[UInt8]
var remote: HostPort
var err: Error
bytes, remote, err = socket.receive_from(1024)
if str(err) != io.EOF:
raise err
bytes.append(0)
var message = String(bytes^)
print("Message Received:", message)
message = message.upper()
var bytes_sent: Int
bytes_sent, err = socket.send_to(message.as_bytes(), remote.host, remote.port)
print("Message sent:", message)
| gojo/examples/udp/socket_server.mojo | false |
<filename>gojo/gojo/bufio/bufio.mojo
from collections import InlineList
import ..io
from ..builtins import copy, panic
from ..builtins.bytes import index_byte
from ..strings import StringBuilder
alias MIN_READ_BUFFER_SIZE = 16
alias MAX_CONSECUTIVE_EMPTY_READS = 100
alias ERR_INVALID_UNREAD_BYTE = "bufio: invalid use of unread_byte"
alias ERR_INVALID_UNREAD_RUNE = "bufio: invalid use of unread_rune"
alias ERR_BUFFER_FULL = "bufio: buffer full"
alias ERR_NEGATIVE_COUNT = "bufio: negative count"
alias ERR_NEGATIVE_READ = "bufio: reader returned negative count from Read"
alias ERR_NEGATIVE_WRITE = "bufio: writer returned negative count from write"
# buffered input
# TODO: Uncomment write_to and write_buf once the bug with the trait's Span argument is fixed.
struct Reader[R: io.Reader, size: Int = MIN_READ_BUFFER_SIZE](Sized, io.Reader, io.ByteReader, io.ByteScanner):
"""Implements buffering for an io.Reader object."""
var buf: InlineList[UInt8, size]
var reader: R # reader provided by the client
var read_pos: Int
var write_pos: Int # buf read and write positions
var last_byte: Int # last byte read for unread_byte; -1 means invalid
var last_rune_size: Int # size of last rune read for unread_rune; -1 means invalid
var err: Error
@always_inline
fn __init__(
inout self,
owned reader: R,
buf: InlineList[UInt8, size] = InlineList[UInt8, size](),
read_pos: Int = 0,
write_pos: Int = 0,
last_byte: Int = -1,
last_rune_size: Int = -1,
):
self.buf = InlineList[UInt8, size]()
for element in buf:
self.buf.append(element[])
self.reader = reader^
self.read_pos = read_pos
self.write_pos = write_pos
self.last_byte = last_byte
self.last_rune_size = last_rune_size
self.err = Error()
@always_inline
fn __moveinit__(inout self, owned existing: Self):
self.buf = InlineList[UInt8, size]()
for element in existing.buf:
self.buf.append(element[])
self.reader = existing.reader^
self.read_pos = existing.read_pos
self.write_pos = existing.write_pos
self.last_byte = existing.last_byte
self.last_rune_size = existing.last_rune_size
self.err = existing.err^
# size returns the size of the underlying buffer in bytes.
@always_inline
fn __len__(self) -> Int:
return len(self.buf)
# reset discards any buffered data, resets all state, and switches
# the buffered reader to read from r.
# Calling reset on the zero value of [Reader] initializes the internal buffer
# to the default size.
# Calling self.reset(b) (that is, resetting a [Reader] to itself) does nothing.
# fn reset[R: io.Reader](self, reader: R):
# # If a Reader r is passed to NewReader, NewReader will return r.
# # Different layers of code may do that, and then later pass r
# # to reset. Avoid infinite recursion in that case.
# if self == reader:
# return
# # if self.buf == nil:
# # self.buf = make(InlineList[UInt8, io.BUFFER_SIZE], io.BUFFER_SIZE)
# self.reset(self.buf, r)
@always_inline
fn as_bytes_slice(inout self) -> Span[UInt8, True, __lifetime_of(self)]:
"""Returns the internal buffer data as a Span[UInt8]."""
return Span[UInt8, True, __lifetime_of(self)](array=Reference(self.buf._array))
@always_inline
fn reset(inout self, buf: InlineList[UInt8, size], owned reader: R):
"""Discards any buffered data, resets all state, and switches
the buffered reader to read from r.
Calling reset on the zero value of [Reader] initializes the internal buffer
to the default size.
Calling self.reset(b) (that is, resetting a [Reader] to itself) does nothing."""
self = Reader[R, size](
buf=buf,
reader=reader^,
last_byte=-1,
last_rune_size=-1,
)
fn fill(inout self):
"""Reads a new chunk into the buffer."""
# Slide existing data to beginning.
if self.read_pos > 0:
var data_to_slide = self.as_bytes_slice()[self.read_pos : self.write_pos]
# TODO: Temp copying of elements until I figure out a better pattern or slice refs are added
for i in range(len(data_to_slide)):
self.buf[i] = data_to_slide[i]
# self.buf.reserve(current_capacity)
self.write_pos -= self.read_pos
self.read_pos = 0
# Compares to the length of the entire InlineList[UInt8, io.BUFFER_SIZE] object, including 0 initialized positions.
# IE. var b = InlineList[UInt8, io.BUFFER_SIZE](capacity=4096), then trying to write at b[4096] and onwards will fail.
if self.write_pos >= io.BUFFER_SIZE:
panic("bufio.Reader: tried to fill full buffer")
# Read new data: try a limited number of times.
var i: Int = MAX_CONSECUTIVE_EMPTY_READS
while i > 0:
# TODO: Using temp until slicing can return a Reference, does reading directly into a Span of self.buf work?
# Maybe we need to read into the end of the buffer.
var span = self.as_bytes_slice()
var bytes_read: Int
var err: Error
bytes_read, err = self.reader._read(span, len(self.buf))
if bytes_read < 0:
panic(ERR_NEGATIVE_READ)
self.write_pos += bytes_read
if err:
self.err = err
return
if bytes_read > 0:
return
i -= 1
self.err = Error(str(io.ERR_NO_PROGRESS))
@always_inline
fn read_error(inout self) -> Error:
if not self.err:
return Error()
var err = self.err
self.err = Error()
return err
fn peek(self: Reference[Self, True], number_of_bytes: Int) -> (Span[UInt8, self.is_mutable, self.lifetime], Error):
"""Returns the next n bytes without advancing the reader. The bytes stop
being valid at the next read call. If Peek returns fewer than n bytes, it
also returns an error explaining why the read is short. The error is
[ERR_BUFFER_FULL] if number_of_bytes is larger than b's buffer size.
Calling Peek prevents a [Reader.unread_byte] or [Reader.unread_rune] call from succeeding
until the next read operation.
Args:
number_of_bytes: The number of bytes to peek.
"""
if number_of_bytes < 0:
return self[].as_bytes_slice()[0:0], Error(ERR_NEGATIVE_COUNT)
self[].last_byte = -1
self[].last_rune_size = -1
while (
self[].write_pos - self[].read_pos < number_of_bytes and self[].write_pos - self[].read_pos < io.BUFFER_SIZE
):
self[].fill() # self.write_pos-self.read_pos < self.capacity => buffer is not full
if number_of_bytes > io.BUFFER_SIZE:
return self[].as_bytes_slice()[self[].read_pos : self[].write_pos], Error(ERR_BUFFER_FULL)
# 0 <= n <= io.BUFFER_SIZE
var err = Error()
var available_space = self[].write_pos - self[].read_pos
if available_space < number_of_bytes:
# not enough data in buffer
err = self[].read_error()
if not err:
err = Error(ERR_BUFFER_FULL)
return self[].as_bytes_slice()[self[].read_pos : self[].read_pos + number_of_bytes], err
fn discard(inout self, number_of_bytes: Int) -> (Int, Error):
"""Discard skips the next n bytes, returning the number of bytes discarded.
If Discard skips fewer than n bytes, it also returns an error.
If 0 <= number_of_bytes <= self.buffered(), Discard is guaranteed to succeed without
reading from the underlying io.Reader.
"""
if number_of_bytes < 0:
return 0, Error(ERR_NEGATIVE_COUNT)
if number_of_bytes == 0:
return 0, Error()
self.last_byte = -1
self.last_rune_size = -1
var remain = number_of_bytes
while True:
var skip = self.buffered()
if skip == 0:
self.fill()
skip = self.buffered()
if skip > remain:
skip = remain
self.read_pos += skip
remain -= skip
if remain == 0:
return number_of_bytes, Error()
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Reads data into dest.
It returns the number of bytes read into dest.
The bytes are taken from at most one Read on the underlying [Reader],
hence n may be less than len(src).
To read exactly len(src) bytes, use io.ReadFull(b, src).
If the underlying [Reader] can return a non-zero count with io.EOF,
then this Read method can do so as well; see the [io.Reader] docs."""
if capacity == 0:
if self.buffered() > 0:
return 0, Error()
return 0, self.read_error()
var bytes_read: Int = 0
if self.read_pos == self.write_pos:
if capacity >= len(self.buf):
# Large read, empty buffer.
# Read directly into dest to avoid copy.
var bytes_read: Int
bytes_read, self.err = self.reader._read(dest, capacity)
if bytes_read < 0:
panic(ERR_NEGATIVE_READ)
if bytes_read > 0:
self.last_byte = int(dest[bytes_read - 1])
self.last_rune_size = -1
return bytes_read, self.read_error()
# One read.
# Do not use self.fill, which will loop.
self.read_pos = 0
self.write_pos = 0
var buf = self.as_bytes_slice() # TODO: I'm hoping this reads into self.data directly lol
var bytes_read: Int
bytes_read, self.err = self.reader._read(buf, len(buf))
if bytes_read < 0:
panic(ERR_NEGATIVE_READ)
if bytes_read == 0:
return 0, self.read_error()
self.write_pos += bytes_read
# copy as much as we can
var source = self.as_bytes_slice()[self.read_pos : self.write_pos]
bytes_read = 0
var start = len(dest)
for i in range(len(source)):
dest[i + start] = source[i]
bytes_read += 1
dest._len += bytes_read
self.read_pos += bytes_read
self.last_byte = int(self.buf[self.read_pos - 1])
self.last_rune_size = -1
return bytes_read, Error()
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Reads data into dest.
It returns the number of bytes read into dest.
The bytes are taken from at most one Read on the underlying [Reader],
hence n may be less than len(src).
To read exactly len(src) bytes, use io.ReadFull(b, src).
If the underlying [Reader] can return a non-zero count with io.EOF,
then this Read method can do so as well; see the [io.Reader] docs."""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn read_byte(inout self) -> (UInt8, Error):
"""Reads and returns a single byte from the internal buffer. If no byte is available, returns an error."""
self.last_rune_size = -1
while self.read_pos == self.write_pos:
if self.err:
return UInt8(0), self.read_error()
self.fill() # buffer is empty
var c = self.as_bytes_slice()[self.read_pos]
self.read_pos += 1
self.last_byte = int(c)
return c, Error()
@always_inline
fn unread_byte(inout self) -> Error:
"""Unreads the last byte. Only the most recently read byte can be unread.
unread_byte returns an error if the most recent method called on the
[Reader] was not a read operation. Notably, [Reader.peek], [Reader.discard], and [Reader.write_to] are not
considered read operations.
"""
if self.last_byte < 0 or self.read_pos == 0 and self.write_pos > 0:
return Error(ERR_INVALID_UNREAD_BYTE)
# self.read_pos > 0 or self.write_pos == 0
if self.read_pos > 0:
self.read_pos -= 1
else:
# self.read_pos == 0 and self.write_pos == 0
self.write_pos = 1
self.as_bytes_slice()[self.read_pos] = self.last_byte
self.last_byte = -1
self.last_rune_size = -1
return Error()
# # read_rune reads a single UTF-8 encoded Unicode character and returns the
# # rune and its size in bytes. If the encoded rune is invalid, it consumes one byte
# # and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
# fn read_rune(inout self) (r rune, size int, err error):
# for self.read_pos+utf8.UTFMax > self.write_pos and !utf8.FullRune(self.as_bytes_slice()[self.read_pos:self.write_pos]) and self.err == nil and self.write_pos-self.read_pos < self.buf.capacity:
# self.fill() # self.write_pos-self.read_pos < len(buf) => buffer is not full
# self.last_rune_size = -1
# if self.read_pos == self.write_pos:
# return 0, 0, self.read_poseadErr()
# r, size = rune(self.as_bytes_slice()[self.read_pos]), 1
# if r >= utf8.RuneSelf:
# r, size = utf8.DecodeRune(self.as_bytes_slice()[self.read_pos:self.write_pos])
# self.read_pos += size
# self.last_byte = int(self.as_bytes_slice()[self.read_pos-1])
# self.last_rune_size = size
# return r, size, nil
# # unread_rune unreads the last rune. If the most recent method called on
# # the [Reader] was not a [Reader.read_rune], [Reader.unread_rune] returns an error. (In this
# # regard it is stricter than [Reader.unread_byte], which will unread the last byte
# # from any read operation.)
# fn unread_rune() error:
# if self.last_rune_size < 0 or self.read_pos < self.last_rune_size:
# return ERR_INVALID_UNREAD_RUNE
# self.read_pos -= self.last_rune_size
# self.last_byte = -1
# self.last_rune_size = -1
# return nil
@always_inline
fn buffered(self) -> Int:
"""Returns the number of bytes that can be read from the current buffer.
Returns:
The number of bytes that can be read from the current buffer.
"""
return self.write_pos - self.read_pos
fn read_slice(self: Reference[Self, True], delim: UInt8) -> (Span[UInt8, self.is_mutable, self.lifetime], Error):
"""Reads until the first occurrence of delim in the input,
returning a slice pointing at the bytes in the buffer. It includes the first occurrence of the delimiter.
The bytes stop being valid at the next read.
If read_slice encounters an error before finding a delimiter,
it returns all the data in the buffer and the error itself (often io.EOF).
read_slice fails with error [ERR_BUFFER_FULL] if the buffer fills without a delim.
Because the data returned from read_slice will be overwritten
by the next I/O operation, most clients should use
[Reader.read_bytes] or read_string instead.
read_slice returns err != nil if and only if line does not end in delim.
Args:
delim: The delimiter to search for.
Returns:
The Span[UInt8] from the internal buffer.
"""
var err = Error()
var s = 0 # search start index
var line: Span[UInt8, self.is_mutable, self.lifetime]
while True:
# Search buffer.
var i = index_byte(self[].as_bytes_slice()[self[].read_pos + s : self[].write_pos], delim)
if i >= 0:
i += s
line = self[].as_bytes_slice()[self[].read_pos : self[].read_pos + i + 1]
self[].read_pos += i + 1
break
# Pending error?
if self[].err:
line = self[].as_bytes_slice()[self[].read_pos : self[].write_pos]
self[].read_pos = self[].write_pos
err = self[].read_error()
break
# Buffer full?
if self[].buffered() >= io.BUFFER_SIZE:
self[].read_pos = self[].write_pos
line = self[].as_bytes_slice()
err = Error(ERR_BUFFER_FULL)
break
s = self[].write_pos - self[].read_pos # do not rescan area we scanned before
self[].fill() # buffer is not full
# Handle last byte, if any.
var i = len(line) - 1
if i >= 0:
self[].last_byte = int(line[i])
self[].last_rune_size = -1
return line, err
fn read_line(inout self: Self) -> (List[UInt8], Bool):
"""Low-level line-reading primitive. Most callers should use
[Reader.read_bytes]('\n') or [Reader.read_string]('\n') instead or use a [Scanner].
read_line tries to return a single line, not including the end-of-line bytes.
If the line was too long for the buffer then isPrefix is set and the
beginning of the line is returned. The rest of the line will be returned
from future calls. isPrefix will be false when returning the last fragment
of the line. The returned buffer is only valid until the next call to
read_line. read_line either returns a non-nil line or it returns an error,
never both.
The text returned from read_line does not include the line end ("\r\n" or "\n").
No indication or error is given if the input ends without a final line end.
Calling [Reader.unread_byte] after read_line will always unread the last byte read
(possibly a character belonging to the line end) even if that byte is not
part of the line returned by read_line.
"""
var line: Span[UInt8, True, __lifetime_of(self)]
var err: Error
line, err = self.read_slice(ord("\n"))
if err and str(err) == ERR_BUFFER_FULL:
# Handle the case where "\r\n" straddles the buffer.
if len(line) > 0 and line[len(line) - 1] == ord("\r"):
# Put the '\r' back on buf and drop it from line.
# Let the next call to read_line check for "\r\n".
if self.read_pos == 0:
# should be unreachable
panic("bufio: tried to rewind past start of buffer")
self.read_pos -= 1
line = line[: len(line) - 1]
return List[UInt8](line), True
if len(line) == 0:
return List[UInt8](line), False
if line[len(line) - 1] == ord("\n"):
var drop = 1
if len(line) > 1 and line[len(line) - 2] == ord("\r"):
drop = 2
line = line[: len(line) - drop]
return List[UInt8](line), False
fn collect_fragments(
inout self, delim: UInt8
) -> (List[List[UInt8]], Span[UInt8, True, __lifetime_of(self)], Int, Error):
"""Reads until the first occurrence of delim in the input. It
returns (slice of full buffers, remaining bytes before delim, total number
of bytes in the combined first two elements, error).
Args:
delim: The delimiter to search for.
"""
# Use read_slice to look for delim, accumulating full buffers.
var err = Error()
var full_buffers = List[List[UInt8]]()
var total_len = 0
var frag: Span[UInt8, True, __lifetime_of(self)]
while True:
frag, err = self.read_slice(delim)
if not err:
break
var read_slice_error = err
if str(read_slice_error) != ERR_BUFFER_FULL:
err = read_slice_error
break
# Make a copy of the buffer Span.
var buf = List[UInt8](frag)
full_buffers.append(buf)
total_len += len(buf)
total_len += len(frag)
return full_buffers, frag, total_len, err
fn read_bytes(inout self, delim: UInt8) -> (List[UInt8], Error):
"""Reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the delimiter.
If read_bytes encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
read_bytes returns err != nil if and only if the returned data does not end in
delim.
For simple uses, a Scanner may be more convenient.
Args:
delim: The delimiter to search for.
Returns:
The List[UInt8] from the internal buffer.
"""
var full: List[List[UInt8]]
var frag: Span[UInt8, True, __lifetime_of(self)]
var n: Int
var err: Error
full, frag, n, err = self.collect_fragments(delim)
# Allocate new buffer to hold the full pieces and the fragment.
var buf = List[UInt8](capacity=n)
n = 0
# copy full pieces and fragment in.
for i in range(len(full)):
var buffer = full[i]
n += copy(buf, buffer, n)
_ = copy(buf, frag, n)
return buf, err
fn read_string(inout self, delim: UInt8) -> (String, Error):
"""Reads until the first occurrence of delim in the input,
returning a string containing the data up to and including the delimiter.
If read_string encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
read_string returns err != nil if and only if the returned data does not end in
delim.
For simple uses, a Scanner may be more convenient.
Args:
delim: The delimiter to search for.
Returns:
The String from the internal buffer.
"""
var full: List[List[UInt8]]
var frag: Span[UInt8, True, __lifetime_of(self)]
var n: Int
var err: Error
full, frag, n, err = self.collect_fragments(delim)
# Allocate new buffer to hold the full pieces and the fragment.
var buf = StringBuilder(capacity=n)
# copy full pieces and fragment in.
for i in range(len(full)):
var buffer = full[i]
_ = buf.write(Span(buffer))
_ = buf.write(frag)
return str(buf), err
# fn write_to[W: io.Writer](inout self, inout writer: W) -> (Int, Error):
# """Writes the internal buffer to the writer. This may make multiple calls to the [Reader.Read] method of the underlying [Reader].
# If the underlying reader supports the [Reader.WriteTo] method,
# this calls the underlying [Reader.WriteTo] without buffering.
# write_to implements io.WriterTo.
# Args:
# writer: The writer to write to.
# Returns:
# The number of bytes written.
# """
# self.last_byte = -1
# self.last_rune_size = -1
# var bytes_written: Int
# var err: Error
# bytes_written, err = self.write_buf(writer)
# if err:
# return bytes_written, err
# # internal buffer not full, fill before writing to writer
# if (self.write_pos - self.read_pos) < io.BUFFER_SIZE:
# self.fill()
# while self.read_pos < self.write_pos:
# # self.read_pos < self.write_pos => buffer is not empty
# var bw: Int
# var err: Error
# bw, err = self.write_buf(writer)
# bytes_written += bw
# self.fill() # buffer is empty
# return bytes_written, Error()
# fn write_buf[W: io.Writer](inout self, inout writer: W) -> (Int, Error):
# """Writes the [Reader]'s buffer to the writer.
# Args:
# writer: The writer to write to.
# Returns:
# The number of bytes written.
# """
# # Nothing to write
# if self.read_pos == self.write_pos:
# return Int(0), Error()
# # Write the buffer to the writer, if we hit EOF it's fine. That's not a failure condition.
# var bytes_written: Int
# var err: Error
# var buf_to_write = self.as_bytes_slice()[self.read_pos : self.write_pos]
# bytes_written, err = writer.write(List[UInt8](buf_to_write))
# if err:
# return bytes_written, err
# if bytes_written < 0:
# panic(ERR_NEGATIVE_WRITE)
# self.read_pos += bytes_written
# return Int(bytes_written), Error()
fn new_reader[R: io.Reader, size: Int = MIN_READ_BUFFER_SIZE](owned reader: R) -> Reader[R, size]:
"""Returns a new [Reader] whose buffer has at least the specified
size. If the argument io.Reader is already a [Reader] with large enough
size, it returns the underlying [Reader].
Args:
reader: The reader to read from.
Params:
size: The size of the buffer.
Returns:
The new [Reader].
"""
var r = Reader[R, size](reader^)
return r^
# buffered output
struct Writer[W: io.Writer, size: Int = io.BUFFER_SIZE](
Sized, io.Writer, io.ByteWriter, io.StringWriter, io.ReaderFrom
):
"""Implements buffering for an [io.Writer] object.
# If an error occurs writing to a [Writer], no more data will be
# accepted and all subsequent writes, and [Writer.flush], will return the error.
# After all data has been written, the client should call the
# [Writer.flush] method to guarantee all data has been forwarded to
# the underlying [io.Writer]."""
var buf: InlineList[UInt8, size]
var bytes_written: Int
var writer: W
var err: Error
@always_inline
fn __init__(
inout self,
owned writer: W,
buf: InlineList[UInt8, size] = InlineList[UInt8, size](),
bytes_written: Int = 0,
):
self.buf = InlineList[UInt8, size]()
for element in buf:
self.buf.append(element[])
self.bytes_written = bytes_written
self.writer = writer^
self.err = Error()
@always_inline
fn __moveinit__(inout self, owned existing: Self):
self.buf = InlineList[UInt8, size]()
for element in existing.buf:
self.buf.append(element[])
self.bytes_written = existing.bytes_written
self.writer = existing.writer^
self.err = existing.err^
@always_inline
fn __len__(self) -> Int:
"""Returns the size of the underlying buffer in bytes."""
return len(self.buf)
@always_inline
fn as_bytes_slice(inout self) -> Span[UInt8, True, __lifetime_of(self)]:
"""Returns the internal buffer data as a Span[UInt8]."""
return Span[UInt8, True, __lifetime_of(self)](array=Reference(self.buf._array))
@always_inline
fn reset(inout self, owned writer: W):
"""Discards any unflushed buffered data, clears any error, and
resets b to write its output to w.
Calling reset on the zero value of [Writer] initializes the internal buffer
to the default size.
Calling w.reset(w) (that is, resetting a [Writer] to itself) does nothing.
Args:
writer: The writer to write to.
"""
# # If a Writer w is passed to new_writer, new_writer will return w.
# # Different layers of code may do that, and then later pass w
# # to reset. Avoid infinite recursion in that case.
# if self == writer:
# return
# if self.buf == nil:
# self.buf = make(InlineList[UInt8, io.BUFFER_SIZE], io.BUFFER_SIZE)
self.err = Error()
self.bytes_written = 0
self.writer = writer^
fn flush(inout self) -> Error:
"""Writes any buffered data to the underlying [io.Writer]."""
# Prior to attempting to flush, check if there's a pre-existing error or if there's nothing to flush.
var err = Error()
if self.err:
return self.err
if self.bytes_written == 0:
return err
var bytes_written: Int = 0
bytes_written, err = self.writer.write(self.as_bytes_slice()[0 : self.bytes_written])
# If the write was short, set a short write error and try to shift up the remaining bytes.
if bytes_written < self.bytes_written and not err:
err = Error(str(io.ERR_SHORT_WRITE))
if err:
if bytes_written > 0 and bytes_written < self.bytes_written:
# TODO: Temp copying of elements until I figure out a better pattern or slice refs are added
var temp = self.as_bytes_slice()[bytes_written : self.bytes_written]
for i in range(len(temp)):
if i > len(temp):
self.buf[i] = temp[i]
else:
self.buf.append(temp[i])
self.bytes_written -= bytes_written
self.err = err
return err
# Reset the buffer
self.buf = InlineList[UInt8, size]()
self.bytes_written = 0
return err
@always_inline
fn available(self) -> Int:
"""Returns how many bytes are unused in the buffer."""
return self.buf.capacity - len(self.buf)
@always_inline
fn buffered(self) -> Int:
"""Returns the number of bytes that have been written into the current buffer.
Returns:
The number of bytes that have been written into the current buffer.
"""
return self.bytes_written
fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
"""Writes the contents of src into the buffer.
It returns the number of bytes written.
If nn < len(src), it also returns an error explaining
why the write is short.
Args:
src: The bytes to write.
Returns:
The number of bytes written.
"""
var total_bytes_written: Int = 0
var src_copy = src # TODO: Make a copy, maybe try a non owning Span
var err = Error()
while len(src_copy) > self.available() and not self.err:
var bytes_written: Int = 0
if self.buffered() == 0:
# Large write, empty buffer.
# write directly from p to avoid copy.
bytes_written, err = self.writer.write(src_copy)
self.err = err
else:
# TODO: Temp copying of elements until I figure out a better pattern or slice refs are added
for i in range(len(src_copy)):
if i + self.bytes_written > len(src_copy):
self.buf[i + self.bytes_written] = src_copy[i]
else:
self.buf.append(src_copy[i])
bytes_written += 1
self.bytes_written += bytes_written
_ = self.flush()
total_bytes_written += bytes_written
src_copy = src_copy[bytes_written : len(src_copy)]
if self.err:
return total_bytes_written, self.err
# TODO: Temp copying of elements until I figure out a better pattern or slice refs are added
var n = 0
for i in range(len(src_copy)):
if i + self.bytes_written > len(src_copy):
self.buf[i + self.bytes_written] = src_copy[i]
else:
self.buf.append(src_copy[i])
n += 1
self.bytes_written += n
total_bytes_written += n
return total_bytes_written, err
@always_inline
fn write(inout self, src: List[UInt8]) -> (Int, Error):
"""
Appends a byte List to the builder buffer.
Args:
src: The byte array to append.
"""
var span = Span(src)
var bytes_read: Int
var err: Error
bytes_read, err = self._write(span)
return bytes_read, err
@always_inline
fn write_byte(inout self, src: UInt8) -> (Int, Error):
"""Writes a single byte to the internal buffer.
Args:
src: The byte to write.
"""
if self.err:
return 0, self.err
# If buffer is full, flush to the underlying writer.
var err = self.flush()
if self.available() <= 0 and err:
return 0, self.err
self.buf.append(src)
self.bytes_written += 1
return 1, Error()
# # WriteRune writes a single Unicode code point, returning
# # the number of bytes written and any error.
# fn WriteRune(r rune) (size int, err error):
# # Compare as uint32 to correctly handle negative runes.
# if uint32(r) < utf8.RuneSelf:
# err = self.write_posriteByte(byte(r))
# if err != nil:
# return 0, err
# return 1, nil
# if self.err != nil:
# return 0, self.err
# n := self.available()
# if n < utf8.UTFMax:
# if self.flush(); self.err != nil:
# return 0, self.err
# n = self.available()
# if n < utf8.UTFMax:
# # Can only happen if buffer is silly small.
# return self.write_posriteString(string(r))
# size = utf8.EncodeRune(self.as_bytes_slice()[self.bytes_written:], r)
# self.bytes_written += size
# return size, nil
@always_inline
fn write_string(inout self, src: String) -> (Int, Error):
"""Writes a string to the internal buffer.
It returns the number of bytes written.
If the count is less than len(s), it also returns an error explaining
why the write is short.
Args:
src: The string to write.
Returns:
The number of bytes written.
"""
return self.write(src.as_bytes_slice())
fn read_from[R: io.Reader](inout self, inout reader: R) -> (Int, Error):
"""Implements [io.ReaderFrom]. If the underlying writer
supports the read_from method, this calls the underlying read_from.
If there is buffered data and an underlying read_from, this fills
the buffer and writes it before calling read_from.
Args:
reader: The reader to read from.
Returns:
The number of bytes read.
"""
if self.err:
return 0, self.err
var bytes_read: Int = 0
var total_bytes_written: Int = 0
var err = Error()
while True:
if self.available() == 0:
var err = self.flush()
if err:
return total_bytes_written, err
var nr = 0
while nr < MAX_CONSECUTIVE_EMPTY_READS:
# Read into remaining unused space in the buffer.
var buf = self.as_bytes_slice()[self.bytes_written : len(self.buf)]
bytes_read, err = reader._read(buf, len(buf))
if bytes_read != 0 or err:
break
nr += 1
if nr == MAX_CONSECUTIVE_EMPTY_READS:
return bytes_read, io.ERR_NO_PROGRESS
self.bytes_written += bytes_read
total_bytes_written += bytes_read
if err:
break
if err and str(err) == str(io.EOF):
# If we filled the buffer exactly, flush preemptively.
if self.available() == 0:
err = self.flush()
else:
err = Error()
return total_bytes_written, Error()
fn new_writer[W: io.Writer, size: Int = io.BUFFER_SIZE](owned writer: W) -> Writer[W, size]:
"""Returns a new [Writer] whose buffer has at least the specified
size. If the argument io.Writer is already a [Writer] with large enough
size, it returns the underlying [Writer]."""
# Is it already a Writer?
# b, ok := w.(*Writer)
# if ok and self.buf.capacity >= size:
# return b
constrained[size > 0, "bufio: invalid buffer size. Must be greater than 0."]()
return Writer[W, size](
buf=InlineList[UInt8, size](),
writer=writer^,
bytes_written=0,
)
# buffered input and output
struct ReadWriter[R: io.Reader, W: io.Writer]():
"""ReadWriter stores pointers to a [Reader] and a [Writer].
It implements [io.ReadWriter]."""
var reader: R
var writer: W
fn __init__(inout self, owned reader: R, owned writer: W):
self.reader = reader^
self.writer = writer^
# new_read_writer
fn new_read_writer[R: io.Reader, W: io.Writer](owned reader: R, owned writer: W) -> ReadWriter[R, W]:
"""Allocates a new [ReadWriter] that dispatches to r and w."""
return ReadWriter[R, W](reader^, writer^)
| gojo/gojo/bufio/bufio.mojo | false |
<filename>gojo/gojo/bufio/scan.mojo
import ..io
from ..builtins import copy, panic
from ..builtins.bytes import index_byte
from .bufio import MAX_CONSECUTIVE_EMPTY_READS
alias MAX_INT: Int = 2147483647
struct Scanner[R: io.Reader, split: SplitFunction = scan_lines](): # The function to split the tokens.
"""Scanner provides a convenient Interface for reading data such as
a file of newline-delimited lines of text. Successive calls to
the [Scanner.Scan] method will step through the 'tokens' of a file, skipping
the bytes between the tokens. The specification of a token is
defined by a split function of type [SplitFunction]; the default split
function breaks the input Into lines with line termination stripped. [Scanner.split]
fntions are defined in this package for scanning a file Into
lines, bytes, UTF-8-encoded runes, and space-delimited words. The
client may instead provide a custom split function.
Scanning stops unrecoverably at EOF, the first I/O error, or a token too
large to fit in the [Scanner.buffer]. When a scan stops, the reader may have
advanced arbitrarily far past the last token. Programs that need more
control over error handling or large tokens, or must run sequential scans
on a reader, should use [bufio.Reader] instead."""
var reader: R # The reader provided by the client.
var max_token_size: Int # Maximum size of a token; modified by tests.
var token: List[UInt8] # Last token returned by split.
var buf: List[UInt8] # buffer used as argument to split.
var start: Int # First non-processed byte in buf.
var end: Int # End of data in buf.
var empties: Int # Count of successive empty tokens.
var scan_called: Bool # Scan has been called; buffer is in use.
var done: Bool # Scan has finished.
var err: Error
fn __init__(
inout self,
owned reader: R,
max_token_size: Int = MAX_SCAN_TOKEN_SIZE,
token: List[UInt8] = List[UInt8](capacity=io.BUFFER_SIZE),
buf: List[UInt8] = List[UInt8](capacity=io.BUFFER_SIZE),
start: Int = 0,
end: Int = 0,
empties: Int = 0,
scan_called: Bool = False,
done: Bool = False,
):
self.reader = reader^
self.max_token_size = max_token_size
self.token = token
self.buf = buf
self.start = start
self.end = end
self.empties = empties
self.scan_called = scan_called
self.done = done
self.err = Error()
@always_inline
fn as_bytes_slice(self: Reference[Self]) -> Span[UInt8, self.is_mutable, self.lifetime]:
"""Returns the internal buffer data as a Span[UInt8]."""
return Span[UInt8, self.is_mutable, self.lifetime](self[].buf)
fn current_token_as_bytes(self) -> List[UInt8]:
"""Returns the most recent token generated by a call to [Scanner.Scan].
The underlying array may point to data that will be overwritten
by a subsequent call to Scan. It does no allocation.
"""
return self.token
fn current_token(self) -> String:
"""Returns the most recent token generated by a call to [Scanner.Scan]
as a newly allocated string holding its bytes."""
var copy = self.token
copy.append(0)
return String(copy^)
fn scan(inout self) -> Bool:
"""Advances the [Scanner] to the next token, which will then be
available through the [Scanner.current_token_as_bytes] or [Scanner.current_token] method.
It returns False when there are no more tokens, either by reaching the end of the input or an error.
After Scan returns False, the [Scanner.Err] method will return any error that
occurred during scanning, except if it was [io.EOF], [Scanner.Err].
Scan raises an Error if the split function returns too many empty
tokens without advancing the input. This is a common error mode for
scanners.
"""
if self.done:
return False
self.scan_called = True
# Loop until we have a token.
while True:
# See if we can get a token with what we already have.
# If we've run out of data but have an error, give the split function
# a chance to recover any remaining, possibly empty token.
if (self.end > self.start) or self.err:
var advance: Int
var token = List[UInt8](capacity=io.BUFFER_SIZE)
var err = Error()
var at_eof = False
if self.err:
at_eof = True
advance, token, err = split(self.as_bytes_slice()[self.start : self.end], at_eof)
if err:
if str(err) == str(ERR_FINAL_TOKEN):
self.token = token
self.done = True
# When token is not nil, it means the scanning stops
# with a trailing token, and thus the return value
# should be True to indicate the existence of the token.
return len(token) != 0
self.set_err(err)
return False
if not self.advance(advance):
return False
self.token = token
if len(token) != 0:
if not self.err or advance > 0:
self.empties = 0
else:
# Returning tokens not advancing input at EOF.
self.empties += 1
if self.empties > MAX_CONSECUTIVE_EMPTY_READS:
panic("bufio.Scan: too many empty tokens without progressing")
return True
# We cannot generate a token with what we are holding.
# If we've already hit EOF or an I/O error, we are done.
if self.err:
# Shut it down.
self.start = 0
self.end = 0
return False
# Must read more data.
# First, shift data to beginning of buffer if there's lots of empty space
# or space is needed.
if self.start > 0 and (self.end == len(self.buf) or self.start > int(len(self.buf) / 2)):
_ = copy(self.buf, self.as_bytes_slice()[self.start : self.end])
self.end -= self.start
self.start = 0
# Is the buffer full? If so, resize.
if self.end == len(self.buf):
# Guarantee no overflow in the multiplication below.
if len(self.buf) >= self.max_token_size or len(self.buf) > int(MAX_INT / 2):
self.set_err((ERR_TOO_LONG))
return False
var new_size = len(self.buf) * 2
if new_size == 0:
new_size = START_BUF_SIZE
# Make a new List[UInt8] buffer and copy the elements in
new_size = min(new_size, self.max_token_size)
var new_buf = List[UInt8](capacity=new_size)
_ = copy(new_buf, self.buf[self.start : self.end])
self.buf = new_buf
self.end -= self.start
self.start = 0
# Finally we can read some input. Make sure we don't get stuck with
# a misbehaving Reader. Officially we don't need to do this, but let's
# be extra careful: Scanner is for safe, simple jobs.
var loop = 0
while True:
var buf = self.as_bytes_slice()[self.end :]
# Catch any reader errors and set the internal error field to that err instead of bubbling it up.
var bytes_read: Int
var err: Error
bytes_read, err = self.reader._read(buf, self.buf.capacity - self.end)
if bytes_read < 0 or len(buf) - self.end < bytes_read:
self.set_err(ERR_BAD_READ_COUNT)
break
self.end += bytes_read
if err:
self.set_err(err)
break
if bytes_read > 0:
self.empties = 0
break
loop += 1
if loop > MAX_CONSECUTIVE_EMPTY_READS:
self.set_err(io.ERR_NO_PROGRESS)
break
fn set_err(inout self, err: Error):
"""Set the internal error field to the provided error.
Args:
err: The error to set.
"""
if self.err:
var value = str(self.err)
if value == "" or value == str(io.EOF):
self.err = err
else:
self.err = err
fn advance(inout self, n: Int) -> Bool:
"""Consumes n bytes of the buffer. It reports whether the advance was legal.
Args:
n: The number of bytes to advance the buffer by.
Returns:
True if the advance was legal, False otherwise.
"""
if n < 0:
self.set_err(ERR_NEGATIVE_ADVANCE)
return False
if n > self.end - self.start:
self.set_err(ERR_ADVANCE_TOO_FAR)
return False
self.start += n
return True
# SplitFunction is the signature of the split function used to tokenize the
# input. The arguments are an initial substring of the remaining unprocessed
# data and a flag, at_eof, that reports whether the [Reader] has no more data
# to give. The return values are the number of bytes to advance the input
# and the next token to return to the user, if any, plus an error, if any.
#
# Scanning stops if the function returns an error, in which case some of
# the input may be discarded. If that error is [ERR_FINAL_TOKEN], scanning
# stops with no error. A non-nil token delivered with [ERR_FINAL_TOKEN]
# will be the last token, and a nil token with [ERR_FINAL_TOKEN]
# immediately stops the scanning.
#
# Otherwise, the [Scanner] advances the input. If the token is not nil,
# the [Scanner] returns it to the user. If the token is nil, the
# Scanner reads more data and continues scanning; if there is no more
# data--if at_eof was True--the [Scanner] returns. If the data does not
# yet hold a complete token, for instance if it has no newline while
# scanning lines, a [SplitFunction] can return (0, nil, nil) to signal the
# [Scanner] to read more data Into the slice and try again with a
# longer slice starting at the same poInt in the input.
#
# The function is never called with an empty data slice unless at_eof
# is True. If at_eof is True, however, data may be non-empty and,
# as always, holds unprocessed text.
alias SplitFunction = fn (data: Span[UInt8], at_eof: Bool) -> (
Int,
List[UInt8],
Error,
)
# Errors returned by Scanner.
alias ERR_TOO_LONG = Error("bufio.Scanner: token too long")
alias ERR_NEGATIVE_ADVANCE = Error("bufio.Scanner: SplitFunction returns negative advance count")
alias ERR_ADVANCE_TOO_FAR = Error("bufio.Scanner: SplitFunction returns advance count beyond input")
alias ERR_BAD_READ_COUNT = Error("bufio.Scanner: Read returned impossible count")
# ERR_FINAL_TOKEN is a special sentinel error value. It is Intended to be
# returned by a split function to indicate that the scanning should stop
# with no error. If the token being delivered with this error is not nil,
# the token is the last token.
#
# The value is useful to stop processing early or when it is necessary to
# deliver a final empty token (which is different from a nil token).
# One could achieve the same behavior with a custom error value but
# providing one here is tidier.
# See the emptyFinalToken example for a use of this value.
alias ERR_FINAL_TOKEN = Error("final token")
# MAX_SCAN_TOKEN_SIZE is the maximum size used to buffer a token
# unless the user provides an explicit buffer with [Scanner.buffer].
# The actual maximum token size may be smaller as the buffer
# may need to include, for instance, a newline.
alias MAX_SCAN_TOKEN_SIZE = 64 * 1024
alias START_BUF_SIZE = 4096 # Size of initial allocation for buffer.
fn new_scanner[R: io.Reader](owned reader: R) -> Scanner[R]:
"""Returns a new [Scanner] to read from r.
The split function defaults to [scan_lines]."""
return Scanner(reader^)
###### split functions ######
fn scan_bytes(data: Span[UInt8], at_eof: Bool) -> (Int, List[UInt8], Error):
"""Returns each byte as a token.
Args:
data: The data to split.
at_eof: Whether the data is at the end of the file.
Returns:
The number of bytes to advance the input, token in bytes, and an error if one occurred.
"""
if at_eof and len(data) == 0:
return 0, List[UInt8](), Error()
return 1, List[UInt8](data[0:1]), Error()
fn scan_runes(data: Span[UInt8], at_eof: Bool) -> (Int, List[UInt8], Error):
"""Returns each UTF-8-encoded rune as a token.
Args:
data: The data to split.
at_eof: Whether the data is at the end of the file.
Returns:
The number of bytes to advance the input, token in bytes, and an error if one occurred.
"""
if at_eof and len(data) == 0:
return 0, List[UInt8](), Error()
# Number of bytes of the current character
var char_length = int(
(DTypePointer[DType.uint8](data.unsafe_ptr()).load() >> 7 == 0).cast[DType.uint8]() * 1
+ countl_zero(~DTypePointer[DType.uint8](data.unsafe_ptr()).load())
)
# Copy N bytes into new pointer and construct List.
var sp = UnsafePointer[UInt8].alloc(char_length)
memcpy(sp, data.unsafe_ptr(), char_length)
var result = List[UInt8](unsafe_pointer=sp, size=char_length, capacity=char_length)
return char_length, result, Error()
fn drop_carriage_return(data: Span[UInt8]) -> List[UInt8]:
"""Drops a terminal \r from the data.
Args:
data: The data to strip.
Returns:
The stripped data.
"""
# In the case of a \r ending without a \n, indexing on -1 doesn't work as it finds a null terminator instead of \r.
if len(data) > 0 and data[-1] == ord("\r"):
return data[:-1]
return data
fn scan_lines(data: Span[UInt8], at_eof: Bool) -> (Int, List[UInt8], Error):
"""Returns each line of text, stripped of any trailing end-of-line marker. The returned line may
be empty. The end-of-line marker is one optional carriage return followed
by one mandatory newline. The last non-empty line of input will be returned even if it has no
newline.
Args:
data: The data to split.
at_eof: Whether the data is at the end of the file.
Returns:
The number of bytes to advance the input.
"""
if at_eof and len(data) == 0:
return 0, List[UInt8](), Error()
var i = index_byte(data, ord("\n"))
if i >= 0:
# We have a full newline-terminated line.
return i + 1, drop_carriage_return(data[0:i]), Error()
# If we're at EOF, we have a final, non-terminated line. Return it.
# if at_eof:
return len(data), drop_carriage_return(data), Error()
# Request more data.
# return 0
fn is_space(r: UInt8) -> Bool:
alias ALL_WHITESPACES: String = " \t\n\r\x0b\f"
if chr(int(r)) in ALL_WHITESPACES:
return True
return False
# TODO: Handle runes and utf8 decoding. For now, just assuming single byte length.
fn scan_words(data: Span[UInt8], at_eof: Bool) -> (Int, List[UInt8], Error):
"""Returns each space-separated word of text, with surrounding spaces deleted. It will
never return an empty string.
Args:
data: The data to split.
at_eof: Whether the data is at the end of the file.
Returns:
The number of bytes to advance the input, token in bytes, and an error if one occurred.
"""
# Skip leading spaces.
var start = 0
var width = 0
while start < len(data):
width = len(data[0])
if not is_space(data[0]):
break
start += width
# Scan until space, marking end of word.
var i = 0
width = 0
start = 0
while i < len(data):
width = len(data[i])
if is_space(data[i]):
return i + width, List[UInt8](data[start:i]), Error()
i += width
# If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
if at_eof and len(data) > start:
return len(data), List[UInt8](data[start:]), Error()
# Request more data.
return start, List[UInt8](), Error()
| gojo/gojo/bufio/scan.mojo | false |
<filename>gojo/gojo/bufio/__init__.mojo
from .bufio import Reader, Writer, ReadWriter, new_writer, new_reader, new_read_writer
from .scan import Scanner, scan_words, scan_bytes, scan_lines, scan_runes
| gojo/gojo/bufio/__init__.mojo | false |
from collections import InlineList
fn copy[T: CollectionElement](inout target: List[T], source: List[T], start: Int = 0) -> Int:
"""Copies the contents of source into target at the same index. Returns the number of bytes copied.
Added a start parameter to specify the index to start copying into.
Args:
target: The buffer to copy into.
source: The buffer to copy from.
start: The index to start copying into.
Returns:
The number of bytes copied.
"""
var count = 0
for i in range(len(source)):
if i + start > len(target):
target[i + start] = source[i]
else:
target.append(source[i])
count += 1
return count
fn copy[T: CollectionElement](inout target_span: Span[T, True], source_span: Span[T], start: Int = 0) -> Int:
"""Copies the contents of source into target at the same index. Returns the number of bytes copied.
Added a start parameter to specify the index to start copying into.
Args:
target_span: The buffer to copy into.
source_span: The buffer to copy from.
start: The index to start copying into.
Returns:
The number of bytes copied.
"""
var count = 0
for i in range(len(source_span)):
target_span[i + start] = source_span[i]
count += 1
target_span._len += count
return count
fn copy[T: CollectionElement](inout target_span: Span[T, True], source: InlineList[T], start: Int = 0) -> Int:
"""Copies the contents of source into target at the same index. Returns the number of bytes copied.
Added a start parameter to specify the index to start copying into.
Args:
target_span: The buffer to copy into.
source: The buffer to copy from.
start: The index to start copying into.
Returns:
The number of bytes copied.
"""
var count = 0
for i in range(len(source)):
target_span[i + start] = source[i]
count += 1
target_span._len += count
return count
fn test(inout dest: List[UInt8]):
var source = List[UInt8](1, 2, 3)
var target = Span[UInt8](dest)
_ = copy(target, Span(source), start=0)
fn copy[T: CollectionElement](inout list: InlineList[T], source: Span[T], start: Int = 0) -> Int:
"""Copies the contents of source into target at the same index. Returns the number of bytes copied.
Added a start parameter to specify the index to start copying into.
Args:
list: The buffer to copy into.
source: The buffer to copy from.
start: The index to start copying into.
Returns:
The number of bytes copied.
"""
var count = 0
for i in range(len(source)):
if i + start > len(list):
list[i + start] = source[i]
else:
list.append(source[i])
count += 1
return count
fn copy(
inout target: List[UInt8],
source: DTypePointer[DType.uint8],
source_start: Int,
source_end: Int,
target_start: Int = 0,
) -> Int:
"""Copies the contents of source into target at the same index. Returns the number of bytes copied.
Added a start parameter to specify the index to start copying into.
Args:
target: The buffer to copy into.
source: The buffer to copy from.
source_start: The index to start copying from.
source_end: The index to stop copying at.
target_start: The index to start copying into.
Returns:
The number of bytes copied.
"""
var count = 0
for i in range(source_start, source_end):
if i + target_start > len(target):
target[i + target_start] = source[i]
else:
target.append(source[i])
count += 1
return count
fn cap[T: CollectionElement](iterable: List[T]) -> Int:
"""Returns the capacity of the List.
Args:
iterable: The List to get the capacity of.
"""
return iterable.capacity
| gojo/gojo/builtins/attributes.mojo | false |
<filename>gojo/gojo/builtins/bytes.mojo
alias Byte = UInt8
fn equals(left: List[UInt8], right: List[UInt8]) -> Bool:
if len(left) != len(right):
return False
for i in range(len(left)):
if left[i] != right[i]:
return False
return True
fn has_prefix(bytes: List[Byte], prefix: List[Byte]) -> Bool:
"""Reports whether the List[Byte] struct begins with prefix.
Args:
bytes: The List[Byte] struct to search.
prefix: The prefix to search for.
Returns:
True if the List[Byte] struct begins with prefix; otherwise, False.
"""
var len_comparison = len(bytes) >= len(prefix)
var prefix_comparison = equals(bytes[0 : len(prefix)], prefix)
return len_comparison and prefix_comparison
fn has_suffix(bytes: List[Byte], suffix: List[Byte]) -> Bool:
"""Reports whether the List[Byte] struct ends with suffix.
Args:
bytes: The List[Byte] struct to search.
suffix: The prefix to search for.
Returns:
True if the List[Byte] struct ends with suffix; otherwise, False.
"""
var len_comparison = len(bytes) >= len(suffix)
var suffix_comparison = equals(bytes[len(bytes) - len(suffix) : len(bytes)], suffix)
return len_comparison and suffix_comparison
fn index_byte(bytes: List[Byte], delim: Byte) -> Int:
"""Return the index of the first occurrence of the byte delim.
Args:
bytes: The List[Byte] struct to search.
delim: The byte to search for.
Returns:
The index of the first occurrence of the byte delim.
"""
for i in range(len(bytes)):
if bytes[i] == delim:
return i
return -1
fn index_byte(bytes: DTypePointer[DType.uint8], size: Int, delim: Byte) -> Int:
"""Return the index of the first occurrence of the byte delim.
Args:
bytes: The DTypePointer[DType.int8] struct to search.
size: The size of the bytes pointer.
delim: The byte to search for.
Returns:
The index of the first occurrence of the byte delim.
"""
for i in range(size):
if UInt8(bytes[i]) == delim:
return i
return -1
fn index_byte(bytes: Span[UInt8], delim: Byte) -> Int:
"""Return the index of the first occurrence of the byte delim.
Args:
bytes: The Span to search.
delim: The byte to search for.
Returns:
The index of the first occurrence of the byte delim.
"""
for i in range(len(bytes)):
if bytes[i] == delim:
return i
return -1
fn to_string(bytes: List[Byte]) -> String:
"""Makes a deepcopy of the List[Byte] supplied and converts it to a string. If it's not null terminated, it will append a null byte.
Args:
bytes: The List[Byte] struct to convert.
Returns:
The string representation of the List[Byte] struct.
"""
var copy = List[Byte](bytes)
if copy[-1] != 0:
copy.append(0)
return String(copy)
| gojo/gojo/builtins/bytes.mojo | false |
from sys import exit
fn panic[T: Stringable](message: T, code: Int = 1):
"""Panics the program with the given message and exit code.
Args:
message: The message to panic with.
code: The exit code to panic with.
"""
print("panic:", message)
exit(code)
| gojo/gojo/builtins/errors.mojo | false |
from .bytes import Byte, index_byte, has_suffix, has_prefix, to_string
from .attributes import cap, copy
from .errors import exit, panic
alias Rune = Int32
| gojo/gojo/builtins/__init__.mojo | false |
<filename>gojo/gojo/bytes/buffer.mojo
import ..io
from ..builtins import copy, Byte, panic, index_byte
from algorithm.memory import parallel_memcpy
alias Rune = Int32
# SMALL_BUFFER_SIZE is an initial allocation minimal capacity.
alias SMALL_BUFFER_SIZE: Int = 64
# The ReadOp constants describe the last action performed on
# the buffer, so that unread_rune and unread_byte can check for
# invalid usage. op_read_runeX constants are chosen such that
# converted to Int they correspond to the rune size that was read.
alias ReadOp = Int8
# Don't use iota for these, as the values need to correspond with the
# names and comments, which is easier to see when being explicit.
alias OP_READ: ReadOp = -1 # Any other read operation.
alias OP_INVALID: ReadOp = 0 # Non-read operation.
alias OP_READ_RUNE1: ReadOp = 1 # read rune of size 1.
alias OP_READ_RUNE2: ReadOp = 2 # read rune of size 2.
alias OP_READ_RUNE3: ReadOp = 3 # read rune of size 3.
alias OP_READ_RUNE4: ReadOp = 4 # read rune of size 4.
alias MAX_INT: Int = 2147483647
# MIN_READ is the minimum slice size passed to a read call by
# [Buffer.read_from]. As long as the [Buffer] has at least MIN_READ bytes beyond
# what is required to hold the contents of r, read_from will not grow the
# underlying buffer.
alias MIN_READ: Int = 512
# ERR_TOO_LARGE is passed to panic if memory cannot be allocated to store data in a buffer.
alias ERR_TOO_LARGE = "buffer.Buffer: too large"
alias ERR_NEGATIVE_READ = "buffer.Buffer: reader returned negative count from read"
alias ERR_SHORT_WRITE = "short write"
struct Buffer(
Stringable,
Sized,
io.Reader,
io.Writer,
io.StringWriter,
io.ByteWriter,
io.ByteReader,
):
var _data: UnsafePointer[UInt8] # contents are the bytes buf[off : len(buf)]
var _size: Int
var _capacity: Int
var offset: Int # read at &buf[off], write at &buf[len(buf)]
var last_read: ReadOp # last read operation, so that unread* can work correctly.
@always_inline
fn __init__(inout self, capacity: Int = io.BUFFER_SIZE):
self._capacity = capacity
self._size = 0
self._data = UnsafePointer[UInt8]().alloc(capacity)
self.offset = 0
self.last_read = OP_INVALID
@always_inline
fn __init__(inout self, owned buf: List[Byte]):
self._capacity = buf.capacity
self._size = buf.size
self._data = buf.steal_data()
self.offset = 0
self.last_read = OP_INVALID
@always_inline
fn __init__(inout self, owned data: UnsafePointer[UInt8], capacity: Int, size: Int):
self._capacity = capacity
self._size = size
self._data = data
self.offset = 0
self.last_read = OP_INVALID
@always_inline
fn __moveinit__(inout self, owned other: Self):
self._data = other._data
self._size = other._size
self._capacity = other._capacity
self.offset = other.offset
self.last_read = other.last_read
other._data = UnsafePointer[UInt8]()
other._size = 0
other._capacity = 0
other.offset = 0
other.last_read = OP_INVALID
@always_inline
fn __del__(owned self):
if self._data:
self._data.free()
@always_inline
fn __len__(self) -> Int:
"""Returns the number of bytes of the unread portion of the buffer.
self._size - self.offset."""
return self._size - self.offset
@always_inline
fn bytes_ptr(self) -> UnsafePointer[UInt8]:
"""Returns a pointer holding the unread portion of the buffer."""
return self._data.offset(self.offset)
@always_inline
fn bytes(self) -> List[UInt8]:
"""Returns a list of bytes holding a copy of the unread portion of the buffer."""
var copy = UnsafePointer[UInt8]().alloc(self._size)
memcpy(copy, self._data.offset(self.offset), self._size)
return List[UInt8](unsafe_pointer=copy, size=self._size - self.offset, capacity=self._size - self.offset)
@always_inline
fn as_bytes_slice(self: Reference[Self]) -> Span[UInt8, self.is_mutable, self.lifetime]:
"""Returns the internal data as a Span[UInt8]."""
return Span[UInt8, self.is_mutable, self.lifetime](unsafe_ptr=self[]._data, len=self[]._size)
@always_inline
fn _resize(inout self, capacity: Int) -> None:
"""
Resizes the string builder buffer.
Args:
capacity: The new capacity of the string builder buffer.
"""
var new_data = UnsafePointer[UInt8]().alloc(capacity)
memcpy(new_data, self._data, self._size)
self._data.free()
self._data = new_data
self._capacity = capacity
return None
@always_inline
fn _resize_if_needed(inout self, bytes_to_add: Int):
# TODO: Handle the case where new_capacity is greater than MAX_INT. It should panic.
if bytes_to_add > self._capacity - self._size:
var new_capacity = int(self._capacity * 2)
if new_capacity < self._capacity + bytes_to_add:
new_capacity = self._capacity + bytes_to_add
self._resize(new_capacity)
@always_inline
fn __str__(self) -> String:
"""
Converts the string builder to a string.
Returns:
The string representation of the string builder. Returns an empty
string if the string builder is empty.
"""
var copy = UnsafePointer[UInt8]().alloc(self._size)
memcpy(copy, self._data, self._size)
return StringRef(copy, self._size)
@always_inline
fn render(self: Reference[Self]) -> StringSlice[self.is_mutable, self.lifetime]:
"""
Return a StringSlice view of the data owned by the builder.
Slightly faster than __str__, 10-20% faster in limited testing.
Returns:
The string representation of the string builder. Returns an empty string if the string builder is empty.
"""
return StringSlice[self.is_mutable, self.lifetime](
unsafe_from_utf8_strref=StringRef(self[]._data, self[]._size)
)
@always_inline
fn _write(inout self, src: Span[Byte]) -> (Int, Error):
"""
Appends a byte Span to the builder buffer.
Args:
src: The byte array to append.
"""
self._resize_if_needed(len(src))
memcpy(self._data.offset(self._size), src._data, len(src))
self._size += len(src)
return len(src), Error()
@always_inline
fn write(inout self, src: List[Byte]) -> (Int, Error):
"""
Appends a byte List to the builder buffer.
Args:
src: The byte array to append.
"""
var span = Span(src)
var bytes_read: Int
var err: Error
bytes_read, err = self._write(span)
return bytes_read, err
@always_inline
fn write_string(inout self, src: String) -> (Int, Error):
"""
Appends a string to the builder buffer.
Args:
src: The string to append.
"""
return self.write(src.as_bytes_slice())
@always_inline
fn write_byte(inout self, byte: Byte) -> (Int, Error):
"""Appends the byte c to the buffer, growing the buffer as needed.
The returned error is always nil, but is included to match [bufio.Writer]'s
write_byte. If the buffer becomes too large, write_byte will panic with
[ERR_TOO_LARGE].
Args:
byte: The byte to write to the buffer.
Returns:
The number of bytes written to the buffer.
"""
self.last_read = OP_INVALID
self._resize_if_needed(1)
self._data[self._size] = byte
self._size += 1
return 1, Error()
@always_inline
fn empty(self) -> Bool:
"""Reports whether the unread portion of the buffer is empty."""
return self._size <= self.offset
@always_inline
fn reset(inout self):
"""Resets the buffer to be empty,
but it retains the underlying storage for use by future writes.
reset is the same as [buffer.truncate](0)."""
if self._data:
self._data.free()
self._data = UnsafePointer[UInt8]().alloc(self._capacity)
self._size = 0
self.offset = 0
self.last_read = OP_INVALID
@always_inline
fn _read(inout self, inout dest: Span[Byte, True], capacity: Int) -> (Int, Error):
"""Reads the next len(dest) bytes from the buffer or until the buffer
is drained. The return value n is the number of bytes read. If the
buffer has no data to return, err is io.EOF (unless len(dest) is zero);
otherwise it is nil.
Args:
dest: The buffer to read into.
capacity: The capacity of the destination buffer.
Returns:
The number of bytes read from the buffer.
"""
self.last_read = OP_INVALID
if self.empty():
# Buffer is empty, reset to recover space.
self.reset()
# TODO: How to check if the span's pointer has 0 capacity? We want to return early if the span can't receive any data.
if capacity == 0:
return 0, Error()
return 0, io.EOF
# Copy the data of the internal buffer from offset to len(buf) into the destination buffer at the given index.
var bytes_read = copy(dest, self.as_bytes_slice()[self.offset :])
dest._len += bytes_read
self.offset += bytes_read
if bytes_read > 0:
self.last_read = OP_READ
return bytes_read, Error()
@always_inline
fn read(inout self, inout dest: List[Byte]) -> (Int, Error):
"""Reads the next len(dest) bytes from the buffer or until the buffer
is drained. The return value n is the number of bytes read. If the
buffer has no data to return, err is io.EOF (unless len(dest) is zero);
otherwise it is nil.
Args:
dest: The buffer to read into.
Returns:
The number of bytes read from the buffer.
"""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn read_byte(inout self) -> (Byte, Error):
"""Reads and returns the next byte from the buffer.
If no byte is available, it returns error io.EOF.
"""
if self.empty():
# Buffer is empty, reset to recover space.
self.reset()
return Byte(0), io.EOF
var byte = self._data[self.offset]
self.offset += 1
self.last_read = OP_READ
return byte, Error()
@always_inline
fn unread_byte(inout self) -> Error:
"""Unreads the last byte returned by the most recent successful
read operation that read at least one byte. If a write has happened since
the last read, if the last read returned an error, or if the read read zero
bytes, unread_byte returns an error.
"""
if self.last_read == OP_INVALID:
return Error("buffer.Buffer: unread_byte: previous operation was not a successful read")
self.last_read = OP_INVALID
if self.offset > 0:
self.offset -= 1
return Error()
@always_inline
fn read_bytes(inout self, delim: Byte) -> (List[Byte], Error):
"""Reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the delimiter.
If read_bytes encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
read_bytes returns err != nil if and only if the returned data does not end in
delim.
Args:
delim: The delimiter to read until.
Returns:
A List[Byte] struct containing the data up to and including the delimiter.
"""
var slice: Span[UInt8, True, __lifetime_of(self)]
var err: Error
slice, err = self.read_slice(delim)
var bytes = List[Byte](capacity=len(slice) + 1)
for byte in slice:
bytes.append(byte[])
return bytes, err
@always_inline
fn read_slice(self: Reference[Self, True], delim: Byte) -> (Span[UInt8, self.is_mutable, self.lifetime], Error):
"""Like read_bytes but returns a reference to internal buffer data.
Args:
delim: The delimiter to read until.
Returns:
A List[Byte] struct containing the data up to and including the delimiter.
"""
var i = index_byte(bytes=self[].as_bytes_slice(), delim=delim)
var end = self[].offset + i + 1
var err = Error()
if i < 0:
end = self[]._size
err = Error(str(io.EOF))
var line = self[].as_bytes_slice()[self[].offset : end]
self[].offset = end
self[].last_read = OP_READ
return line, err
@always_inline
fn read_string(inout self, delim: Byte) -> (String, Error):
"""Reads until the first occurrence of delim in the input,
returning a string containing the data up to and including the delimiter.
If read_string encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
read_string returns err != nil if and only if the returned data does not end
in delim.
Args:
delim: The delimiter to read until.
Returns:
A string containing the data up to and including the delimiter.
"""
var bytes: List[UInt8]
var err: Error
bytes, err = self.read_bytes(delim)
bytes.append(0)
return String(bytes), err
@always_inline
fn next(self: Reference[Self, True], number_of_bytes: Int) raises -> Span[Byte, self.is_mutable, self.lifetime]:
"""Returns a slice containing the next n bytes from the buffer,
advancing the buffer as if the bytes had been returned by [Buffer.read].
If there are fewer than n bytes in the buffer, next returns the entire buffer.
The slice is only valid until the next call to a read or write method.
Args:
number_of_bytes: The number of bytes to read from the buffer.
Returns:
A slice containing the next n bytes from the buffer.
"""
self[].last_read = OP_INVALID
var bytes_remaining = len(self[])
var bytes_to_read = number_of_bytes
if bytes_to_read > bytes_remaining:
bytes_to_read = bytes_remaining
var data = self[].as_bytes_slice()[self[].offset : self[].offset + bytes_to_read]
self[].offset += bytes_to_read
if bytes_to_read > 0:
self[].last_read = OP_READ
return data
# fn write_to[W: io.Writer](inout self, inout writer: W) -> (Int, Error):
# """Writes data to w until the buffer is drained or an error occurs.
# The return value n is the number of bytes written; Any error
# encountered during the write is also returned.
# Args:
# writer: The writer to write to.
# Returns:
# The number of bytes written to the writer.
# """
# self.last_read = OP_INVALID
# var bytes_to_write = len(self)
# var total_bytes_written: Int = 0
# if bytes_to_write > 0:
# var bytes_written: Int
# var err: Error
# bytes_written, err = writer.write(self.as_bytes_slice()[self.offset :])
# if bytes_written > bytes_to_write:
# panic("bytes.Buffer.write_to: invalid write count")
# self.offset += bytes_written
# total_bytes_written = bytes_written
# if err:
# return total_bytes_written, err
# # all bytes should have been written, by definition of write method in io.Writer
# if bytes_written != bytes_to_write:
# return total_bytes_written, Error(ERR_SHORT_WRITE)
# # Buffer is now empty; reset.
# self.reset()
# return total_bytes_written, Error()
fn new_buffer(capacity: Int = io.BUFFER_SIZE) -> Buffer:
"""Creates and initializes a new [Buffer] using buf as its`
initial contents. The new [Buffer] takes ownership of buf, and the
caller should not use buf after this call. new_buffer is intended to
prepare a [Buffer] to read existing data. It can also be used to set
the initial size of the internal buffer for writing. To do that,
buf should have the desired capacity but a length of zero.
In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
sufficient to initialize a [Buffer].
"""
var b = List[Byte](capacity=capacity)
return Buffer(b^)
fn new_buffer(owned buf: List[Byte]) -> Buffer:
"""Creates and initializes a new [Buffer] using buf as its`
initial contents. The new [Buffer] takes ownership of buf, and the
caller should not use buf after this call. new_buffer is intended to
prepare a [Buffer] to read existing data. It can also be used to set
the initial size of the internal buffer for writing. To do that,
buf should have the desired capacity but a length of zero.
In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
sufficient to initialize a [Buffer].
Args:
buf: The bytes to use as the initial contents of the buffer.
Returns:
A new [Buffer] initialized with the provided bytes.
"""
return Buffer(buf^)
fn new_buffer(owned s: String) -> Buffer:
"""Creates and initializes a new [Buffer] using string s as its
initial contents. It is intended to prepare a buffer to read an existing
string.
In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
sufficient to initialize a [Buffer].
Args:
s: The string to use as the initial contents of the buffer.
Returns:
A new [Buffer] initialized with the provided string.
"""
return Buffer(s.as_bytes())
| gojo/gojo/bytes/buffer.mojo | false |
from ..builtins import copy, panic
import ..io
# TODO: Maybe try a non owning reader, but I'm concerned about the lifetime of the buffer.
# Is making it unsafe a good idea? The source data would need to be ensured to outlive the reader by the user.
struct Reader(
Sized,
io.Reader,
io.ReaderAt,
io.WriterTo,
io.Seeker,
io.ByteReader,
io.ByteScanner,
):
"""A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker,
io.ByteScanner, and io.RuneScanner Interfaces by reading from
a byte slice.
Unlike a [Buffer], a Reader is read-only and supports seeking.
The zero value for Reader operates like a Reader of an empty slice.
"""
var data: UnsafePointer[UInt8] # contents are the bytes buf[index : size]
var size: Int
var capacity: Int
var index: Int # current reading index
var prev_rune: Int # index of previous rune; or < 0
@always_inline
fn __init__(inout self, owned buffer: List[UInt8]):
"""Initializes a new [Reader.Reader] struct."""
self.capacity = buffer.capacity
self.size = buffer.size
self.data = buffer.steal_data()
self.index = 0
self.prev_rune = -1
@always_inline
fn __moveinit__(inout self, owned other: Reader):
"""Initializes a new [Reader.Reader] struct by moving the data from another [Reader.Reader] struct."""
self.capacity = other.capacity
self.size = other.size
self.data = other.data
self.index = other.index
self.prev_rune = other.prev_rune
other.data = UnsafePointer[UInt8]()
other.size = 0
other.capacity = 0
other.index = 0
other.prev_rune = -1
@always_inline
fn __len__(self) -> Int:
"""len returns the number of bytes of the unread portion of the
slice."""
return self.size - int(self.index)
@always_inline
fn __del__(owned self):
if self.data:
self.data.free()
@always_inline
fn as_bytes_slice(self: Reference[Self]) -> Span[UInt8, self.is_mutable, self.lifetime]:
"""Returns the internal data as a Span[UInt8]."""
return Span[UInt8, self.is_mutable, self.lifetime](unsafe_ptr=self[].data, len=self[].size)
@always_inline
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Reads from the internal buffer into the dest List[UInt8] struct.
Implements the [io.Reader] Interface.
Args:
dest: The destination Span[UInt8] struct to read into.
capacity: The capacity of the destination buffer.
Returns:
Int: The number of bytes read into dest."""
if self.index >= self.size:
return 0, io.EOF
# Copy the data of the internal buffer from offset to len(buf) into the destination buffer at the given index.
self.prev_rune = -1
var bytes_written = copy(dest, self.as_bytes_slice()[self.index : self.size], len(dest))
dest._len += bytes_written
self.index += bytes_written
return bytes_written, Error()
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Reads from the internal buffer into the dest List[UInt8] struct.
Implements the [io.Reader] Interface.
Args:
dest: The destination List[UInt8] struct to read into.
Returns:
Int: The number of bytes read into dest."""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn _read_at(self, inout dest: Span[UInt8, True], off: Int, capacity: Int) -> (Int, Error):
"""Reads len(dest) bytes into dest beginning at byte offset off.
Implements the [io.ReaderAt] Interface.
Args:
dest: The destination List[UInt8] struct to read into.
off: The offset to start reading from.
Returns:
Int: The number of bytes read into dest.
"""
# cannot modify state - see io.ReaderAt
if off < 0:
return 0, Error("bytes.Reader.read_at: negative offset")
if off >= Int(self.size):
return 0, io.EOF
var unread_bytes = self.as_bytes_slice()[off : self.size]
var bytes_written = copy(dest, unread_bytes)
if bytes_written < len(dest):
return 0, io.EOF
return bytes_written, Error()
@always_inline
fn read_at(self, inout dest: List[UInt8], off: Int) -> (Int, Error):
"""Reads len(dest) bytes into dest beginning at byte offset off.
Implements the [io.ReaderAt] Interface.
Args:
dest: The destination List[UInt8] struct to read into.
off: The offset to start reading from.
Returns:
Int: The number of bytes read into dest.
"""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read_at(span, off, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn read_byte(inout self) -> (UInt8, Error):
"""Reads and returns a single byte from the internal buffer. Implements the [io.ByteReader] Interface."""
self.prev_rune = -1
if self.index >= self.size:
return UInt8(0), io.EOF
var byte = self.data[self.index]
self.index += 1
return byte, Error()
@always_inline
fn unread_byte(inout self) -> Error:
"""Unreads the last byte read by moving the read position back by one.
Complements [Reader.read_byte] in implementing the [io.ByteScanner] Interface.
"""
if self.index <= 0:
return Error("bytes.Reader.unread_byte: at beginning of slice")
self.prev_rune = -1
self.index -= 1
return Error()
# # read_rune implements the [io.RuneReader] Interface.
# fn read_rune(self) (ch rune, size Int, err error):
# if self.index >= Int(self.size):
# self.prev_rune = -1
# return 0, 0, io.EOF
# self.prev_rune = Int(self.index)
# if c := self.buffer[self.index]; c < utf8.RuneSelf:
# self.index+= 1
# return rune(c), 1, nil
# ch, size = utf8.DecodeRune(self.buffer[self.index:])
# self.index += Int(size)
# return
# # unread_rune complements [Reader.read_rune] in implementing the [io.RuneScanner] Interface.
# fn unread_rune(self) error:
# if self.index <= 0:
# return errors.New("bytes.Reader.unread_rune: at beginning of slice")
# if self.prev_rune < 0:
# return errors.New("bytes.Reader.unread_rune: previous operation was not read_rune")
# self.index = Int(self.prev_rune)
# self.prev_rune = -1
# return nil
@always_inline
fn seek(inout self, offset: Int, whence: Int) -> (Int, Error):
"""Moves the read position to the specified offset from the specified whence.
Args:
offset: The offset to move to.
whence: The reference point for offset.
Returns:
The new position in which the next read will start from.
"""
self.prev_rune = -1
var position: Int = 0
if whence == io.SEEK_START:
position = offset
elif whence == io.SEEK_CURRENT:
position = self.index + offset
elif whence == io.SEEK_END:
position = self.size + offset
else:
return Int(0), Error("bytes.Reader.seek: invalid whence")
if position < 0:
return Int(0), Error("bytes.Reader.seek: negative position")
self.index = position
return position, Error()
@always_inline
fn write_to[W: io.Writer](inout self, inout writer: W) -> (Int, Error):
"""Writes data to w until the buffer is drained or an error occurs.
implements the [io.WriterTo] Interface.
Args:
writer: The writer to write to.
"""
self.prev_rune = -1
if self.index >= self.size:
return 0, Error()
var bytes = self.as_bytes_slice()[self.index : self.size]
var write_count: Int
var err: Error
write_count, err = writer.write(bytes)
if write_count > len(bytes):
panic("bytes.Reader.write_to: invalid Write count")
self.index += write_count
if write_count != len(bytes):
return write_count, io.ERR_SHORT_WRITE
return write_count, Error()
@always_inline
fn reset(inout self, owned buffer: List[UInt8]):
"""Resets the [Reader.Reader] to be reading from buffer.
Args:
buffer: The new buffer to read from.
"""
self.capacity = buffer.capacity
self.size = buffer.size
self.data = buffer.steal_data()
self.index = 0
self.prev_rune = -1
fn new_reader(owned buffer: List[UInt8]) -> Reader:
"""Returns a new [Reader.Reader] reading from b.
Args:
buffer: The new buffer to read from.
"""
return Reader(buffer)
fn new_reader(owned buffer: String) -> Reader:
"""Returns a new [Reader.Reader] reading from b.
Args:
buffer: The new buffer to read from.
"""
return Reader(buffer.as_bytes())
| gojo/gojo/bytes/reader.mojo | false |
<filename>gojo/gojo/bytes/__init__.mojo
from .buffer import Buffer, new_buffer
from .reader import Reader, new_reader
| gojo/gojo/bytes/__init__.mojo | false |
"""Formatting options
General
%v the value in a default format
when printing structs, the plus flag (%+v) adds field names
Boolean
%t the word true or false
Integer
%d base 10
%q a single-quoted character literal.
%x base 16, with lower-case letters for a-f
%X base 16, with upper-case letters for A-F
Floating-point and complex constituents:
%f decimal point but no exponent, e.g. 123.456
String and slice of bytes (treated equivalently with these verbs):
%s the uninterpreted bytes of the string or slice
%q a double-quoted string
TODO:
- Add support for more formatting options
- Switch to buffered writing to avoid multiple string concatenations
- Add support for width and precision formatting options
- Handle escaping for String's %q
"""
from utils.variant import Variant
from math import floor
from ..builtins import Byte
alias Args = Variant[String, Int, Float64, Bool, List[Byte]]
fn replace_first(s: String, old: String, new: String) -> String:
"""Replace the first occurrence of a substring in a string.
Args:
s: The original string.
old: The substring to be replaced.
new: The new substring.
Returns:
The string with the first occurrence of the old substring replaced by the new one.
"""
# Find the first occurrence of the old substring
var index = s.find(old)
# If the old substring is found, replace it
if index != -1:
return s[:index] + new + s[index + len(old) :]
# If the old substring is not found, return the original string
return s
fn find_first_verb(s: String, verbs: List[String]) -> String:
"""Find the first occurrence of a verb in a string.
Args:
s: The original string.
verbs: The list of verbs to search for.
Returns:
The verb to replace.
"""
var index = -1
var verb: String = ""
for v in verbs:
var i = s.find(v[])
if i != -1 and (index == -1 or i < index):
index = i
verb = v[]
return verb
alias BASE10_TO_BASE16 = List[String](
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f",
)
fn convert_base10_to_base16(value: Int) -> String:
"""Converts a base 10 number to base 16.
Args:
value: Base 10 number.
Returns:
Base 16 number as a String.
"""
var val: Float64 = 0.0
var result: Float64 = value
var base16: String = ""
while result > 1:
var temp = result / 16
var floor_result = floor(temp)
var remainder = temp - floor_result
result = floor_result
val = 16 * remainder
base16 = BASE10_TO_BASE16[int(val)] + base16
return base16
fn format_string(format: String, arg: String) -> String:
var verb = find_first_verb(format, List[String]("%s", "%q"))
var arg_to_place = arg
if verb == "%q":
arg_to_place = '"' + arg + '"'
return replace_first(format, String("%s"), arg)
fn format_bytes(format: String, arg: List[Byte]) -> String:
var argument = arg
if argument[-1] != 0:
argument.append(0)
return format_string(format, argument)
fn format_integer(format: String, arg: Int) -> String:
var verb = find_first_verb(format, List[String]("%x", "%X", "%d", "%q"))
var arg_to_place = str(arg)
if verb == "%x":
arg_to_place = str(convert_base10_to_base16(arg)).lower()
elif verb == "%X":
arg_to_place = str(convert_base10_to_base16(arg)).upper()
elif verb == "%q":
arg_to_place = "'" + str(arg) + "'"
return replace_first(format, verb, arg_to_place)
fn format_float(format: String, arg: Float64) -> String:
return replace_first(format, str("%f"), str(arg))
fn format_boolean(format: String, arg: Bool) -> String:
var value: String = "False"
if arg:
value = "True"
return replace_first(format, String("%t"), value)
# If the number of arguments does not match the number of format specifiers
alias BadArgCount = "(BAD ARG COUNT)"
fn sprintf(formatting: String, *args: Args) -> String:
var text = formatting
var raw_percent_count = formatting.count("%%") * 2
var formatter_count = formatting.count("%") - raw_percent_count
if formatter_count != len(args):
return BadArgCount
for i in range(len(args)):
var argument = args[i]
if argument.isa[String]():
text = format_string(text, argument[String])
elif argument.isa[List[Byte]]():
text = format_bytes(text, argument[List[Byte]])
elif argument.isa[Int]():
text = format_integer(text, argument[Int])
elif argument.isa[Float64]():
text = format_float(text, argument[Float64])
elif argument.isa[Bool]():
text = format_boolean(text, argument[Bool])
return text
# TODO: temporary until we have arg packing.
fn sprintf_str(formatting: String, args: List[String]) raises -> String:
var text = formatting
var formatter_count = formatting.count("%")
if formatter_count > len(args):
raise Error("Not enough arguments for format string")
elif formatter_count < len(args):
raise Error("Too many arguments for format string")
for i in range(len(args)):
text = format_string(text, args[i])
return text
fn printf(formatting: String, *args: Args) raises:
var text = formatting
var raw_percent_count = formatting.count("%%") * 2
var formatter_count = formatting.count("%") - raw_percent_count
if formatter_count > len(args):
raise Error("Not enough arguments for format string")
elif formatter_count < len(args):
raise Error("Too many arguments for format string")
for i in range(len(args)):
var argument = args[i]
if argument.isa[String]():
text = format_string(text, argument[String])
elif argument.isa[List[Byte]]():
text = format_bytes(text, argument[List[Byte]])
elif argument.isa[Int]():
text = format_integer(text, argument[Int])
elif argument.isa[Float64]():
text = format_float(text, argument[Float64])
elif argument.isa[Bool]():
text = format_boolean(text, argument[Bool])
else:
raise Error("Unknown for argument #" + str(i))
print(text)
| gojo/gojo/fmt/fmt.mojo | false |
from .fmt import sprintf, printf, sprintf_str
| gojo/gojo/fmt/__init__.mojo | false |
import ..io
from ..builtins import copy
from ..syscall import FileDescriptorBase
struct FileWrapper(FileDescriptorBase, io.ByteReader):
var handle: FileHandle
@always_inline
fn __init__(inout self, path: String, mode: String) raises:
self.handle = open(path, mode)
@always_inline
fn __moveinit__(inout self, owned existing: Self):
self.handle = existing.handle^
@always_inline
fn __del__(owned self):
var err = self.close()
if err:
# TODO: __del__ can't raise, but there should be some fallback.
print(str(err))
@always_inline
fn close(inout self) -> Error:
try:
self.handle.close()
except e:
return e
return Error()
@always_inline
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Read from the file handle into dest's pointer.
Pretty hacky way to force the filehandle read into the defined trait, and it's unsafe since we're
reading directly into the pointer.
"""
# var bytes_to_read = dest.capacity - len(dest)
var bytes_read: Int
var result: List[UInt8]
try:
result = self.handle.read_bytes()
bytes_read = len(result)
# TODO: Need to raise an Issue for this. Reading with pointer does not return an accurate count of bytes_read :(
# bytes_read = int(self.handle.read(DTypePointer[DType.uint8](dest.unsafe_ptr()) + dest.size))
except e:
return 0, e
_ = copy(dest, Span(result), len(dest))
if bytes_read == 0:
return bytes_read, io.EOF
return bytes_read, Error()
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Read from the file handle into dest's pointer.
Pretty hacky way to force the filehandle read into the defined trait, and it's unsafe since we're
reading directly into the pointer.
"""
# var bytes_to_read = dest.capacity - len(dest)
var bytes_read: Int
var result: List[UInt8]
try:
result = self.handle.read_bytes()
bytes_read = len(result)
# TODO: Need to raise an Issue for this. Reading with pointer does not return an accurate count of bytes_read :(
# bytes_read = int(self.handle.read(DTypePointer[DType.uint8](dest.unsafe_ptr()) + dest.size))
except e:
return 0, e
_ = copy(dest, result, len(dest))
if bytes_read == 0:
return bytes_read, io.EOF
return bytes_read, Error()
@always_inline
fn read_all(inout self) -> (List[UInt8], Error):
var bytes = List[UInt8](capacity=io.BUFFER_SIZE)
while True:
var temp = List[UInt8](capacity=io.BUFFER_SIZE)
_ = self.read(temp)
# If new bytes will overflow the result, resize it.
if len(bytes) + len(temp) > bytes.capacity:
bytes.reserve(bytes.capacity * 2)
bytes.extend(temp)
if len(temp) < io.BUFFER_SIZE:
return bytes, io.EOF
@always_inline
fn read_byte(inout self) -> (UInt8, Error):
try:
var bytes: List[UInt8]
var err: Error
bytes, err = self.read_bytes(1)
return bytes[0], Error()
except e:
return UInt8(0), e
@always_inline
fn read_bytes(inout self, size: Int = -1) raises -> (List[UInt8], Error):
try:
return self.handle.read_bytes(size), Error()
except e:
return List[UInt8](), e
@always_inline
fn stream_until_delimiter(inout self, inout dest: List[UInt8], delimiter: UInt8, max_size: Int) -> Error:
var byte: UInt8
var err = Error()
for _ in range(max_size):
byte, err = self.read_byte()
if err:
return err
if byte == delimiter:
return err
dest.append(byte)
return Error("Stream too long")
@always_inline
fn seek(inout self, offset: Int, whence: Int = 0) -> (Int, Error):
try:
var position = self.handle.seek(UInt64(offset), whence)
return int(position), Error()
except e:
return 0, e
@always_inline
fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
if len(src) == 0:
return 0, Error("No data to write")
try:
self.handle.write(src.unsafe_ptr())
return len(src), io.EOF
except e:
return 0, Error(str(e))
@always_inline
fn write(inout self, src: List[UInt8]) -> (Int, Error):
return self._write(Span(src))
| gojo/gojo/io/file.mojo | false |
<filename>gojo/gojo/io/io.mojo
from ..builtins import copy, Byte, panic
alias BUFFER_SIZE = 4096
fn write_string[W: Writer](inout writer: W, string: String) -> (Int, Error):
"""Writes the contents of the string s to w, which accepts a slice of bytes.
If w implements [StringWriter], [StringWriter.write_string] is invoked directly.
Otherwise, [Writer.write] is called exactly once.
Args:
writer: The writer to write to.
string: The string to write.
Returns:
The number of bytes written and an error, if any.
"""
return writer.write(string.as_bytes())
fn write_string[W: StringWriter](inout writer: W, string: String) -> (Int, Error):
"""Writes the contents of the string s to w, which accepts a slice of bytes.
If w implements [StringWriter], [StringWriter.write_string] is invoked directly.
Otherwise, [Writer.write] is called exactly once.
Args:
writer: The writer to write to.
string: The string to write.
Returns:
The number of bytes written and an error, if any."""
return writer.write_string(string)
fn read_at_least[R: Reader](inout reader: R, inout dest: List[Byte], min: Int) -> (Int, Error):
"""Reads from r into buf until it has read at least min bytes.
It returns the number of bytes copied and an error if fewer bytes were read.
The error is EOF only if no bytes were read.
If an EOF happens after reading fewer than min bytes,
read_at_least returns [ERR_UNEXPECTED_EOF].
If min is greater than the length of buf, read_at_least returns [ERR_SHORT_BUFFER].
On return, n >= min if and only if err == nil.
If r returns an error having read at least min bytes, the error is dropped.
Args:
reader: The reader to read from.
dest: The buffer to read into.
min: The minimum number of bytes to read.
Returns:
The number of bytes read."""
var error = Error()
if len(dest) < min:
return 0, io.ERR_SHORT_BUFFER
var total_bytes_read: Int = 0
while total_bytes_read < min and not error:
var bytes_read: Int
bytes_read, error = reader.read(dest)
total_bytes_read += bytes_read
if total_bytes_read >= min:
error = Error()
elif total_bytes_read > 0 and str(error):
error = ERR_UNEXPECTED_EOF
return total_bytes_read, error
fn read_full[R: Reader](inout reader: R, inout dest: List[Byte]) -> (Int, Error):
"""Reads exactly len(buf) bytes from r into buf.
It returns the number of bytes copied and an error if fewer bytes were read.
The error is EOF only if no bytes were read.
If an EOF happens after reading some but not all the bytes,
read_full returns [ERR_UNEXPECTED_EOF].
On return, n == len(buf) if and only if err == nil.
If r returns an error having read at least len(buf) bytes, the error is dropped.
"""
return read_at_least(reader, dest, len(dest))
# fn copy_n[W: Writer, R: Reader](dst: W, src: R, n: Int) raises -> Int:
# """Copies n bytes (or until an error) from src to dst.
# It returns the number of bytes copied and the earliest
# error encountered while copying.
# On return, written == n if and only if err == nil.
# If dst implements [ReaderFrom], the copy is implemented using it.
# """
# var written = copy(dst, LimitReader(src, n))
# if written == n:
# return n
# if written < n:
# # src stopped early; must have been EOF.
# raise Error(ERR_UNEXPECTED_EOF)
# return written
# fn copy[W: Writer, R: Reader](dst: W, src: R, n: Int) -> Int:
# """copy copies from src to dst until either EOF is reached
# on src or an error occurs. It returns the number of bytes
# copied and the first error encountered while copying, if any.
# A successful copy returns err == nil, not err == EOF.
# Because copy is defined to read from src until EOF, it does
# not treat an EOF from Read as an error to be reported.
# If src implements [WriterTo],
# the copy is implemented by calling src.WriteTo(dst).
# Otherwise, if dst implements [ReaderFrom],
# the copy is implemented by calling dst.ReadFrom(src).
# """
# return copy_buffer(dst, src, nil)
# # CopyBuffer is identical to copy except that it stages through the
# # provided buffer (if one is required) rather than allocating a
# # temporary one. If buf is nil, one is allocated; otherwise if it has
# # zero length, CopyBuffer panics.
# #
# # If either src implements [WriterTo] or dst implements [ReaderFrom],
# # buf will not be used to perform the copy.
# fn CopyBuffer(dst Writer, src Reader, buf bytes) (written Int, err error) {
# if buf != nil and len(buf) == 0 {
# panic("empty buffer in CopyBuffer")
# }
# return copy_buffer(dst, src, buf)
# }
# fn copy_buffer[W: Writer, R: Reader](dst: W, src: R, buf: Span[Byte]) raises -> Int:
# """Actual implementation of copy and CopyBuffer.
# if buf is nil, one is allocated.
# """
# var nr: Int
# nr = src.read(buf)
# while True:
# if nr > 0:
# var nw: Int
# nw = dst.write(get_slice(buf, 0, nr))
# if nw < 0 or nr < nw:
# nw = 0
# var written = Int(nw)
# if nr != nw:
# raise Error(ERR_SHORT_WRITE)
# return written
# fn copy_buffer[W: Writer, R: ReaderWriteTo](dst: W, src: R, buf: Span[Byte]) -> Int:
# return src.write_to(dst)
# fn copy_buffer[W: WriterReadFrom, R: Reader](dst: W, src: R, buf: Span[Byte]) -> Int:
# return dst.read_from(src)
# # LimitReader returns a Reader that reads from r
# # but stops with EOF after n bytes.
# # The underlying implementation is a *LimitedReader.
# fn LimitReader(r Reader, n Int) Reader { return &LimitedReader{r, n} }
# # A LimitedReader reads from R but limits the amount of
# # data returned to just N bytes. Each call to Read
# # updates N to reflect the new amount remaining.
# # Read returns EOF when N <= 0 or when the underlying R returns EOF.
# struct LimitedReader():
# var R: Reader # underlying reader
# N Int # max bytes remaining
# fn (l *LimitedReader) Read(p bytes) (n Int, err error) {
# if l.N <= 0 {
# return 0, EOF
# }
# if Int(len(p)) > l.N {
# p = p[0:l.N]
# }
# n, err = l.R.Read(p)
# l.N -= Int(n)
# return
# }
# # NewSectionReader returns a [SectionReader] that reads from r
# # starting at offset off and stops with EOF after n bytes.
# fn NewSectionReader(r ReaderAt, off Int, n Int) *SectionReader {
# var remaining Int
# const maxInt = 1<<63 - 1
# if off <= maxInt-n {
# remaining = n + off
# } else {
# # Overflow, with no way to return error.
# # Assume we can read up to an offset of 1<<63 - 1.
# remaining = maxInt
# }
# return &SectionReader{r, off, off, remaining, n}
# }
# # SectionReader implements Read, Seek, and ReadAt on a section
# # of an underlying [ReaderAt].
# type SectionReader struct {
# r ReaderAt # constant after creation
# base Int # constant after creation
# off Int
# limit Int # constant after creation
# n Int # constant after creation
# }
# fn (s *SectionReader) Read(p bytes) (n Int, err error) {
# if s.off >= s.limit {
# return 0, EOF
# }
# if max := s.limit - s.off; Int(len(p)) > max {
# p = p[0:max]
# }
# n, err = s.r.ReadAt(p, s.off)
# s.off += Int(n)
# return
# }
# alias errWhence = "Seek: invalid whence"
# alias errOffset = "Seek: invalid offset"
# fn (s *SectionReader) Seek(offset Int, whence Int) (Int, error) {
# switch whence {
# default:
# return 0, errWhence
# case SEEK_START:
# offset += s.base
# case SEEK_CURRENT:
# offset += s.off
# case SEEK_END:
# offset += s.limit
# }
# if offset < s.base {
# return 0, errOffset
# }
# s.off = offset
# return offset - s.base, nil
# }
# fn (s *SectionReader) ReadAt(p bytes, off Int) (n Int, err error) {
# if off < 0 or off >= s.capacity {
# return 0, EOF
# }
# off += s.base
# if max := s.limit - off; Int(len(p)) > max {
# p = p[0:max]
# n, err = s.r.ReadAt(p, off)
# if err == nil {
# err = EOF
# }
# return n, err
# }
# return s.r.ReadAt(p, off)
# }
# # Size returns the size of the section in bytes.
# fn (s *SectionReader) Size() Int { return s.limit - s.base }
# # Outer returns the underlying [ReaderAt] and offsets for the section.
# #
# # The returned values are the same that were passed to [NewSectionReader]
# # when the [SectionReader] was created.
# fn (s *SectionReader) Outer() (r ReaderAt, off Int, n Int) {
# return s.r, s.base, s.n
# }
# # An OffsetWriter maps writes at offset base to offset base+off in the underlying writer.
# type OffsetWriter struct {
# w WriterAt
# base Int # the original offset
# off Int # the current offset
# }
# # NewOffsetWriter returns an [OffsetWriter] that writes to w
# # starting at offset off.
# fn NewOffsetWriter(w WriterAt, off Int) *OffsetWriter {
# return &OffsetWriter{w, off, off}
# }
# fn (o *OffsetWriter) Write(p bytes) (n Int, err error) {
# n, err = o.w.WriteAt(p, o.off)
# o.off += Int(n)
# return
# }
# fn (o *OffsetWriter) WriteAt(p bytes, off Int) (n Int, err error) {
# if off < 0 {
# return 0, errOffset
# }
# off += o.base
# return o.w.WriteAt(p, off)
# }
# fn (o *OffsetWriter) Seek(offset Int, whence Int) (Int, error) {
# switch whence {
# default:
# return 0, errWhence
# case SEEK_START:
# offset += o.base
# case SEEK_CURRENT:
# offset += o.off
# }
# if offset < o.base {
# return 0, errOffset
# }
# o.off = offset
# return offset - o.base, nil
# }
# # TeeReader returns a [Reader] that writes to w what it reads from r.
# # All reads from r performed through it are matched with
# # corresponding writes to w. There is no internal buffering -
# # the write must complete before the read completes.
# # Any error encountered while writing is reported as a read error.
# fn TeeReader(r Reader, w Writer) Reader {
# return &teeReader{r, w}
# }
# type teeReader struct {
# r Reader
# w Writer
# }
# fn (t *teeReader) Read(p bytes) (n Int, err error) {
# n, err = t.r.Read(p)
# if n > 0 {
# if n, err := t.w.Write(p[:n]); err != nil {
# return n, err
# }
# }
# return
# }
# # Discard is a [Writer] on which all Write calls succeed
# # without doing anything.
# var Discard Writer = discard{}
# type discard struct{}
# # discard implements ReaderFrom as an optimization so copy to
# # io.Discard can avoid doing unnecessary work.
# var _ ReaderFrom = discard{}
# fn (discard) Write(p bytes) (Int, error) {
# return len(p), nil
# }
# fn (discard) write_string(s string) (Int, error) {
# return len(s), nil
# }
# var blackHolePool = sync.Pool{
# New: fn() any {
# b := make(bytes, 8192)
# return &b
# },
# }
# fn (discard) ReadFrom(r Reader) (n Int, err error) {
# bufp := blackHolePool.Get().(*bytes)
# readSize := 0
# for {
# readSize, err = r.Read(*bufp)
# n += Int(readSize)
# if err != nil {
# blackHolePool.Put(bufp)
# if err == EOF {
# return n, nil
# }
# return
# }
# }
# }
# # NopCloser returns a [ReadCloser] with a no-op Close method wrapping
# # the provided [Reader] r.
# # If r implements [WriterTo], the returned [ReadCloser] will implement [WriterTo]
# # by forwarding calls to r.
# fn NopCloser(r Reader) ReadCloser {
# if _, ok := r.(WriterTo); ok {
# return nopCloserWriterTo{r}
# }
# return nopCloser{r}
# }
# type nopCloser struct {
# Reader
# }
# fn (nopCloser) Close() error { return nil }
# type nopCloserWriterTo struct {
# Reader
# }
# fn (nopCloserWriterTo) Close() error { return nil }
# fn (c nopCloserWriterTo) WriteTo(w Writer) (n Int, err error) {
# return c.Reader.(WriterTo).WriteTo(w)
# }
# TODO: read directly into dest
fn read_all[R: Reader](inout reader: R) -> (List[Byte], Error):
"""Reads from r until an error or EOF and returns the data it read.
A successful call returns err == nil, not err == EOF. Because ReadAll is
defined to read from src until EOF, it does not treat an EOF from Read
as an error to be reported.
Args:
reader: The reader to read from.
Returns:
The data read."""
var dest = List[Byte](capacity=BUFFER_SIZE)
var at_eof: Bool = False
while True:
var temp = List[Byte](capacity=BUFFER_SIZE)
var bytes_read: Int
var err: Error
bytes_read, err = reader.read(temp)
if str(err) != "":
if str(err) != str(EOF):
return dest, err
at_eof = True
# If new bytes will overflow the result, resize it.
# if some bytes were written, how do I append before returning result on the last one?
if len(dest) + len(temp) > dest.capacity:
dest.reserve(dest.capacity * 2)
dest.extend(temp)
if at_eof:
return dest, err
| gojo/gojo/io/io.mojo | false |
import ..io
from ..syscall import FD
@value
struct STDWriter[file_descriptor: Int](Copyable, io.Writer, io.StringWriter):
"""A writer for POSIX file descriptors."""
@always_inline
fn __init__(inout self):
constrained[
file_descriptor == FD.STDOUT or file_descriptor == FD.STDERR,
"The STDWriter Struct is meant to write to STDOUT and STDERR. file_descriptor must be 1 or 2.",
]()
@always_inline
fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
"""Writes the given bytes to the file descriptor.
Args:
src: The bytes to write to the file descriptor.
Returns:
The number of bytes written to the file descriptor.
"""
var write_count: Int = external_call["write", Int, Int32, UnsafePointer[UInt8], Int](
file_descriptor, src.unsafe_ptr(), len(src)
)
if write_count == -1:
return 0, Error("Failed to write to file descriptor " + str(file_descriptor))
return write_count, Error()
@always_inline
fn write(inout self, src: List[UInt8]) -> (Int, Error):
"""Writes the given bytes to the file descriptor.
Args:
src: The bytes to write to the file descriptor.
Returns:
The number of bytes written to the file descriptor.
"""
return self._write(Span(src))
@always_inline
fn write_string(inout self, src: String) -> (Int, Error):
"""Writes the given string to the file descriptor.
Args:
src: The string to write to the file descriptor.
Returns:
The number of bytes written to the file descriptor.
"""
return self._write(src.as_bytes_slice())
@always_inline
fn read_from[R: io.Reader](inout self, inout reader: R) -> (Int, Error):
"""Reads from the given reader to a temporary buffer and writes to the file descriptor.
Args:
reader: The reader to read from.
Returns:
The number of bytes written to the file descriptor.
"""
var buffer = List[UInt8](capacity=io.BUFFER_SIZE)
_ = reader.read(buffer)
return self._write(Span(buffer))
| gojo/gojo/io/std.mojo | false |
<filename>gojo/gojo/io/__init__.mojo
from .io import write_string, read_at_least, read_full, read_all, BUFFER_SIZE
from .file import FileWrapper
from .std import STDWriter
alias Rune = Int32
# Package io provides basic interfaces to I/O primitives.
# Its primary job is to wrap existing implementations of such primitives,
# such as those in package os, into shared public interfaces that
# abstract the fntionality, plus some other related primitives.
#
# Because these interfaces and primitives wrap lower-level operations with
# various implementations, unless otherwise informed clients should not
# assume they are safe for parallel execution.
# Seek whence values.
alias SEEK_START = 0 # seek relative to the origin of the file
alias SEEK_CURRENT = 1 # seek relative to the current offset
alias SEEK_END = 2 # seek relative to the end
# ERR_SHORT_WRITE means that a write accepted fewer bytes than requested
# but failed to return an explicit error.
alias ERR_SHORT_WRITE = Error("short write")
# ERR_INVALID_WRITE means that a write returned an impossible count.
alias ERR_INVALID_WRITE = Error("invalid write result")
# ERR_SHORT_BUFFER means that a read required a longer buffer than was provided.
alias ERR_SHORT_BUFFER = Error("short buffer")
# EOF is the error returned by Read when no more input is available.
# (Read must return EOF itself, not an error wrapping EOF,
# because callers will test for EOF using ==.)
# fntions should return EOF only to signal a graceful end of input.
# If the EOF occurs unexpectedly in a structured data stream,
# the appropriate error is either [ERR_UNEXPECTED_EOF] or some other error
# giving more detail.
alias EOF = Error("EOF")
# ERR_UNEXPECTED_EOF means that EOF was encountered in the
# middle of reading a fixed-size block or data structure.
alias ERR_UNEXPECTED_EOF = Error("unexpected EOF")
# ERR_NO_PROGRESS is returned by some clients of a [Reader] when
# many calls to Read have failed to return any data or error,
# usually the sign of a broken [Reader] implementation.
alias ERR_NO_PROGRESS = Error("multiple Read calls return no data or error")
trait Reader(Movable):
"""Reader is the trait that wraps the basic Read method.
Read reads up to len(p) bytes into p. It returns the number of bytes
read (0 <= n <= len(p)) and any error encountered. Even if Read
returns n < len(p), it may use all of p as scratch space during the call.
If some data is available but not len(p) bytes, Read conventionally
returns what is available instead of waiting for more.
When Read encounters an error or end-of-file condition after
successfully reading n > 0 bytes, it returns the number of
bytes read. It may return the (non-nil) error from the same call
or return the error (and n == 0) from a subsequent call.
An instance of this general case is that a Reader returning
a non-zero number of bytes at the end of the input stream may
return either err == EOF or err == nil. The next Read should
return 0, EOF.
Callers should always process the n > 0 bytes returned before
considering the error err. Doing so correctly handles I/O errors
that happen after reading some bytes and also both of the
allowed EOF behaviors.
If len(p) == 0, Read should always return n == 0. It may return a
non-nil error if some error condition is known, such as EOF.
Implementations of Read are discouraged from returning a
zero byte count with a nil error, except when len(p) == 0.
Callers should treat a return of 0 and nil as indicating that
nothing happened; in particular it does not indicate EOF.
Implementations must not retain p."""
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
...
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
...
trait Writer(Movable):
"""Writer is the trait that wraps the basic Write method.
Write writes len(p) bytes from p to the underlying data stream.
It returns the number of bytes written from p (0 <= n <= len(p))
and any error encountered that caused the write to stop early.
Write must return a non-nil error if it returns n < len(p).
Write must not modify the slice data, even temporarily.
Implementations must not retain p.
"""
# fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
# ...
fn write(inout self, src: List[UInt8]) -> (Int, Error):
...
trait Closer(Movable):
"""
Closer is the trait that wraps the basic Close method.
The behavior of Close after the first call is undefined.
Specific implementations may document their own behavior.
"""
fn close(inout self) -> Error:
...
trait Seeker(Movable):
"""
Seeker is the trait that wraps the basic Seek method.
Seek sets the offset for the next Read or Write to offset,
interpreted according to whence:
[SEEK_START] means relative to the start of the file,
[SEEK_CURRENT] means relative to the current offset, and
[SEEK_END] means relative to the end
(for example, offset = -2 specifies the penultimate byte of the file).
Seek returns the new offset relative to the start of the
file or an error, if any.
Seeking to an offset before the start of the file is an error.
Seeking to any positive offset may be allowed, but if the new offset exceeds
the size of the underlying object the behavior of subsequent I/O operations
is implementation-dependent.
"""
fn seek(inout self, offset: Int, whence: Int) -> (Int, Error):
...
trait ReadWriter(Reader, Writer):
...
trait ReadCloser(Reader, Closer):
...
trait WriteCloser(Writer, Closer):
...
trait ReadWriteCloser(Reader, Writer, Closer):
...
trait ReadSeeker(Reader, Seeker):
...
trait ReadSeekCloser(Reader, Seeker, Closer):
...
trait WriteSeeker(Writer, Seeker):
...
trait ReadWriteSeeker(Reader, Writer, Seeker):
...
trait ReaderFrom:
"""ReaderFrom is the trait that wraps the ReadFrom method.
ReadFrom reads data from r until EOF or error.
The return value n is the number of bytes read.
Any error except EOF encountered during the read is also returned.
The [copy] function uses [ReaderFrom] if available."""
fn read_from[R: Reader](inout self, inout reader: R) -> (Int, Error):
...
trait WriterReadFrom(Writer, ReaderFrom):
...
trait WriterTo:
"""WriterTo is the trait that wraps the WriteTo method.
WriteTo writes data to w until there's no more data to write or
when an error occurs. The return value n is the number of bytes
written. Any error encountered during the write is also returned.
The copy function uses WriterTo if available."""
fn write_to[W: Writer](inout self, inout writer: W) -> (Int, Error):
...
trait ReaderWriteTo(Reader, WriterTo):
...
trait ReaderAt:
"""ReaderAt is the trait that wraps the basic ReadAt method.
ReadAt reads len(p) bytes into p starting at offset off in the
underlying input source. It returns the number of bytes
read (0 <= n <= len(p)) and any error encountered.
When ReadAt returns n < len(p), it returns a non-nil error
explaining why more bytes were not returned. In this respect,
ReadAt is stricter than Read.
Even if ReadAt returns n < len(p), it may use all of p as scratch
space during the call. If some data is available but not len(p) bytes,
ReadAt blocks until either all the data is available or an error occurs.
In this respect ReadAt is different from Read.
If the n = len(p) bytes returned by ReadAt are at the end of the
input source, ReadAt may return either err == EOF or err == nil.
If ReadAt is reading from an input source with a seek offset,
ReadAt should not affect nor be affected by the underlying
seek offset.
Clients of ReadAt can execute parallel ReadAt calls on the
same input source.
Implementations must not retain p."""
fn read_at(self, inout dest: List[UInt8], off: Int) -> (Int, Error):
...
fn _read_at(self, inout dest: Span[UInt8, True], off: Int, capacity: Int) -> (Int, Error):
...
trait WriterAt:
"""WriterAt is the trait that wraps the basic WriteAt method.
WriteAt writes len(p) bytes from p to the underlying data stream
at offset off. It returns the number of bytes written from p (0 <= n <= len(p))
and any error encountered that caused the write to stop early.
WriteAt must return a non-nil error if it returns n < len(p).
If WriteAt is writing to a destination with a seek offset,
WriteAt should not affect nor be affected by the underlying
seek offset.
Clients of WriteAt can execute parallel WriteAt calls on the same
destination if the ranges do not overlap.
Implementations must not retain p."""
fn _write_at(self, src: Span[UInt8], off: Int) -> (Int, Error):
...
fn write_at(self, src: List[UInt8], off: Int) -> (Int, Error):
...
trait ByteReader:
"""ByteReader is the trait that wraps the read_byte method.
read_byte reads and returns the next byte from the input or
any error encountered. If read_byte returns an error, no input
byte was consumed, and the returned byte value is undefined.
read_byte provides an efficient trait for byte-at-time
processing. A [Reader] that does not implement ByteReader
can be wrapped using bufio.NewReader to add this method."""
fn read_byte(inout self) -> (UInt8, Error):
...
trait ByteScanner(ByteReader):
"""ByteScanner is the trait that adds the unread_byte method to the
basic read_byte method.
unread_byte causes the next call to read_byte to return the last byte read.
If the last operation was not a successful call to read_byte, unread_byte may
return an error, unread the last byte read (or the byte prior to the
last-unread byte), or (in implementations that support the [Seeker] trait)
seek to one byte before the current offset."""
fn unread_byte(inout self) -> Error:
...
trait ByteWriter:
"""ByteWriter is the trait that wraps the write_byte method."""
fn write_byte(inout self, byte: UInt8) -> (Int, Error):
...
trait RuneReader:
"""RuneReader is the trait that wraps the read_rune method.
read_rune reads a single encoded Unicode character
and returns the rune and its size in bytes. If no character is
available, err will be set."""
fn read_rune(inout self) -> (Rune, Int):
...
trait RuneScanner(RuneReader):
"""RuneScanner is the trait that adds the unread_rune method to the
basic read_rune method.
unread_rune causes the next call to read_rune to return the last rune read.
If the last operation was not a successful call to read_rune, unread_rune may
return an error, unread the last rune read (or the rune prior to the
last-unread rune), or (in implementations that support the [Seeker] trait)
seek to the start of the rune before the current offset."""
fn unread_rune(inout self) -> Rune:
...
trait StringWriter:
"""StringWriter is the trait that wraps the WriteString method."""
fn write_string(inout self, src: String) -> (Int, Error):
...
| gojo/gojo/io/__init__.mojo | false |
@value
struct NetworkType:
var value: String
alias empty = NetworkType("")
alias tcp = NetworkType("tcp")
alias tcp4 = NetworkType("tcp4")
alias tcp6 = NetworkType("tcp6")
alias udp = NetworkType("udp")
alias udp4 = NetworkType("udp4")
alias udp6 = NetworkType("udp6")
alias ip = NetworkType("ip")
alias ip4 = NetworkType("ip4")
alias ip6 = NetworkType("ip6")
alias unix = NetworkType("unix")
trait Addr(CollectionElement, Stringable):
fn network(self) -> String:
"""Name of the network (for example, "tcp", "udp")."""
...
@value
struct BaseAddr:
"""Addr struct representing a TCP address.
Args:
ip: IP address.
port: Port number.
zone: IPv6 addressing zone.
"""
var ip: String
var port: Int
var zone: String # IPv6 addressing zone
fn __init__(inout self, ip: String = "", port: Int = 0, zone: String = ""):
self.ip = ip
self.port = port
self.zone = zone
fn __init__(inout self, other: TCPAddr):
self.ip = other.ip
self.port = other.port
self.zone = other.zone
fn __init__(inout self, other: UDPAddr):
self.ip = other.ip
self.port = other.port
self.zone = other.zone
fn __str__(self) -> String:
if self.zone != "":
return join_host_port(self.ip + "%" + self.zone, str(self.port))
return join_host_port(self.ip, str(self.port))
fn resolve_internet_addr(network: String, address: String) -> (TCPAddr, Error):
var host: String = ""
var port: String = ""
var portnum: Int = 0
var err = Error()
if (
network == NetworkType.tcp.value
or network == NetworkType.tcp4.value
or network == NetworkType.tcp6.value
or network == NetworkType.udp.value
or network == NetworkType.udp4.value
or network == NetworkType.udp6.value
):
if address != "":
var result = split_host_port(address)
if result[1]:
return TCPAddr(), result[1]
host = result[0].host
port = str(result[0].port)
portnum = result[0].port
elif network == NetworkType.ip.value or network == NetworkType.ip4.value or network == NetworkType.ip6.value:
if address != "":
host = address
elif network == NetworkType.unix.value:
return TCPAddr(), Error("Unix addresses not supported yet")
else:
return TCPAddr(), Error("unsupported network type: " + network)
return TCPAddr(host, portnum), err
alias MISSING_PORT_ERROR = Error("missing port in address")
alias TOO_MANY_COLONS_ERROR = Error("too many colons in address")
@value
struct HostPort(Stringable):
var host: String
var port: Int
fn __init__(inout self, host: String = "", port: Int = 0):
self.host = host
self.port = port
fn __str__(self) -> String:
return join_host_port(self.host, str(self.port))
fn join_host_port(host: String, port: String) -> String:
if host.find(":") != -1: # must be IPv6 literal
return "[" + host + "]:" + port
return host + ":" + port
fn split_host_port(hostport: String) -> (HostPort, Error):
var host: String = ""
var port: String = ""
var colon_index = hostport.rfind(":")
var j: Int = 0
var k: Int = 0
if colon_index == -1:
return HostPort(), MISSING_PORT_ERROR
if hostport[0] == "[":
var end_bracket_index = hostport.find("]")
if end_bracket_index == -1:
return HostPort(), Error("missing ']' in address")
if end_bracket_index + 1 == len(hostport):
return HostPort(), MISSING_PORT_ERROR
elif end_bracket_index + 1 == colon_index:
host = hostport[1:end_bracket_index]
j = 1
k = end_bracket_index + 1
else:
if hostport[end_bracket_index + 1] == ":":
return HostPort(), TOO_MANY_COLONS_ERROR
else:
return HostPort(), MISSING_PORT_ERROR
else:
host = hostport[:colon_index]
if host.find(":") != -1:
return HostPort(), TOO_MANY_COLONS_ERROR
if hostport[j:].find("[") != -1:
return HostPort(), Error("unexpected '[' in address")
if hostport[k:].find("]") != -1:
return HostPort(), Error("unexpected ']' in address")
port = hostport[colon_index + 1 :]
if port == "":
return HostPort(), MISSING_PORT_ERROR
if host == "":
return HostPort(), Error("missing host")
try:
return HostPort(host, atol(port)), Error()
except e:
return HostPort(), e
| gojo/gojo/net/address.mojo | false |
import ..io
from ..syscall import (
recv,
send,
close,
FileDescriptorBase,
)
alias O_RDWR = 0o2
struct FileDescriptor(FileDescriptorBase):
var fd: Int
var is_closed: Bool
@always_inline
fn __init__(inout self, fd: Int):
self.fd = fd
self.is_closed = False
@always_inline
fn __moveinit__(inout self, owned existing: Self):
self.fd = existing.fd
self.is_closed = existing.is_closed
@always_inline
fn __del__(owned self):
if not self.is_closed:
var err = self.close()
if err:
print(str(err))
@always_inline
fn close(inout self) -> Error:
"""Mark the file descriptor as closed."""
var close_status = close(self.fd)
if close_status == -1:
return Error("FileDescriptor.close: Failed to close socket")
self.is_closed = True
return Error()
@always_inline
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Receive data from the file descriptor and write it to the buffer provided."""
var bytes_received = recv(
self.fd,
dest.unsafe_ptr() + len(dest),
capacity - len(dest),
0,
)
if bytes_received == 0:
return bytes_received, io.EOF
if bytes_received == -1:
return 0, Error("Failed to receive message from socket.")
dest._len += bytes_received
return bytes_received, Error()
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Receive data from the file descriptor and write it to the buffer provided."""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn write(inout self, src: List[UInt8]) -> (Int, Error):
"""Write data from the buffer to the file descriptor."""
return self._write(Span(src))
@always_inline
fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
"""Write data from the buffer to the file descriptor."""
var bytes_sent = send(self.fd, src.unsafe_ptr(), len(src), 0)
if bytes_sent == -1:
return 0, Error("Failed to send message")
return bytes_sent, Error()
| gojo/gojo/net/fd.mojo | false |
<filename>gojo/gojo/net/ip.mojo
from utils.variant import Variant
from utils.static_tuple import StaticTuple
from sys.info import os_is_linux, os_is_macos
from ..syscall import (
c_int,
c_char,
c_void,
c_uint,
addrinfo,
addrinfo_unix,
AddressFamily,
AddressInformation,
SocketOptions,
SocketType,
ProtocolFamily,
sockaddr,
sockaddr_in,
htons,
ntohs,
inet_pton,
inet_ntop,
getaddrinfo,
getaddrinfo_unix,
gai_strerror,
)
from .address import HostPort
alias AddrInfo = Variant[addrinfo, addrinfo_unix]
fn get_addr_info(host: String) raises -> AddrInfo:
if os_is_macos():
var servinfo = UnsafePointer[addrinfo]().alloc(1)
servinfo[0] = addrinfo()
var hints = addrinfo(
ai_family=AddressFamily.AF_INET,
ai_socktype=SocketType.SOCK_STREAM,
ai_flags=AddressInformation.AI_PASSIVE,
)
var status = getaddrinfo(
host.unsafe_uint8_ptr(),
UnsafePointer[UInt8](),
UnsafePointer.address_of(hints),
UnsafePointer.address_of(servinfo),
)
if status != 0:
print("getaddrinfo failed to execute with status:", status)
if not servinfo:
print("servinfo is null")
raise Error("Failed to get address info. Pointer to addrinfo is null.")
return move_from_pointee(servinfo)
elif os_is_linux():
var servinfo = UnsafePointer[addrinfo_unix]().alloc(1)
servinfo[0] = addrinfo_unix()
var hints = addrinfo_unix(
ai_family=AddressFamily.AF_INET,
ai_socktype=SocketType.SOCK_STREAM,
ai_flags=AddressInformation.AI_PASSIVE,
)
var status = getaddrinfo_unix(
host.unsafe_uint8_ptr(),
UnsafePointer[UInt8](),
UnsafePointer.address_of(hints),
UnsafePointer.address_of(servinfo),
)
if status != 0:
print("getaddrinfo failed to execute with status:", status)
if not servinfo:
print("servinfo is null")
raise Error("Failed to get address info. Pointer to addrinfo is null.")
return move_from_pointee(servinfo)
else:
raise Error("Windows is not supported yet! Sorry!")
fn get_ip_address(host: String) raises -> String:
"""Get the IP address of a host."""
# Call getaddrinfo to get the IP address of the host.
var result = get_addr_info(host)
var ai_addr: UnsafePointer[sockaddr]
var address_family: Int32 = 0
var address_length: UInt32 = 0
if result.isa[addrinfo]():
var addrinfo = result[addrinfo]
ai_addr = addrinfo.ai_addr
address_family = addrinfo.ai_family
address_length = addrinfo.ai_addrlen
else:
var addrinfo = result[addrinfo_unix]
ai_addr = addrinfo.ai_addr
address_family = addrinfo.ai_family
address_length = addrinfo.ai_addrlen
if not ai_addr:
print("ai_addr is null")
raise Error("Failed to get IP address. getaddrinfo was called successfully, but ai_addr is null.")
# Cast sockaddr struct to sockaddr_in struct and convert the binary IP to a string using inet_ntop.
var addr_in = move_from_pointee(ai_addr.bitcast[sockaddr_in]())
return convert_binary_ip_to_string(addr_in.sin_addr.s_addr, address_family, address_length).strip()
fn convert_port_to_binary(port: Int) -> UInt16:
return htons(UInt16(port))
fn convert_binary_port_to_int(port: UInt16) -> Int:
return int(ntohs(port))
fn convert_ip_to_binary(ip_address: String, address_family: Int) -> UInt32:
var ip_buffer = UnsafePointer[UInt8].alloc(4)
var status = inet_pton(address_family, ip_address.unsafe_uint8_ptr(), ip_buffer)
if status == -1:
print("Failed to convert IP address to binary")
return move_from_pointee(ip_buffer.bitcast[c_uint]())
fn convert_binary_ip_to_string(owned ip_address: UInt32, address_family: Int32, address_length: UInt32) -> String:
"""Convert a binary IP address to a string by calling inet_ntop.
Args:
ip_address: The binary IP address.
address_family: The address family of the IP address.
address_length: The length of the address.
Returns:
The IP address as a string.
"""
# It seems like the len of the buffer depends on the length of the string IP.
# Allocating 10 works for localhost (127.0.0.1) which I suspect is 9 bytes + 1 null terminator byte. So max should be 16 (15 + 1).
var ip_buffer = UnsafePointer[c_void].alloc(16)
var ip_address_ptr = UnsafePointer.address_of(ip_address).bitcast[c_void]()
_ = inet_ntop(address_family, ip_address_ptr, ip_buffer, 16)
var index = 0
while True:
if ip_buffer[index] == 0:
break
index += 1
return StringRef(ip_buffer, index)
fn build_sockaddr_pointer(ip_address: String, port: Int, address_family: Int) -> UnsafePointer[sockaddr]:
"""Build a sockaddr pointer from an IP address and port number.
https://learn.microsoft.com/en-us/windows/win32/winsock/sockaddr-2
https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-sockaddr_in.
"""
var bin_port = convert_port_to_binary(port)
var bin_ip = convert_ip_to_binary(ip_address, address_family)
var ai = sockaddr_in(address_family, bin_port, bin_ip, StaticTuple[c_char, 8]())
return UnsafePointer[sockaddr_in].address_of(ai).bitcast[sockaddr]()
fn convert_sockaddr_to_host_port(sockaddr: UnsafePointer[sockaddr]) -> (HostPort, Error):
"""Casts a sockaddr pointer to a sockaddr_in pointer and converts the binary IP and port to a string and int respectively.
Args:
sockaddr: The sockaddr pointer to convert.
Returns:
A tuple containing the HostPort and an Error if any occurred,.
"""
if not sockaddr:
return HostPort(), Error("sockaddr is null, nothing to convert.")
# Cast sockaddr struct to sockaddr_in to convert binary IP to string.
var addr_in = move_from_pointee(sockaddr.bitcast[sockaddr_in]())
return (
HostPort(
host=convert_binary_ip_to_string(addr_in.sin_addr.s_addr, AddressFamily.AF_INET, 16),
port=convert_binary_port_to_int(addr_in.sin_port),
),
Error(),
)
| gojo/gojo/net/ip.mojo | false |
<filename>gojo/gojo/net/socket.mojo
from ..syscall import (
sockaddr,
sockaddr_in,
addrinfo,
addrinfo_unix,
socklen_t,
c_void,
c_uint,
c_char,
c_int,
socket,
connect,
recv,
recvfrom,
send,
sendto,
shutdown,
inet_pton,
inet_ntoa,
inet_ntop,
htons,
ntohs,
getaddrinfo,
getaddrinfo_unix,
gai_strerror,
bind,
listen,
accept,
setsockopt,
getsockopt,
getsockname,
getpeername,
AddressFamily,
AddressInformation,
SocketOptions,
SocketType,
SHUT_RDWR,
SOL_SOCKET,
close,
)
from .fd import FileDescriptor, FileDescriptorBase
from .ip import (
convert_binary_ip_to_string,
build_sockaddr_pointer,
convert_binary_port_to_int,
convert_sockaddr_to_host_port,
)
from .address import Addr, BaseAddr, HostPort
alias SocketClosedError = Error("Socket: Socket is already closed")
struct Socket(FileDescriptorBase):
"""Represents a network file descriptor. Wraps around a file descriptor and provides network functions.
Args:
local_address: The local address of the socket (local address if bound).
remote_address: The remote address of the socket (peer's address if connected).
address_family: The address family of the socket.
socket_type: The socket type.
protocol: The protocol.
"""
var fd: FileDescriptor
var address_family: Int
var socket_type: Int32
var protocol: UInt8
var local_address: BaseAddr
var remote_address: BaseAddr
var _closed: Bool
var _is_connected: Bool
fn __init__(
inout self,
local_address: BaseAddr = BaseAddr(),
remote_address: BaseAddr = BaseAddr(),
address_family: Int = AddressFamily.AF_INET,
socket_type: Int32 = SocketType.SOCK_STREAM,
protocol: UInt8 = 0,
) raises:
"""Create a new socket object.
Args:
local_address: The local address of the socket (local address if bound).
remote_address: The remote address of the socket (peer's address if connected).
address_family: The address family of the socket.
socket_type: The socket type.
protocol: The protocol.
"""
self.address_family = address_family
self.socket_type = socket_type
self.protocol = protocol
var fd = socket(address_family, socket_type, 0)
if fd == -1:
raise Error("Socket creation error")
self.fd = FileDescriptor(int(fd))
self.local_address = local_address
self.remote_address = remote_address
self._closed = False
self._is_connected = False
fn __init__(
inout self,
fd: Int32,
address_family: Int,
socket_type: Int32,
protocol: UInt8,
local_address: BaseAddr = BaseAddr(),
remote_address: BaseAddr = BaseAddr(),
):
"""
Create a new socket object when you already have a socket file descriptor. Typically through socket.accept().
Args:
fd: The file descriptor of the socket.
address_family: The address family of the socket.
socket_type: The socket type.
protocol: The protocol.
local_address: The local address of the socket (local address if bound).
remote_address: The remote address of the socket (peer's address if connected).
"""
self.fd = FileDescriptor(int(fd))
self.address_family = address_family
self.socket_type = socket_type
self.protocol = protocol
self.local_address = local_address
self.remote_address = remote_address
self._closed = False
self._is_connected = True
fn __moveinit__(inout self, owned existing: Self):
self.fd = existing.fd^
self.address_family = existing.address_family
self.socket_type = existing.socket_type
self.protocol = existing.protocol
self.local_address = existing.local_address^
self.remote_address = existing.remote_address^
self._closed = existing._closed
self._is_connected = existing._is_connected
# fn __enter__(self) -> Self:
# return self
# fn __exit__(inout self) raises:
# if self._is_connected:
# self.shutdown()
# if not self._closed:
# var err = self.close()
# if err:
# raise err
fn __del__(owned self):
if self._is_connected:
self.shutdown()
if not self._closed:
var err = self.close()
_ = self.fd.fd
if err:
print("Failed to close socket during deletion:", str(err))
@always_inline
fn local_address_as_udp(self) -> UDPAddr:
return UDPAddr(self.local_address)
@always_inline
fn local_address_as_tcp(self) -> TCPAddr:
return TCPAddr(self.local_address)
@always_inline
fn remote_address_as_udp(self) -> UDPAddr:
return UDPAddr(self.remote_address)
@always_inline
fn remote_address_as_tcp(self) -> TCPAddr:
return TCPAddr(self.remote_address)
@always_inline
fn accept(self) raises -> Socket:
"""Accept a connection. The socket must be bound to an address and listening for connections.
The return value is a connection where conn is a new socket object usable to send and receive data on the connection,
and address is the address bound to the socket on the other end of the connection.
"""
var remote_address_ptr = UnsafePointer[sockaddr].alloc(1)
var sin_size = socklen_t(sizeof[socklen_t]())
var new_fd = accept(
self.fd.fd,
remote_address_ptr,
UnsafePointer[socklen_t].address_of(sin_size),
)
if new_fd == -1:
raise Error("Failed to accept connection")
var remote: HostPort
var err: Error
remote, err = convert_sockaddr_to_host_port(remote_address_ptr)
if err:
raise err
return Socket(
new_fd,
self.address_family,
self.socket_type,
self.protocol,
self.local_address,
BaseAddr(remote.host, remote.port),
)
fn listen(self, backlog: Int = 0) raises:
"""Enable a server to accept connections.
Args:
backlog: The maximum number of queued connections. Should be at least 0, and the maximum is system-dependent (usually 5).
"""
var queued = backlog
if backlog < 0:
queued = 0
if listen(self.fd.fd, queued) == -1:
raise Error("Failed to listen for connections")
@always_inline
fn bind(inout self, address: String, port: Int) raises:
"""Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family).
When a socket is created with Socket(), it exists in a name
space (address family) but has no address assigned to it. bind()
assigns the address specified by addr to the socket referred to
by the file descriptor fd. addrlen specifies the size, in
bytes, of the address structure pointed to by addr.
Traditionally, this operation is called 'assigning a name to a
socket'.
Args:
address: String - The IP address to bind the socket to.
port: The port number to bind the socket to.
"""
var sockaddr_pointer = build_sockaddr_pointer(address, port, self.address_family)
if bind(self.fd.fd, sockaddr_pointer, sizeof[sockaddr_in]()) == -1:
_ = shutdown(self.fd.fd, SHUT_RDWR)
raise Error("Binding socket failed. Wait a few seconds and try again?")
var local = self.get_sock_name()
self.local_address = BaseAddr(local.host, local.port)
@always_inline
fn file_no(self) -> Int32:
"""Return the file descriptor of the socket."""
return self.fd.fd
@always_inline
fn get_sock_name(self) raises -> HostPort:
"""Return the address of the socket."""
if self._closed:
raise SocketClosedError
# TODO: Add check to see if the socket is bound and error if not.
var local_address_ptr = UnsafePointer[sockaddr].alloc(1)
var local_address_ptr_size = socklen_t(sizeof[sockaddr]())
var status = getsockname(
self.fd.fd,
local_address_ptr,
UnsafePointer[socklen_t].address_of(local_address_ptr_size),
)
if status == -1:
raise Error("Socket.get_sock_name: Failed to get address of local socket.")
var addr_in = move_from_pointee(local_address_ptr.bitcast[sockaddr_in]())
return HostPort(
host=convert_binary_ip_to_string(addr_in.sin_addr.s_addr, AddressFamily.AF_INET, 16),
port=convert_binary_port_to_int(addr_in.sin_port),
)
fn get_peer_name(self) -> (HostPort, Error):
"""Return the address of the peer connected to the socket."""
if self._closed:
return HostPort(), SocketClosedError
# TODO: Add check to see if the socket is bound and error if not.
var remote_address_ptr = UnsafePointer[sockaddr].alloc(1)
var remote_address_ptr_size = socklen_t(sizeof[sockaddr]())
var status = getpeername(
self.fd.fd,
remote_address_ptr,
UnsafePointer[socklen_t].address_of(remote_address_ptr_size),
)
if status == -1:
return HostPort(), Error("Socket.get_peer_name: Failed to get address of remote socket.")
var remote: HostPort
var err: Error
remote, err = convert_sockaddr_to_host_port(remote_address_ptr)
if err:
return HostPort(), err
return remote, Error()
fn get_socket_option(self, option_name: Int) raises -> Int:
"""Return the value of the given socket option.
Args:
option_name: The socket option to get.
"""
var option_value_pointer = UnsafePointer[c_void].alloc(1)
var option_len = socklen_t(sizeof[socklen_t]())
var option_len_pointer = UnsafePointer.address_of(option_len)
var status = getsockopt(
self.fd.fd,
SOL_SOCKET,
option_name,
option_value_pointer,
option_len_pointer,
)
if status == -1:
raise Error("Socket.get_sock_opt failed with status: " + str(status))
return move_from_pointee(option_value_pointer.bitcast[Int]())
fn set_socket_option(self, option_name: Int, owned option_value: UInt8 = 1) raises:
"""Return the value of the given socket option.
Args:
option_name: The socket option to set.
option_value: The value to set the socket option to.
"""
var option_value_pointer = UnsafePointer[c_void].address_of(option_value)
var option_len = sizeof[socklen_t]()
var status = setsockopt(
self.fd.fd,
SOL_SOCKET,
option_name,
option_value_pointer,
option_len,
)
if status == -1:
raise Error("Socket.set_sock_opt failed with status: " + str(status))
fn connect(inout self, address: String, port: Int) -> Error:
"""Connect to a remote socket at address.
Args:
address: String - The IP address to connect to.
port: The port number to connect to.
"""
var sockaddr_pointer = build_sockaddr_pointer(address, port, self.address_family)
if connect(self.fd.fd, sockaddr_pointer, sizeof[sockaddr_in]()) == -1:
self.shutdown()
return Error("Socket.connect: Failed to connect to the remote socket at: " + address + ":" + str(port))
var remote: HostPort
var err: Error
remote, err = self.get_peer_name()
if err:
return err
self.remote_address = BaseAddr(remote.host, remote.port)
return Error()
@always_inline
fn _write(inout self: Self, src: Span[UInt8]) -> (Int, Error):
"""Send data to the socket. The socket must be connected to a remote socket.
Args:
src: The data to send.
Returns:
The number of bytes sent.
"""
return self.fd._write(src)
@always_inline
fn write(inout self: Self, src: List[UInt8]) -> (Int, Error):
"""Send data to the socket. The socket must be connected to a remote socket.
Args:
src: The data to send.
Returns:
The number of bytes sent.
"""
return self.fd.write(src)
fn send_all(self, src: Span[UInt8], max_attempts: Int = 3) -> Error:
"""Send data to the socket. The socket must be connected to a remote socket.
Args:
src: The data to send.
max_attempts: The maximum number of attempts to send the data.
"""
var bytes_to_send = len(src)
var total_bytes_sent = 0
var attempts = 0
# Try to send all the data in the buffer. If it did not send all the data, keep trying but start from the offset of the last successful send.
while total_bytes_sent < len(src):
if attempts > max_attempts:
return Error("Failed to send message after " + str(max_attempts) + " attempts.")
var bytes_sent = send(
self.fd.fd,
src.unsafe_ptr() + total_bytes_sent,
bytes_to_send - total_bytes_sent,
0,
)
if bytes_sent == -1:
return Error("Failed to send message, wrote" + String(total_bytes_sent) + "bytes before failing.")
total_bytes_sent += bytes_sent
attempts += 1
return Error()
@always_inline
fn send_to(inout self, src: Span[UInt8], address: String, port: Int) -> (Int, Error):
"""Send data to the a remote address by connecting to the remote socket before sending.
The socket must be not already be connected to a remote socket.
Args:
src: The data to send.
address: The IP address to connect to.
port: The port number to connect to.
"""
var bytes_sent = sendto(
self.fd.fd,
src.unsafe_ptr(),
len(src),
0,
build_sockaddr_pointer(address, port, self.address_family),
sizeof[sockaddr_in](),
)
if bytes_sent == -1:
return 0, Error("Socket.send_to: Failed to send message to remote socket at: " + address + ":" + str(port))
return bytes_sent, Error()
@always_inline
fn receive(inout self, size: Int = io.BUFFER_SIZE) -> (List[UInt8], Error):
"""Receive data from the socket into the buffer with capacity of `size` bytes.
Args:
size: The size of the buffer to receive data into.
Returns:
The buffer with the received data, and an error if one occurred.
"""
var buffer = UnsafePointer[UInt8].alloc(size)
var bytes_received = recv(
self.fd.fd,
buffer,
size,
0,
)
if bytes_received == -1:
return List[UInt8](), Error("Socket.receive: Failed to receive message from socket.")
var bytes = List[UInt8](unsafe_pointer=buffer, size=bytes_received, capacity=size)
if bytes_received < bytes.capacity:
return bytes, io.EOF
return bytes, Error()
@always_inline
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Receive data from the socket into the buffer dest. Equivalent to recv_into().
Args:
dest: The buffer to read data into.
capacity: The capacity of the buffer.
Returns:
The number of bytes read, and an error if one occurred.
"""
return self.fd._read(dest, capacity)
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Receive data from the socket into the buffer dest. Equivalent to recv_into().
Args:
dest: The buffer to read data into.
Returns:
The number of bytes read, and an error if one occurred.
"""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn receive_from(inout self, size: Int = io.BUFFER_SIZE) -> (List[UInt8], HostPort, Error):
"""Receive data from the socket into the buffer dest.
Args:
size: The size of the buffer to receive data into.
Returns:
The number of bytes read, the remote address, and an error if one occurred.
"""
var remote_address_ptr = UnsafePointer[sockaddr].alloc(1)
var remote_address_ptr_size = socklen_t(sizeof[sockaddr]())
var buffer = UnsafePointer[UInt8].alloc(size)
var bytes_received = recvfrom(
self.fd.fd,
buffer,
size,
0,
remote_address_ptr,
UnsafePointer[socklen_t].address_of(remote_address_ptr_size),
)
if bytes_received == -1:
return List[UInt8](), HostPort(), Error("Failed to read from socket, received a -1 response.")
var remote: HostPort
var err: Error
remote, err = convert_sockaddr_to_host_port(remote_address_ptr)
if err:
return List[UInt8](), HostPort(), err
var bytes = List[UInt8](unsafe_pointer=buffer, size=bytes_received, capacity=size)
if bytes_received < bytes.capacity:
return bytes, remote, io.EOF
return bytes, remote, Error()
@always_inline
fn receive_from_into(inout self, inout dest: List[UInt8]) -> (Int, HostPort, Error):
"""Receive data from the socket into the buffer dest."""
var remote_address_ptr = UnsafePointer[sockaddr].alloc(1)
var remote_address_ptr_size = socklen_t(sizeof[sockaddr]())
var bytes_read = recvfrom(
self.fd.fd,
dest.unsafe_ptr() + dest.size,
dest.capacity - dest.size,
0,
remote_address_ptr,
UnsafePointer[socklen_t].address_of(remote_address_ptr_size),
)
dest.size += bytes_read
if bytes_read == -1:
return 0, HostPort(), Error("Socket.receive_from_into: Failed to read from socket, received a -1 response.")
var remote: HostPort
var err: Error
remote, err = convert_sockaddr_to_host_port(remote_address_ptr)
if err:
return 0, HostPort(), err
if bytes_read < dest.capacity:
return bytes_read, remote, io.EOF
return bytes_read, remote, Error()
@always_inline
fn shutdown(self):
_ = shutdown(self.fd.fd, SHUT_RDWR)
@always_inline
fn close(inout self) -> Error:
"""Mark the socket closed.
Once that happens, all future operations on the socket object will fail.
The remote end will receive no more data (after queued data is flushed).
"""
self.shutdown()
var err = self.fd.close()
if err:
return err
self._closed = True
return Error()
# TODO: Trying to set timeout fails, but some other options don't?
# fn get_timeout(self) raises -> Int:
# """Return the timeout value for the socket."""
# return self.get_socket_option(SocketOptions.SO_RCVTIMEO)
# fn set_timeout(self, owned duration: Int) raises:
# """Set the timeout value for the socket.
# Args:
# duration: Seconds - The timeout duration in seconds.
# """
# self.set_socket_option(SocketOptions.SO_RCVTIMEO, duration)
@always_inline
fn send_file(self, file: FileHandle) -> Error:
try:
var bytes = file.read_bytes()
return self.send_all(Span(bytes))
except e:
return e
| gojo/gojo/net/socket.mojo | false |
from collections import InlineList
from ..syscall import SocketOptions
from .address import NetworkType, split_host_port, join_host_port, BaseAddr, resolve_internet_addr, HostPort
from .socket import Socket
@value
struct TCPAddr(Addr):
"""Addr struct representing a TCP address.
Args:
ip: IP address.
port: Port number.
zone: IPv6 addressing zone.
"""
var ip: String
var port: Int
var zone: String # IPv6 addressing zone
fn __init__(inout self, ip: String = "127.0.0.1", port: Int = 8000, zone: String = ""):
self.ip = ip
self.port = port
self.zone = zone
fn __init__(inout self, addr: BaseAddr):
self.ip = addr.ip
self.port = addr.port
self.zone = addr.zone
fn __str__(self) -> String:
if self.zone != "":
return join_host_port(str(self.ip) + "%" + self.zone, str(self.port))
return join_host_port(self.ip, str(self.port))
fn network(self) -> String:
return NetworkType.tcp.value
struct TCPConnection(Movable):
"""TCPConn is an implementation of the Conn interface for TCP network connections.
Args:
connection: The underlying Connection.
"""
var socket: Socket
@always_inline
fn __init__(inout self, owned socket: Socket):
self.socket = socket^
@always_inline
fn __moveinit__(inout self, owned existing: Self):
self.socket = existing.socket^
@always_inline
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Reads data from the underlying file descriptor.
Args:
dest: The buffer to read data into.
capacity: The capacity of the destination buffer.
Returns:
The number of bytes read, or an error if one occurred.
"""
var bytes_read: Int
var err = Error()
bytes_read, err = self.socket._read(dest, capacity)
if err:
if str(err) != str(io.EOF):
return bytes_read, err
return bytes_read, err
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Reads data from the underlying file descriptor.
Args:
dest: The buffer to read data into.
Returns:
The number of bytes read, or an error if one occurred.
"""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
"""Writes data to the underlying file descriptor.
Args:
src: The buffer to read data into.
Returns:
The number of bytes written, or an error if one occurred.
"""
return self.socket._write(src)
@always_inline
fn write(inout self, src: List[UInt8]) -> (Int, Error):
"""Writes data to the underlying file descriptor.
Args:
src: The buffer to read data into.
Returns:
The number of bytes written, or an error if one occurred.
"""
return self.socket.write(src)
@always_inline
fn close(inout self) -> Error:
"""Closes the underlying file descriptor.
Returns:
An error if one occurred, or None if the file descriptor was closed successfully.
"""
return self.socket.close()
@always_inline
fn local_address(self) -> TCPAddr:
"""Returns the local network address.
The Addr returned is shared by all invocations of local_address, so do not modify it.
Returns:
The local network address.
"""
return self.socket.local_address_as_tcp()
@always_inline
fn remote_address(self) -> TCPAddr:
"""Returns the remote network address.
The Addr returned is shared by all invocations of remote_address, so do not modify it.
Returns:
The remote network address.
"""
return self.socket.remote_address_as_tcp()
fn listen_tcp(network: String, local_address: TCPAddr) raises -> TCPListener:
"""Creates a new TCP listener.
Args:
network: The network type.
local_address: The local address to listen on.
"""
var socket = Socket()
socket.bind(local_address.ip, local_address.port)
socket.set_socket_option(SocketOptions.SO_REUSEADDR, 1)
socket.listen()
# print(str("Listening on ") + str(socket.local_address_as_tcp()))
return TCPListener(socket^, network, local_address)
fn listen_tcp(network: String, local_address: String) raises -> TCPListener:
"""Creates a new TCP listener.
Args:
network: The network type.
local_address: The address to listen on. The format is "host:port".
"""
var tcp_addr: TCPAddr
var err: Error
tcp_addr, err = resolve_internet_addr(network, local_address)
if err:
raise err
return listen_tcp(network, tcp_addr)
fn listen_tcp(network: String, host: String, port: Int) raises -> TCPListener:
"""Creates a new TCP listener.
Args:
network: The network type.
host: The address to listen on, in ipv4 format.
port: The port to listen on.
"""
return listen_tcp(network, TCPAddr(host, port))
struct TCPListener:
var socket: Socket
var network_type: String
var address: TCPAddr
fn __init__(
inout self,
owned socket: Socket,
network_type: String,
address: TCPAddr,
):
self.socket = socket^
self.network_type = network_type
self.address = address
fn __moveinit__(inout self, owned existing: Self):
self.socket = existing.socket^
self.network_type = existing.network_type^
self.address = existing.address^
fn accept(self) raises -> TCPConnection:
return TCPConnection(self.socket.accept())
fn close(inout self) -> Error:
return self.socket.close()
alias TCP_NETWORK_TYPES = InlineList[String, 3]("tcp", "tcp4", "tcp6")
fn dial_tcp(network: String, remote_address: TCPAddr) raises -> TCPConnection:
"""Connects to the address on the named network.
The network must be "tcp", "tcp4", or "tcp6".
Args:
network: The network type.
remote_address: The remote address to connect to.
Returns:
The TCP connection.
"""
# TODO: Add conversion of domain name to ip address
if network not in TCP_NETWORK_TYPES:
raise Error("unsupported network type: " + network)
var socket = Socket()
var err = socket.connect(remote_address.ip, remote_address.port)
if err:
raise err
return TCPConnection(socket^)
fn dial_tcp(network: String, remote_address: String) raises -> TCPConnection:
"""Connects to the address on the named network.
The network must be "tcp", "tcp4", or "tcp6".
Args:
network: The network type.
remote_address: The remote address to connect to. (The format is "host:port").
Returns:
The TCP connection.
"""
var remote: HostPort
var err: Error
remote, err = split_host_port(remote_address)
if err:
raise err
return dial_tcp(network, TCPAddr(remote.host, remote.port))
fn dial_tcp(network: String, host: String, port: Int) raises -> TCPConnection:
"""Connects to the address on the named network.
The network must be "tcp", "tcp4", or "tcp6".
Args:
network: The network type.
host: The remote address to connect to in ipv4 format.
port: The remote port.
Returns:
The TCP connection.
"""
return dial_tcp(network, TCPAddr(host, port))
| gojo/gojo/net/tcp.mojo | false |
from collections import InlineList
from ..syscall import SocketOptions, SocketType
from .address import NetworkType, split_host_port, join_host_port, BaseAddr, resolve_internet_addr
from .socket import Socket
# TODO: Change ip to list of bytes
@value
struct UDPAddr(Addr):
"""Represents the address of a UDP end point.
Args:
ip: IP address.
port: Port number.
zone: IPv6 addressing zone.
"""
var ip: String
var port: Int
var zone: String # IPv6 addressing zone
fn __init__(inout self, ip: String = "127.0.0.1", port: Int = 8000, zone: String = ""):
self.ip = ip
self.port = port
self.zone = zone
fn __init__(inout self, addr: BaseAddr):
self.ip = addr.ip
self.port = addr.port
self.zone = addr.zone
fn __str__(self) -> String:
if self.zone != "":
return join_host_port(str(self.ip) + "%" + self.zone, str(self.port))
return join_host_port(self.ip, str(self.port))
fn network(self) -> String:
return NetworkType.udp.value
struct UDPConnection(Movable):
"""Implementation of the Conn interface for TCP network connections."""
var socket: Socket
fn __init__(inout self, owned socket: Socket):
self.socket = socket^
fn __moveinit__(inout self, owned existing: Self):
self.socket = existing.socket^
fn read_from(inout self, inout dest: List[UInt8]) -> (Int, HostPort, Error):
"""Reads data from the underlying file descriptor.
Args:
dest: The buffer to read data into.
Returns:
The number of bytes read, or an error if one occurred.
"""
var bytes_read: Int
var remote: HostPort
var err = Error()
bytes_read, remote, err = self.socket.receive_from_into(dest)
if err:
if str(err) != io.EOF:
return bytes_read, remote, err
return bytes_read, remote, err
fn write_to(inout self, src: Span[UInt8], address: UDPAddr) -> (Int, Error):
"""Writes data to the underlying file descriptor.
Args:
src: The buffer to read data into.
address: The remote peer address.
Returns:
The number of bytes written, or an error if one occurred.
"""
return self.socket.send_to(src, address.ip, address.port)
fn write_to(inout self, src: Span[UInt8], host: String, port: Int) -> (Int, Error):
"""Writes data to the underlying file descriptor.
Args:
src: The buffer to read data into.
host: The remote peer address in IPv4 format.
port: The remote peer port.
Returns:
The number of bytes written, or an error if one occurred.
"""
return self.socket.send_to(src, host, port)
fn close(inout self) -> Error:
"""Closes the underlying file descriptor.
Returns:
An error if one occurred, or None if the file descriptor was closed successfully.
"""
return self.socket.close()
fn local_address(self) -> UDPAddr:
"""Returns the local network address.
The Addr returned is shared by all invocations of local_address, so do not modify it.
Returns:
The local network address.
"""
return self.socket.local_address_as_udp()
fn remote_address(self) -> UDPAddr:
"""Returns the remote network address.
The Addr returned is shared by all invocations of remote_address, so do not modify it.
Returns:
The remote network address.
"""
return self.socket.remote_address_as_udp()
fn listen_udp(network: String, local_address: UDPAddr) raises -> UDPConnection:
"""Creates a new UDP listener.
Args:
network: The network type.
local_address: The local address to listen on.
"""
var socket = Socket(socket_type=SocketType.SOCK_DGRAM)
socket.bind(local_address.ip, local_address.port)
# print(str("Listening on ") + str(socket.local_address_as_udp()))
return UDPConnection(socket^)
fn listen_udp(network: String, local_address: String) raises -> UDPConnection:
"""Creates a new UDP listener.
Args:
network: The network type.
local_address: The address to listen on. The format is "host:port".
"""
var result = split_host_port(local_address)
return listen_udp(network, UDPAddr(result[0].host, result[0].port))
fn listen_udp(network: String, host: String, port: Int) raises -> UDPConnection:
"""Creates a new UDP listener.
Args:
network: The network type.
host: The address to listen on in ipv4 format.
port: The port number.
"""
return listen_udp(network, UDPAddr(host, port))
alias UDP_NETWORK_TYPES = InlineList[String, 3]("udp", "udp4", "udp6")
fn dial_udp(network: String, local_address: UDPAddr) raises -> UDPConnection:
"""Connects to the address on the named network.
The network must be "udp", "udp4", or "udp6".
Args:
network: The network type.
local_address: The local address.
Returns:
The TCP connection.
"""
# TODO: Add conversion of domain name to ip address
if network not in UDP_NETWORK_TYPES:
raise Error("unsupported network type: " + network)
var socket = Socket(local_address=BaseAddr(local_address), socket_type=SocketType.SOCK_DGRAM)
return UDPConnection(socket^)
fn dial_udp(network: String, local_address: String) raises -> UDPConnection:
"""Connects to the address on the named network.
The network must be "udp", "udp4", or "udp6".
Args:
network: The network type.
local_address: The local address to connect to. (The format is "host:port").
Returns:
The TCP connection.
"""
var result = split_host_port(local_address)
if result[1]:
raise result[1]
return dial_udp(network, UDPAddr(result[0].host, result[0].port))
fn dial_udp(network: String, host: String, port: Int) raises -> UDPConnection:
"""Connects to the address on the named network.
The network must be "udp", "udp4", or "udp6".
Args:
network: The network type.
host: The remote host in ipv4 format.
port: The remote port.
Returns:
The TCP connection.
"""
return dial_udp(network, UDPAddr(host, port))
| gojo/gojo/net/udp.mojo | false |
<filename>gojo/gojo/net/__init__.mojo
"""Adapted from go's net package
A good chunk of the leg work here came from the lightbug_http project! https://github.com/saviorand/lightbug_http/tree/main
"""
from .fd import FileDescriptor
from .socket import Socket
from .tcp import TCPConnection, TCPListener, listen_tcp, dial_tcp, TCPAddr
from .udp import UDPAddr, UDPConnection, listen_udp, dial_udp
from .address import NetworkType, Addr, HostPort
from .ip import get_ip_address, get_addr_info
# Time in nanoseconds
alias Duration = Int
alias DEFAULT_BUFFER_SIZE = 4096
alias DEFAULT_TCP_KEEP_ALIVE = Duration(15 * 1000 * 1000 * 1000) # 15 seconds
| gojo/gojo/net/__init__.mojo | false |
<filename>gojo/gojo/strings/builder.mojo
import ..io
struct StringBuilder[growth_factor: Float32 = 2](
Stringable,
Sized,
io.Writer,
io.StringWriter,
io.ByteWriter,
):
"""
A string builder class that allows for efficient string management and concatenation.
This class is useful when you need to build a string by appending multiple strings
together. The performance increase is not linear. Compared to string concatenation,
I've observed around 20-30x faster for writing and rending ~4KB and up to 2100x-2300x
for ~4MB. This is because it avoids the overhead of creating and destroying many
intermediate strings and performs memcopy operations.
The result is a more efficient when building larger string concatenations. It
is generally not recommended to use this class for small concatenations such as
a few strings like `a + b + c + d` because the overhead of creating the string
builder and appending the strings is not worth the performance gain.
Example:
```
from strings.builder import StringBuilder
var sb = StringBuilder()
sb.write_string("Hello ")
sb.write_string("World!")
print(sb) # Hello World!
```
"""
var _data: UnsafePointer[UInt8]
var _size: Int
var _capacity: Int
@always_inline
fn __init__(inout self, *, capacity: Int = 4096):
constrained[growth_factor >= 1.25]()
self._data = UnsafePointer[UInt8]().alloc(capacity)
self._size = 0
self._capacity = capacity
@always_inline
fn __moveinit__(inout self, owned other: Self):
self._data = other._data
self._size = other._size
self._capacity = other._capacity
other._data = UnsafePointer[UInt8]()
other._size = 0
other._capacity = 0
@always_inline
fn __del__(owned self):
if self._data:
self._data.free()
@always_inline
fn __len__(self) -> Int:
"""Returns the length of the string builder."""
return self._size
@always_inline
fn __str__(self) -> String:
"""
Converts the string builder to a string.
Returns:
The string representation of the string builder. Returns an empty
string if the string builder is empty.
"""
var copy = UnsafePointer[UInt8]().alloc(self._size)
memcpy(copy, self._data, self._size)
return StringRef(copy, self._size)
@always_inline
fn as_bytes_slice(self: Reference[Self]) -> Span[UInt8, self.is_mutable, self.lifetime]:
"""Returns the internal _data as a Span[UInt8]."""
return Span[UInt8, self.is_mutable, self.lifetime](unsafe_ptr=self[]._data, len=self[]._size)
@always_inline
fn render(
self: Reference[Self],
) -> StringSlice[self.is_mutable, self.lifetime]:
"""
Return a StringSlice view of the _data owned by the builder.
Slightly faster than __str__, 10-20% faster in limited testing.
Returns:
The string representation of the string builder. Returns an empty string if the string builder is empty.
"""
return StringSlice[self.is_mutable, self.lifetime](unsafe_from_utf8_ptr=self[]._data, len=self[]._size)
@always_inline
fn _resize(inout self, _capacity: Int) -> None:
"""
Resizes the string builder buffer.
Args:
_capacity: The new _capacity of the string builder buffer.
"""
var new__data = UnsafePointer[UInt8]().alloc(_capacity)
memcpy(new__data, self._data, self._size)
self._data.free()
self._data = new__data
self._capacity = _capacity
return None
@always_inline
fn _resize_if_needed(inout self, bytes_to_add: Int):
"""Resizes the buffer if the bytes to add exceeds the current capacity."""
# TODO: Handle the case where new_capacity is greater than MAX_INT. It should panic.
if bytes_to_add > self._capacity - self._size:
var new_capacity = int(self._capacity * 2)
if new_capacity < self._capacity + bytes_to_add:
new_capacity = self._capacity + bytes_to_add
self._resize(new_capacity)
@always_inline
fn _write(inout self, src: Span[UInt8]) -> (Int, Error):
"""
Appends a byte Span to the builder buffer.
Args:
src: The byte array to append.
"""
self._resize_if_needed(len(src))
memcpy(self._data.offset(self._size), src._data, len(src))
self._size += len(src)
return len(src), Error()
@always_inline
fn write(inout self, src: List[UInt8]) -> (Int, Error):
"""
Appends a byte List to the builder buffer.
Args:
src: The byte array to append.
"""
var span = Span(src)
var bytes_read: Int
var err: Error
bytes_read, err = self._write(span)
return bytes_read, err
@always_inline
fn write_string(inout self, src: String) -> (Int, Error):
"""
Appends a string to the builder buffer.
Args:
src: The string to append.
"""
return self._write(src.as_bytes_slice())
@always_inline
fn write_byte(inout self, byte: UInt8) -> (Int, Error):
self._resize_if_needed(1)
self._data[self._size] = byte
self._size += 1
return 1, Error()
| gojo/gojo/strings/builder.mojo | false |
<filename>gojo/gojo/strings/reader.mojo
import ..io
from ..builtins import copy, panic
@value
# TODO: Uncomment write_to and write_buf once the bug with the trait's Span argument is fixed.
struct Reader(
Sized,
io.Reader,
io.ReaderAt,
io.ByteReader,
io.ByteScanner,
io.Seeker,
# io.WriterTo,
):
"""A Reader that implements the [io.Reader], [io.ReaderAt], [io.ByteReader], [io.ByteScanner], [io.Seeker], and [io.WriterTo] traits
by reading from a string. The zero value for Reader operates like a Reader of an empty string.
"""
var string: String
var read_pos: Int # current reading index
var prev_rune: Int # index of previous rune; or < 0
@always_inline
fn __init__(inout self, string: String = ""):
self.string = string
self.read_pos = 0
self.prev_rune = -1
@always_inline
fn __len__(self) -> Int:
"""Returns the number of bytes of the unread portion of the string.
Returns:
int: the number of bytes of the unread portion of the string.
"""
if self.read_pos >= len(self.string):
return 0
return len(self.string) - self.read_pos
@always_inline
fn size(self) -> Int:
"""Returns the original length of the underlying string.
size is the number of bytes available for reading via [Reader.read_at].
The returned value is always the same and is not affected by calls
to any other method.
Returns:
The original length of the underlying string.
"""
return len(self.string)
@always_inline
fn _read(inout self, inout dest: Span[UInt8, True], capacity: Int) -> (Int, Error):
"""Reads from the underlying string into the provided List[UInt8] object.
Implements the [io.Reader] trait.
Args:
dest: The destination List[UInt8] object to read into.
capacity: The capacity of the destination List[UInt8] object.
Returns:
The number of bytes read into dest.
"""
if self.read_pos >= len(self.string):
return 0, io.EOF
self.prev_rune = -1
var bytes_written = copy(dest, self.string.as_bytes_slice()[self.read_pos :])
self.read_pos += bytes_written
return bytes_written, Error()
@always_inline
fn read(inout self, inout dest: List[UInt8]) -> (Int, Error):
"""Reads from the underlying string into the provided List[UInt8] object.
Implements the [io.Reader] trait.
Args:
dest: The destination List[UInt8] object to read into.
Returns:
The number of bytes read into dest.
"""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read(span, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn _read_at(self, inout dest: Span[UInt8, True], off: Int, capacity: Int) -> (Int, Error):
"""Reads from the Reader into the dest List[UInt8] starting at the offset off.
It returns the number of bytes read into dest and an error if any.
Args:
dest: The destination List[UInt8] object to read into.
off: The byte offset to start reading from.
capacity: The capacity of the destination List[UInt8] object.
Returns:
The number of bytes read into dest.
"""
# cannot modify state - see io.ReaderAt
if off < 0:
return 0, Error("strings.Reader.read_at: negative offset")
if off >= len(self.string):
return 0, io.EOF
var error = Error()
var copied_elements_count = copy(dest, self.string.as_bytes_slice()[off:])
if copied_elements_count < len(dest):
error = Error(str(io.EOF))
return copied_elements_count, error
@always_inline
fn read_at(self, inout dest: List[UInt8], off: Int) -> (Int, Error):
"""Reads from the Reader into the dest List[UInt8] starting at the offset off.
It returns the number of bytes read into dest and an error if any.
Args:
dest: The destination List[UInt8] object to read into.
off: The byte offset to start reading from.
Returns:
The number of bytes read into dest.
"""
var span = Span(dest)
var bytes_read: Int
var err: Error
bytes_read, err = self._read_at(span, off, dest.capacity)
dest.size += bytes_read
return bytes_read, err
@always_inline
fn read_byte(inout self) -> (UInt8, Error):
"""Reads the next byte from the underlying string."""
self.prev_rune = -1
if self.read_pos >= len(self.string):
return UInt8(0), io.EOF
var b = self.string.as_bytes_slice()[self.read_pos]
self.read_pos += 1
return UInt8(b), Error()
@always_inline
fn unread_byte(inout self) -> Error:
"""Unreads the last byte read. Only the most recent byte read can be unread."""
if self.read_pos <= 0:
return Error("strings.Reader.unread_byte: at beginning of string")
self.prev_rune = -1
self.read_pos -= 1
return Error()
# # read_rune implements the [io.RuneReader] trait.
# fn read_rune() (ch rune, size int, err error):
# if self.read_pos >= Int(len(self.string)):
# self.prev_rune = -1
# return 0, 0, io.EOF
# self.prev_rune = int(self.read_pos)
# if c = self.string[self.read_pos]; c < utf8.RuneSelf:
# self.read_pos += 1
# return rune(c), 1, nil
# ch, size = utf8.DecodeRuneInString(self.string[self.read_pos:])
# self.read_pos += Int(size)
# return
# # unread_rune implements the [io.RuneScanner] trait.
# fn unread_rune() error:
# if self.read_pos <= 0:
# return errors.New("strings.Reader.unread_rune: at beginning of string")
# if self.prev_rune < 0:
# return errors.New("strings.Reader.unread_rune: previous operation was not read_rune")
# self.read_pos = Int(self.prev_rune)
# self.prev_rune = -1
# return nil
fn seek(inout self, offset: Int, whence: Int) -> (Int, Error):
"""Seeks to a new position in the underlying string. The next read will start from that position.
Args:
offset: The offset to seek to.
whence: The seek mode. It can be one of [io.SEEK_START], [io.SEEK_CURRENT], or [io.SEEK_END].
Returns:
The new position in the string.
"""
self.prev_rune = -1
var position: Int = 0
if whence == io.SEEK_START:
position = offset
elif whence == io.SEEK_CURRENT:
position = self.read_pos + offset
elif whence == io.SEEK_END:
position = Int(len(self.string)) + offset
else:
return Int(0), Error("strings.Reader.seek: invalid whence")
if position < 0:
return Int(0), Error("strings.Reader.seek: negative position")
self.read_pos = position
return position, Error()
# fn write_to[W: io.Writer](inout self, inout writer: W) -> (Int, Error):
# """Writes the remaining portion of the underlying string to the provided writer.
# Implements the [io.WriterTo] trait.
# Args:
# writer: The writer to write the remaining portion of the string to.
# Returns:
# The number of bytes written to the writer.
# """
# self.prev_rune = -1
# var err = Error()
# if self.read_pos >= len(self.string):
# return Int(0), err
# var chunk_to_write = self.string.as_bytes_slice()[self.read_pos :]
# var bytes_written: Int
# bytes_written, err = writer.write(chunk_to_write)
# if bytes_written > len(chunk_to_write):
# panic("strings.Reader.write_to: invalid write_string count")
# self.read_pos += bytes_written
# if bytes_written != len(chunk_to_write) and not err:
# err = Error(io.ERR_SHORT_WRITE)
# return bytes_written, err
# # TODO: How can I differentiate between the two write_to methods when the writer implements both traits?
# fn write_to[W: io.StringWriter](inout self, inout writer: W) raises -> Int:
# """Writes the remaining portion of the underlying string to the provided writer.
# Implements the [io.WriterTo] trait.
# Args:
# writer: The writer to write the remaining portion of the string to.
# Returns:
# The number of bytes written to the writer.
# """
# self.prev_rune = -1
# if self.read_pos >= Int(len(self.string)):
# return 0
# var chunk_to_write = self.string[self.read_pos:]
# var bytes_written = io.write_string(writer, chunk_to_write)
# if bytes_written > len(chunk_to_write):
# raise Error("strings.Reader.write_to: invalid write_string count")
# self.read_pos += Int(bytes_written)
# if bytes_written != len(chunk_to_write):
# raise Error(io.ERR_SHORT_WRITE)
# return Int(bytes_written)
@always_inline
fn reset(inout self, string: String):
"""Resets the [Reader] to be reading from the beginning of the provided string.
Args:
string: The string to read from.
"""
self.string = string
self.read_pos = 0
self.prev_rune = -1
fn new_reader(string: String = "") -> Reader:
"""Returns a new [Reader] reading from the provided string.
It is similar to [bytes.new_buffer] but more efficient and non-writable.
Args:
string: The string to read from.
"""
return Reader(string)
| gojo/gojo/strings/reader.mojo | false |
<filename>gojo/gojo/strings/__init__.mojo
from .builder import StringBuilder
from .reader import Reader, new_reader
| gojo/gojo/strings/__init__.mojo | false |
<filename>gojo/gojo/syscall/file.mojo
trait FileDescriptorBase(io.Reader, io.Writer, io.Closer):
...
# --- ( File Related Syscalls & Structs )---------------------------------------
alias O_NONBLOCK = 16384
alias O_ACCMODE = 3
alias O_CLOEXEC = 524288
fn close(fildes: c_int) -> c_int:
"""Libc POSIX `close` function
Reference: https://man7.org/linux/man-pages/man3/close.3p.html
Fn signature: int close(int fildes).
Args:
fildes: A File Descriptor to close.
Returns:
Upon successful completion, 0 shall be returned; otherwise, -1
shall be returned and errno set to indicate the error.
"""
return external_call["close", c_int, c_int](fildes)
fn open[*T: AnyType](path: UnsafePointer[c_char], oflag: c_int) -> c_int:
"""Libc POSIX `open` function
Reference: https://man7.org/linux/man-pages/man3/open.3p.html
Fn signature: int open(const char *path, int oflag, ...).
Args:
path: A pointer to a C string containing the path to open.
oflag: The flags to open the file with.
Returns:
A File Descriptor or -1 in case of failure
"""
return external_call["open", c_int, UnsafePointer[c_char], c_int](path, oflag) # FnName, RetType # Args
fn read(fildes: c_int, buf: UnsafePointer[c_void], nbyte: c_size_t) -> c_int:
"""Libc POSIX `read` function
Reference: https://man7.org/linux/man-pages/man3/read.3p.html
Fn signature: sssize_t read(int fildes, void *buf, size_t nbyte).
Args: fildes: A File Descriptor.
buf: A pointer to a buffer to store the read data.
nbyte: The number of bytes to read.
Returns: The number of bytes read or -1 in case of failure.
"""
return external_call["read", c_ssize_t, c_int, UnsafePointer[c_void], c_size_t](fildes, buf, nbyte)
fn write(fildes: c_int, buf: UnsafePointer[c_void], nbyte: c_size_t) -> c_int:
"""Libc POSIX `write` function
Reference: https://man7.org/linux/man-pages/man3/write.3p.html
Fn signature: ssize_t write(int fildes, const void *buf, size_t nbyte).
Args: fildes: A File Descriptor.
buf: A pointer to a buffer to write.
nbyte: The number of bytes to write.
Returns: The number of bytes written or -1 in case of failure.
"""
return external_call["write", c_ssize_t, c_int, UnsafePointer[c_void], c_size_t](fildes, buf, nbyte)
| gojo/gojo/syscall/file.mojo | false |
<filename>gojo/gojo/syscall/net.mojo
from . import c_char, c_int, c_ushort, c_uint, c_size_t, c_ssize_t
from .file import O_CLOEXEC, O_NONBLOCK
from utils.static_tuple import StaticTuple
alias IPPROTO_IPV6 = 41
alias IPV6_V6ONLY = 26
alias EPROTONOSUPPORT = 93
# Adapted from https://github.com/gabrieldemarmiesse/mojo-stdlib-extensions/ . Huge thanks to Gabriel!
struct FD:
alias STDIN = 0
alias STDOUT = 1
alias STDERR = 2
alias SUCCESS = 0
alias GRND_NONBLOCK: UInt8 = 1
alias char_pointer = UnsafePointer[UInt8]
# --- ( error.h Constants )-----------------------------------------------------
struct ErrnoConstants:
alias EPERM = 1
alias ENOENT = 2
alias ESRCH = 3
alias EINTR = 4
alias EIO = 5
alias ENXIO = 6
alias E2BIG = 7
alias ENOEXEC = 8
alias EBADF = 9
alias ECHILD = 10
alias EAGAIN = 11
alias ENOMEM = 12
alias EACCES = 13
alias EFAULT = 14
alias ENOTBLK = 15
alias EBUSY = 16
alias EEXIST = 17
alias EXDEV = 18
alias ENODEV = 19
alias ENOTDIR = 20
alias EISDIR = 21
alias EINVAL = 22
alias ENFILE = 23
alias EMFILE = 24
alias ENOTTY = 25
alias ETXTBSY = 26
alias EFBIG = 27
alias ENOSPC = 28
alias ESPIPE = 29
alias EROFS = 30
alias EMLINK = 31
alias EPIPE = 32
alias EDOM = 33
alias ERANGE = 34
alias EWOULDBLOCK = 11
# fn to_char_ptr(s: String) -> UnsafePointer[UInt8]:
# """Only ASCII-based strings."""
# var ptr = UnsafePointer[UInt8]().alloc(len(s))
# for i in range(len(s)):
# ptr.store(i, ord(s[i]))
# return ptr
fn cftob(val: c_int) -> Bool:
"""Convert C-like failure (-1) to Bool."""
return rebind[Bool](val > 0)
# --- ( Network Related Constants )---------------------------------------------
alias sa_family_t = c_ushort
alias socklen_t = c_uint
alias in_addr_t = c_uint
alias in_port_t = c_ushort
# Address Family Constants
struct AddressFamily:
alias AF_UNSPEC = 0
alias AF_UNIX = 1
alias AF_LOCAL = 1
alias AF_INET = 2
alias AF_AX25 = 3
alias AF_IPX = 4
alias AF_APPLETALK = 5
alias AF_NETROM = 6
alias AF_BRIDGE = 7
alias AF_ATMPVC = 8
alias AF_X25 = 9
alias AF_INET6 = 10
alias AF_ROSE = 11
alias AF_DECnet = 12
alias AF_NETBEUI = 13
alias AF_SECURITY = 14
alias AF_KEY = 15
alias AF_NETLINK = 16
alias AF_ROUTE = 16
alias AF_PACKET = 17
alias AF_ASH = 18
alias AF_ECONET = 19
alias AF_ATMSVC = 20
alias AF_RDS = 21
alias AF_SNA = 22
alias AF_IRDA = 23
alias AF_PPPOX = 24
alias AF_WANPIPE = 25
alias AF_LLC = 26
alias AF_CAN = 29
alias AF_TIPC = 30
alias AF_BLUETOOTH = 31
alias AF_IUCV = 32
alias AF_RXRPC = 33
alias AF_ISDN = 34
alias AF_PHONET = 35
alias AF_IEEE802154 = 36
alias AF_CAIF = 37
alias AF_ALG = 38
alias AF_NFC = 39
alias AF_VSOCK = 40
alias AF_KCM = 41
alias AF_QIPCRTR = 42
alias AF_MAX = 43
# Protocol family constants
struct ProtocolFamily:
alias PF_UNSPEC = AddressFamily.AF_UNSPEC
alias PF_UNIX = AddressFamily.AF_UNIX
alias PF_LOCAL = AddressFamily.AF_LOCAL
alias PF_INET = AddressFamily.AF_INET
alias PF_AX25 = AddressFamily.AF_AX25
alias PF_IPX = AddressFamily.AF_IPX
alias PF_APPLETALK = AddressFamily.AF_APPLETALK
alias PF_NETROM = AddressFamily.AF_NETROM
alias PF_BRIDGE = AddressFamily.AF_BRIDGE
alias PF_ATMPVC = AddressFamily.AF_ATMPVC
alias PF_X25 = AddressFamily.AF_X25
alias PF_INET6 = AddressFamily.AF_INET6
alias PF_ROSE = AddressFamily.AF_ROSE
alias PF_DECnet = AddressFamily.AF_DECnet
alias PF_NETBEUI = AddressFamily.AF_NETBEUI
alias PF_SECURITY = AddressFamily.AF_SECURITY
alias PF_KEY = AddressFamily.AF_KEY
alias PF_NETLINK = AddressFamily.AF_NETLINK
alias PF_ROUTE = AddressFamily.AF_ROUTE
alias PF_PACKET = AddressFamily.AF_PACKET
alias PF_ASH = AddressFamily.AF_ASH
alias PF_ECONET = AddressFamily.AF_ECONET
alias PF_ATMSVC = AddressFamily.AF_ATMSVC
alias PF_RDS = AddressFamily.AF_RDS
alias PF_SNA = AddressFamily.AF_SNA
alias PF_IRDA = AddressFamily.AF_IRDA
alias PF_PPPOX = AddressFamily.AF_PPPOX
alias PF_WANPIPE = AddressFamily.AF_WANPIPE
alias PF_LLC = AddressFamily.AF_LLC
alias PF_CAN = AddressFamily.AF_CAN
alias PF_TIPC = AddressFamily.AF_TIPC
alias PF_BLUETOOTH = AddressFamily.AF_BLUETOOTH
alias PF_IUCV = AddressFamily.AF_IUCV
alias PF_RXRPC = AddressFamily.AF_RXRPC
alias PF_ISDN = AddressFamily.AF_ISDN
alias PF_PHONET = AddressFamily.AF_PHONET
alias PF_IEEE802154 = AddressFamily.AF_IEEE802154
alias PF_CAIF = AddressFamily.AF_CAIF
alias PF_ALG = AddressFamily.AF_ALG
alias PF_NFC = AddressFamily.AF_NFC
alias PF_VSOCK = AddressFamily.AF_VSOCK
alias PF_KCM = AddressFamily.AF_KCM
alias PF_QIPCRTR = AddressFamily.AF_QIPCRTR
alias PF_MAX = AddressFamily.AF_MAX
# Socket Type constants
struct SocketType:
alias SOCK_STREAM = 1
alias SOCK_DGRAM = 2
alias SOCK_RAW = 3
alias SOCK_RDM = 4
alias SOCK_SEQPACKET = 5
alias SOCK_DCCP = 6
alias SOCK_PACKET = 10
alias SOCK_CLOEXEC = O_CLOEXEC
alias SOCK_NONBLOCK = O_NONBLOCK
# Address Information
struct AddressInformation:
alias AI_PASSIVE = 1
alias AI_CANONNAME = 2
alias AI_NUMERICHOST = 4
alias AI_V4MAPPED = 2048
alias AI_ALL = 256
alias AI_ADDRCONFIG = 1024
alias AI_IDN = 64
alias INET_ADDRSTRLEN = 16
alias INET6_ADDRSTRLEN = 46
alias SHUT_RD = 0
alias SHUT_WR = 1
alias SHUT_RDWR = 2
alias SOL_SOCKET = 65535
# Socket Options
struct SocketOptions:
alias SO_DEBUG = 1
alias SO_REUSEADDR = 4
alias SO_TYPE = 4104
alias SO_ERROR = 4103
alias SO_DONTROUTE = 16
alias SO_BROADCAST = 32
alias SO_SNDBUF = 4097
alias SO_RCVBUF = 4098
alias SO_KEEPALIVE = 8
alias SO_OOBINLINE = 256
alias SO_LINGER = 128
alias SO_REUSEPORT = 512
alias SO_RCVLOWAT = 4100
alias SO_SNDLOWAT = 4099
alias SO_RCVTIMEO = 4102
alias SO_SNDTIMEO = 4101
alias SO_RCVTIMEO_OLD = 4102
alias SO_SNDTIMEO_OLD = 4101
alias SO_ACCEPTCONN = 2
# unsure of these socket options, they weren't available via python
alias SO_NO_CHECK = 11
alias SO_PRIORITY = 12
alias SO_BSDCOMPAT = 14
alias SO_PASSCRED = 16
alias SO_PEERCRED = 17
alias SO_SECURITY_AUTHENTICATION = 22
alias SO_SECURITY_ENCRYPTION_TRANSPORT = 23
alias SO_SECURITY_ENCRYPTION_NETWORK = 24
alias SO_BINDTODEVICE = 25
alias SO_ATTACH_FILTER = 26
alias SO_DETACH_FILTER = 27
alias SO_GET_FILTER = 26
alias SO_PEERNAME = 28
alias SO_TIMESTAMP = 29
alias SO_TIMESTAMP_OLD = 29
alias SO_PEERSEC = 31
alias SO_SNDBUFFORCE = 32
alias SO_RCVBUFFORCE = 33
alias SO_PASSSEC = 34
alias SO_TIMESTAMPNS = 35
alias SO_TIMESTAMPNS_OLD = 35
alias SO_MARK = 36
alias SO_TIMESTAMPING = 37
alias SO_TIMESTAMPING_OLD = 37
alias SO_PROTOCOL = 38
alias SO_DOMAIN = 39
alias SO_RXQ_OVFL = 40
alias SO_WIFI_STATUS = 41
alias SCM_WIFI_STATUS = 41
alias SO_PEEK_OFF = 42
alias SO_NOFCS = 43
alias SO_LOCK_FILTER = 44
alias SO_SELECT_ERR_QUEUE = 45
alias SO_BUSY_POLL = 46
alias SO_MAX_PACING_RATE = 47
alias SO_BPF_EXTENSIONS = 48
alias SO_INCOMING_CPU = 49
alias SO_ATTACH_BPF = 50
alias SO_DETACH_BPF = 27
alias SO_ATTACH_REUSEPORT_CBPF = 51
alias SO_ATTACH_REUSEPORT_EBPF = 52
alias SO_CNX_ADVICE = 53
alias SCM_TIMESTAMPING_OPT_STATS = 54
alias SO_MEMINFO = 55
alias SO_INCOMING_NAPI_ID = 56
alias SO_COOKIE = 57
alias SCM_TIMESTAMPING_PKTINFO = 58
alias SO_PEERGROUPS = 59
alias SO_ZEROCOPY = 60
alias SO_TXTIME = 61
alias SCM_TXTIME = 61
alias SO_BINDTOIFINDEX = 62
alias SO_TIMESTAMP_NEW = 63
alias SO_TIMESTAMPNS_NEW = 64
alias SO_TIMESTAMPING_NEW = 65
alias SO_RCVTIMEO_NEW = 66
alias SO_SNDTIMEO_NEW = 67
alias SO_DETACH_REUSEPORT_BPF = 68
# --- ( Network Related Structs )-----------------------------------------------
@value
@register_passable("trivial")
struct in_addr:
var s_addr: in_addr_t
@value
@register_passable("trivial")
struct in6_addr:
var s6_addr: StaticTuple[c_char, 16]
@value
@register_passable("trivial")
struct sockaddr:
var sa_family: sa_family_t
var sa_data: StaticTuple[c_char, 14]
@value
@register_passable("trivial")
struct sockaddr_in:
var sin_family: sa_family_t
var sin_port: in_port_t
var sin_addr: in_addr
var sin_zero: StaticTuple[c_char, 8]
@value
@register_passable("trivial")
struct sockaddr_in6:
var sin6_family: sa_family_t
var sin6_port: in_port_t
var sin6_flowinfo: c_uint
var sin6_addr: in6_addr
var sin6_scope_id: c_uint
@value
@register_passable("trivial")
struct addrinfo:
"""Struct field ordering can vary based on platform.
For MacOS, I had to swap the order of ai_canonname and ai_addr.
https://stackoverflow.com/questions/53575101/calling-getaddrinfo-directly-from-python-ai-addr-is-null-pointer.
"""
var ai_flags: c_int
var ai_family: c_int
var ai_socktype: c_int
var ai_protocol: c_int
var ai_addrlen: socklen_t
var ai_canonname: UnsafePointer[UInt8]
var ai_addr: UnsafePointer[sockaddr]
var ai_next: UnsafePointer[addrinfo]
fn __init__(
inout self,
ai_flags: c_int = 0,
ai_family: c_int = 0,
ai_socktype: c_int = 0,
ai_protocol: c_int = 0,
ai_addrlen: socklen_t = 0,
ai_canonname: UnsafePointer[UInt8] = UnsafePointer[UInt8](),
ai_addr: UnsafePointer[sockaddr] = UnsafePointer[sockaddr](),
ai_next: UnsafePointer[addrinfo] = UnsafePointer[addrinfo](),
):
self.ai_flags = ai_flags
self.ai_family = ai_family
self.ai_socktype = ai_socktype
self.ai_protocol = ai_protocol
self.ai_addrlen = ai_addrlen
self.ai_canonname = ai_canonname
self.ai_addr = ai_addr
self.ai_next = ai_next
# fn __init__() -> Self:
# return Self(0, 0, 0, 0, 0, UnsafePointer[UInt8](), UnsafePointer[sockaddr](), UnsafePointer[addrinfo]())
@value
@register_passable("trivial")
struct addrinfo_unix:
"""Struct field ordering can vary based on platform.
For MacOS, I had to swap the order of ai_canonname and ai_addr.
https://stackoverflow.com/questions/53575101/calling-getaddrinfo-directly-from-python-ai-addr-is-null-pointer.
"""
var ai_flags: c_int
var ai_family: c_int
var ai_socktype: c_int
var ai_protocol: c_int
var ai_addrlen: socklen_t
var ai_addr: UnsafePointer[sockaddr]
var ai_canonname: UnsafePointer[UInt8]
var ai_next: UnsafePointer[addrinfo]
fn __init__(
inout self,
ai_flags: c_int = 0,
ai_family: c_int = 0,
ai_socktype: c_int = 0,
ai_protocol: c_int = 0,
ai_addrlen: socklen_t = 0,
ai_canonname: UnsafePointer[UInt8] = UnsafePointer[UInt8](),
ai_addr: UnsafePointer[sockaddr] = UnsafePointer[sockaddr](),
ai_next: UnsafePointer[addrinfo] = UnsafePointer[addrinfo](),
):
self.ai_flags = ai_flags
self.ai_family = ai_family
self.ai_socktype = ai_socktype
self.ai_protocol = ai_protocol
self.ai_addrlen = ai_addrlen
self.ai_canonname = ai_canonname
self.ai_addr = ai_addr
self.ai_next = ai_next
# --- ( Network Related Syscalls & Structs )------------------------------------
fn htonl(hostlong: c_uint) -> c_uint:
"""Libc POSIX `htonl` function
Reference: https://man7.org/linux/man-pages/man3/htonl.3p.html
Fn signature: uint32_t htonl(uint32_t hostlong).
Args: hostlong: A 32-bit integer in host byte order.
Returns: The value provided in network byte order.
"""
return external_call["htonl", c_uint, c_uint](hostlong)
fn htons(hostshort: c_ushort) -> c_ushort:
"""Libc POSIX `htons` function
Reference: https://man7.org/linux/man-pages/man3/htonl.3p.html
Fn signature: uint16_t htons(uint16_t hostshort).
Args: hostshort: A 16-bit integer in host byte order.
Returns: The value provided in network byte order.
"""
return external_call["htons", c_ushort, c_ushort](hostshort)
fn ntohl(netlong: c_uint) -> c_uint:
"""Libc POSIX `ntohl` function
Reference: https://man7.org/linux/man-pages/man3/htonl.3p.html
Fn signature: uint32_t ntohl(uint32_t netlong).
Args: netlong: A 32-bit integer in network byte order.
Returns: The value provided in host byte order.
"""
return external_call["ntohl", c_uint, c_uint](netlong)
fn ntohs(netshort: c_ushort) -> c_ushort:
"""Libc POSIX `ntohs` function
Reference: https://man7.org/linux/man-pages/man3/htonl.3p.html
Fn signature: uint16_t ntohs(uint16_t netshort).
Args: netshort: A 16-bit integer in network byte order.
Returns: The value provided in host byte order.
"""
return external_call["ntohs", c_ushort, c_ushort](netshort)
fn inet_ntop(
af: c_int,
src: UnsafePointer[UInt8],
dst: UnsafePointer[UInt8],
size: socklen_t,
) -> UnsafePointer[UInt8]:
"""Libc POSIX `inet_ntop` function
Reference: https://man7.org/linux/man-pages/man3/inet_ntop.3p.html.
Fn signature: const char *inet_ntop(int af, const void *restrict src, char *restrict dst, socklen_t size).
Args:
af: Address Family see AF_ aliases.
src: A pointer to a binary address.
dst: A pointer to a buffer to store the result.
size: The size of the buffer.
Returns:
A pointer to the buffer containing the result.
"""
return external_call[
"inet_ntop",
UnsafePointer[UInt8], # FnName, RetType
c_int,
UnsafePointer[UInt8],
UnsafePointer[UInt8],
socklen_t, # Args
](af, src, dst, size)
fn inet_pton(af: c_int, src: UnsafePointer[UInt8], dst: UnsafePointer[UInt8]) -> c_int:
"""Libc POSIX `inet_pton` function
Reference: https://man7.org/linux/man-pages/man3/inet_ntop.3p.html
Fn signature: int inet_pton(int af, const char *restrict src, void *restrict dst).
Args: af: Address Family see AF_ aliases.
src: A pointer to a string containing the address.
dst: A pointer to a buffer to store the result.
Returns: 1 on success, 0 if the input is not a valid address, -1 on error.
"""
return external_call[
"inet_pton",
c_int, # FnName, RetType
c_int,
UnsafePointer[UInt8],
UnsafePointer[UInt8], # Args
](af, src, dst)
fn inet_addr(cp: UnsafePointer[UInt8]) -> in_addr_t:
"""Libc POSIX `inet_addr` function
Reference: https://man7.org/linux/man-pages/man3/inet_addr.3p.html
Fn signature: in_addr_t inet_addr(const char *cp).
Args: cp: A pointer to a string containing the address.
Returns: The address in network byte order.
"""
return external_call["inet_addr", in_addr_t, UnsafePointer[UInt8]](cp)
fn inet_ntoa(addr: in_addr) -> UnsafePointer[UInt8]:
"""Libc POSIX `inet_ntoa` function
Reference: https://man7.org/linux/man-pages/man3/inet_addr.3p.html
Fn signature: char *inet_ntoa(struct in_addr in).
Args: in: A pointer to a string containing the address.
Returns: The address in network byte order.
"""
return external_call["inet_ntoa", UnsafePointer[UInt8], in_addr](addr)
fn socket(domain: c_int, type: c_int, protocol: c_int) -> c_int:
"""Libc POSIX `socket` function
Reference: https://man7.org/linux/man-pages/man3/socket.3p.html
Fn signature: int socket(int domain, int type, int protocol).
Args: domain: Address Family see AF_ aliases.
type: Socket Type see SOCK_ aliases.
protocol: The protocol to use.
Returns: A File Descriptor or -1 in case of failure.
"""
return external_call["socket", c_int, c_int, c_int, c_int](domain, type, protocol) # FnName, RetType # Args
fn setsockopt(
socket: c_int,
level: c_int,
option_name: c_int,
option_value: UnsafePointer[UInt8],
option_len: socklen_t,
) -> c_int:
"""Libc POSIX `setsockopt` function
Reference: https://man7.org/linux/man-pages/man3/setsockopt.3p.html
Fn signature: int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len).
Args:
socket: A File Descriptor.
level: The protocol level.
option_name: The option to set.
option_value: A pointer to the value to set.
option_len: The size of the value.
Returns: 0 on success, -1 on error.
"""
return external_call[
"setsockopt",
c_int, # FnName, RetType
c_int,
c_int,
c_int,
UnsafePointer[UInt8],
socklen_t, # Args
](socket, level, option_name, option_value, option_len)
fn getsockopt(
socket: c_int,
level: c_int,
option_name: c_int,
option_value: UnsafePointer[UInt8],
option_len: UnsafePointer[socklen_t],
) -> c_int:
"""Libc POSIX `getsockopt` function
Reference: https://man7.org/linux/man-pages/man3/getsockopt.3p.html
Fn signature: int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len).
Args: socket: A File Descriptor.
level: The protocol level.
option_name: The option to get.
option_value: A pointer to the value to get.
option_len: DTypePointer to the size of the value.
Returns: 0 on success, -1 on error.
"""
return external_call[
"getsockopt",
c_int, # FnName, RetType
c_int,
c_int,
c_int,
UnsafePointer[UInt8],
UnsafePointer[socklen_t], # Args
](socket, level, option_name, option_value, option_len)
fn getsockname(
socket: c_int,
address: UnsafePointer[sockaddr],
address_len: UnsafePointer[socklen_t],
) -> c_int:
"""Libc POSIX `getsockname` function
Reference: https://man7.org/linux/man-pages/man3/getsockname.3p.html
Fn signature: int getsockname(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len).
Args: socket: A File Descriptor.
address: A pointer to a buffer to store the address of the peer.
address_len: A pointer to the size of the buffer.
Returns: 0 on success, -1 on error.
"""
return external_call[
"getsockname",
c_int, # FnName, RetType
c_int,
UnsafePointer[sockaddr],
UnsafePointer[socklen_t], # Args
](socket, address, address_len)
fn getpeername(
sockfd: c_int,
addr: UnsafePointer[sockaddr],
address_len: UnsafePointer[socklen_t],
) -> c_int:
"""Libc POSIX `getpeername` function
Reference: https://man7.org/linux/man-pages/man2/getpeername.2.html
Fn signature: int getpeername(int socket, struct sockaddr *restrict addr, socklen_t *restrict address_len).
Args: sockfd: A File Descriptor.
addr: A pointer to a buffer to store the address of the peer.
address_len: A pointer to the size of the buffer.
Returns: 0 on success, -1 on error.
"""
return external_call[
"getpeername",
c_int, # FnName, RetType
c_int,
UnsafePointer[sockaddr],
UnsafePointer[socklen_t], # Args
](sockfd, addr, address_len)
fn bind(socket: c_int, address: UnsafePointer[sockaddr], address_len: socklen_t) -> c_int:
"""Libc POSIX `bind` function
Reference: https://man7.org/linux/man-pages/man3/bind.3p.html
Fn signature: int bind(int socket, const struct sockaddr *address, socklen_t address_len).
"""
return external_call["bind", c_int, c_int, UnsafePointer[sockaddr], socklen_t]( # FnName, RetType # Args
socket, address, address_len
)
fn listen(socket: c_int, backlog: c_int) -> c_int:
"""Libc POSIX `listen` function
Reference: https://man7.org/linux/man-pages/man3/listen.3p.html
Fn signature: int listen(int socket, int backlog).
Args: socket: A File Descriptor.
backlog: The maximum length of the queue of pending connections.
Returns: 0 on success, -1 on error.
"""
return external_call["listen", c_int, c_int, c_int](socket, backlog)
fn accept(
socket: c_int,
address: UnsafePointer[sockaddr],
address_len: UnsafePointer[socklen_t],
) -> c_int:
"""Libc POSIX `accept` function
Reference: https://man7.org/linux/man-pages/man3/accept.3p.html
Fn signature: int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len).
Args: socket: A File Descriptor.
address: A pointer to a buffer to store the address of the peer.
address_len: A pointer to the size of the buffer.
Returns: A File Descriptor or -1 in case of failure.
"""
return external_call[
"accept",
c_int, # FnName, RetType
c_int,
UnsafePointer[sockaddr],
UnsafePointer[socklen_t], # Args
](socket, address, address_len)
fn connect(socket: c_int, address: UnsafePointer[sockaddr], address_len: socklen_t) -> c_int:
"""Libc POSIX `connect` function
Reference: https://man7.org/linux/man-pages/man3/connect.3p.html
Fn signature: int connect(int socket, const struct sockaddr *address, socklen_t address_len).
Args: socket: A File Descriptor.
address: A pointer to the address to connect to.
address_len: The size of the address.
Returns: 0 on success, -1 on error.
"""
return external_call["connect", c_int, c_int, UnsafePointer[sockaddr], socklen_t]( # FnName, RetType # Args
socket, address, address_len
)
fn recv(
socket: c_int,
buffer: UnsafePointer[UInt8],
length: c_size_t,
flags: c_int,
) -> c_ssize_t:
"""Libc POSIX `recv` function
Reference: https://man7.org/linux/man-pages/man3/recv.3p.html
Fn signature: ssize_t recv(int socket, void *buffer, size_t length, int flags).
Args:
socket: Specifies the socket file descriptor.
buffer: Points to the buffer where the message should be stored.
length: Specifies the length in bytes of the buffer pointed to by the buffer argument.
flags: Specifies the type of message reception.
Returns:
The number of bytes received or -1 in case of failure.
Valid Flags:
MSG_PEEK: Peeks at an incoming message. The data is treated as unread and the next recvfrom() or similar function shall still return this data.
MSG_OOB: Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
MSG_WAITALL: On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. The function may return the smaller amount of data if the socket is a message-based socket, if a signal is caught, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.
"""
return external_call[
"recv",
c_ssize_t,
c_int,
UnsafePointer[UInt8],
c_size_t,
c_int,
](socket, buffer, length, flags)
fn recvfrom(
socket: c_int,
buffer: UnsafePointer[UInt8],
length: c_size_t,
flags: c_int,
address: UnsafePointer[sockaddr],
address_len: UnsafePointer[socklen_t],
) -> c_ssize_t:
"""Libc POSIX `recvfrom` function
Reference: https://man7.org/linux/man-pages/man3/recvfrom.3p.html
Fn signature: ssize_t recvfrom(int socket, void *restrict buffer, size_t length,
int flags, struct sockaddr *restrict address,
socklen_t *restrict address_len).
Args:
socket: Specifies the socket file descriptor.
buffer: Points to the buffer where the message should be stored.
length: Specifies the length in bytes of the buffer pointed to by the buffer argument.
flags: Specifies the type of message reception.
address: A null pointer, or points to a sockaddr structure in which the sending address is to be stored.
address_len: Either a null pointer, if address is a null pointer, or a pointer to a socklen_t object which on input specifies the length of the supplied sockaddr structure, and on output specifies the length of the stored address.
Returns:
The number of bytes received or -1 in case of failure.
Valid Flags:
MSG_PEEK: Peeks at an incoming message. The data is treated as unread and the next recvfrom() or similar function shall still return this data.
MSG_OOB: Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
MSG_WAITALL: On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. The function may return the smaller amount of data if the socket is a message-based socket, if a signal is caught, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.
"""
return external_call[
"recvfrom",
c_ssize_t,
c_int,
UnsafePointer[UInt8],
c_size_t,
c_int,
UnsafePointer[sockaddr],
UnsafePointer[socklen_t],
](socket, buffer, length, flags, address, address_len)
fn send(
socket: c_int,
buffer: UnsafePointer[UInt8],
length: c_size_t,
flags: c_int,
) -> c_ssize_t:
"""Libc POSIX `send` function
Reference: https://man7.org/linux/man-pages/man3/send.3p.html
Fn signature: ssize_t send(int socket, const void *buffer, size_t length, int flags).
Args: socket: A File Descriptor.
buffer: A pointer to the buffer to send.
length: The size of the buffer.
flags: Flags to control the behaviour of the function.
Returns: The number of bytes sent or -1 in case of failure.
"""
return external_call[
"send",
c_ssize_t, # FnName, RetType
c_int,
UnsafePointer[UInt8],
c_size_t,
c_int, # Args
](socket, buffer, length, flags)
fn sendto(
socket: c_int,
message: UnsafePointer[UInt8],
length: c_size_t,
flags: c_int,
dest_addr: UnsafePointer[sockaddr],
dest_len: socklen_t,
) -> c_ssize_t:
"""Libc POSIX `sendto` function
Reference: https://man7.org/linux/man-pages/man3/sendto.3p.html
Fn signature: ssize_t sendto(int socket, const void *message, size_t length,
int flags, const struct sockaddr *dest_addr,
socklen_t dest_len).
Args:
socket: Specifies the socket file descriptor.
message: Points to a buffer containing the message to be sent.
length: Specifies the size of the message in bytes.
flags: Specifies the type of message transmission.
dest_addr: Points to a sockaddr structure containing the destination address.
dest_len: Specifies the length of the sockaddr.
Returns:
The number of bytes sent or -1 in case of failure.
Valid Flags:
MSG_EOR: Terminates a record (if supported by the protocol).
MSG_OOB: Sends out-of-band data on sockets that support out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
MSG_NOSIGNAL: Requests not to send the SIGPIPE signal if an attempt to send is made on a stream-oriented socket that is no longer connected. The [EPIPE] error shall still be returned.
"""
return external_call[
"sendto", c_ssize_t, c_int, UnsafePointer[UInt8], c_size_t, c_int, UnsafePointer[sockaddr], socklen_t
](socket, message, length, flags, dest_addr, dest_len)
fn shutdown(socket: c_int, how: c_int) -> c_int:
"""Libc POSIX `shutdown` function
Reference: https://man7.org/linux/man-pages/man3/shutdown.3p.html
Fn signature: int shutdown(int socket, int how).
Args: socket: A File Descriptor.
how: How to shutdown the socket.
Returns: 0 on success, -1 on error.
"""
return external_call["shutdown", c_int, c_int, c_int](socket, how) # FnName, RetType # Args
fn getaddrinfo(
nodename: UnsafePointer[UInt8],
servname: UnsafePointer[UInt8],
hints: UnsafePointer[addrinfo],
res: UnsafePointer[UnsafePointer[addrinfo]],
) -> c_int:
"""Libc POSIX `getaddrinfo` function
Reference: https://man7.org/linux/man-pages/man3/getaddrinfo.3p.html
Fn signature: int getaddrinfo(const char *restrict nodename, const char *restrict servname, const struct addrinfo *restrict hints, struct addrinfo **restrict res).
"""
return external_call[
"getaddrinfo",
c_int, # FnName, RetType
UnsafePointer[UInt8],
UnsafePointer[UInt8],
UnsafePointer[addrinfo], # Args
UnsafePointer[UnsafePointer[addrinfo]], # Args
](nodename, servname, hints, res)
fn getaddrinfo_unix(
nodename: UnsafePointer[UInt8],
servname: UnsafePointer[UInt8],
hints: UnsafePointer[addrinfo_unix],
res: UnsafePointer[UnsafePointer[addrinfo_unix]],
) -> c_int:
"""Libc POSIX `getaddrinfo` function
Reference: https://man7.org/linux/man-pages/man3/getaddrinfo.3p.html
Fn signature: int getaddrinfo(const char *restrict nodename, const char *restrict servname, const struct addrinfo *restrict hints, struct addrinfo **restrict res).
"""
return external_call[
"getaddrinfo",
c_int, # FnName, RetType
UnsafePointer[UInt8],
UnsafePointer[UInt8],
UnsafePointer[addrinfo_unix], # Args
UnsafePointer[UnsafePointer[addrinfo_unix]], # Args
](nodename, servname, hints, res)
fn gai_strerror(ecode: c_int) -> UnsafePointer[UInt8]:
"""Libc POSIX `gai_strerror` function
Reference: https://man7.org/linux/man-pages/man3/gai_strerror.3p.html
Fn signature: const char *gai_strerror(int ecode).
Args: ecode: The error code.
Returns: A pointer to a string describing the error.
"""
return external_call["gai_strerror", UnsafePointer[UInt8], c_int](ecode) # FnName, RetType # Args
# fn inet_pton(address_family: Int, address: String) -> Int:
# var ip_buf_size = 4
# if address_family == AF_INET6:
# ip_buf_size = 16
# var ip_buf = UnsafePointer[UInt8].alloc(ip_buf_size)
# var conv_status = inet_pton(rebind[c_int](address_family), to_char_ptr(address), ip_buf)
# return int(ip_buf.bitcast[c_uint]().load())
| gojo/gojo/syscall/net.mojo | false |
<filename>gojo/gojo/syscall/__init__.mojo
from .net import (
FD,
SocketType,
AddressFamily,
ProtocolFamily,
SocketOptions,
AddressInformation,
send,
sendto,
recv,
recvfrom,
open,
addrinfo,
addrinfo_unix,
sockaddr,
sockaddr_in,
socklen_t,
socket,
connect,
htons,
ntohs,
inet_pton,
inet_ntop,
getaddrinfo,
getaddrinfo_unix,
gai_strerror,
shutdown,
inet_ntoa,
bind,
listen,
accept,
setsockopt,
getsockopt,
getsockname,
getpeername,
SHUT_RDWR,
SOL_SOCKET,
)
from .file import close, FileDescriptorBase
# Adapted from https://github.com/crisadamo/mojo-Libc . Huge thanks to Cristian!
# C types
alias c_void = UInt8
alias c_char = UInt8
alias c_schar = Int8
alias c_uchar = UInt8
alias c_short = Int16
alias c_ushort = UInt16
alias c_int = Int32
alias c_uint = UInt32
alias c_long = Int64
alias c_ulong = UInt64
alias c_float = Float32
alias c_double = Float64
# `Int` is known to be machine's width
alias c_size_t = Int
alias c_ssize_t = Int
alias ptrdiff_t = Int64
alias intptr_t = Int64
alias uintptr_t = UInt64
| gojo/gojo/syscall/__init__.mojo | false |
from .utf8 import rune_count_in_string, UnicodeString
| gojo/gojo/uni__init__.mojo | false |
<filename>gojo/gojo/uniutf8/runes.mojo
"""Almost all of the actual implementation in this module was written by @mzaks (https://github.com/mzaks)!
This would not be possible without his help.
"""
from ...builtins import Rune
from algorithm.functional import vectorize
from sys.info import simdwidthof
from bit import countl_zero
# alias simd_width_u8 = simdwidthof[DType.uint8]()
alias simd_width_u8 = 1
fn rune_count_in_string(s: String) -> Int:
"""Count the number of runes in a string.
Args:
s: The string to count runes in.
Returns:
The number of runes in the string.
"""
var p = DTypePointer[DType.uint8](s.unsafe_uint8_ptr())
var string_byte_length = len(s)
var result = 0
@parameter
fn count[simd_width: Int](offset: Int):
result += int(((p.load[width=simd_width](offset) >> 6) != 0b10).reduce_add())
vectorize[count, simd_width_u8](string_byte_length)
return result
| gojo/gojo/uniutf8/runes.mojo | false |
<filename>gojo/gojo/uniutf8/string.mojo
from bit import countl_zero
from algorithm.functional import vectorize
from sys.info import simdwidthof
alias simd_width_u8 = simdwidthof[DType.uint8]()
@value
struct UnicodeString(Stringable, Sized):
"""A string that supports Unicode characters of printable size 1
(ie not east asian characters and such.).
The algorithms to handle UTF-8 are from @maxim on the Mojo Discord. Thanks!
"""
var inner: String
@always_inline
fn __init__(inout self, owned s: String):
self.inner = s^
@always_inline
fn __init__(inout self, owned bytes: List[UInt8]):
if bytes[-1] != 0:
bytes.append(0)
self.inner = String(bytes^)
@always_inline
fn __len__(self) -> Int:
"""Count the number of runes in a string.
Returns:
The number of runes in the string.
"""
var data = DTypePointer[DType.uint8](self.inner.unsafe_uint8_ptr())
var byte_count = len(self.inner)
var result = 0
@parameter
fn count[simd_width: Int](offset: Int):
result += int(((data.load[width=simd_width](offset) >> 6) != 0b10).cast[DType.uint8]().reduce_add())
vectorize[count, simd_width_u8](byte_count)
return result
@always_inline
fn __str__(self) -> String:
return self.inner
# @always_inline
# fn __getitem__(self, slice: Slice) -> String:
# # Copy N bytes + null terminator into new pointer and construct string.
# var copy_src = self.inner
# var copy = DTypePointer[DType.uint8](copy_src.unsafe_uint8_ptr())
# var bytes_left = len(self.inner)
# var result = DTypePointer[DType.uint8].alloc(len(self.inner))
# var total_char_length: Int = 0
# for _ in range(slice.start, slice.end):
# print(total_char_length, bytes_left)
# # Number of bytes of the current character
# var char_length = int((copy.load() >> 7 == 0).cast[DType.uint8]() * 1 + countl_zero(~copy.load()))
# memcpy(result.offset(total_char_length), copy, char_length)
# # Move iterator forward
# bytes_left -= char_length
# copy += char_length
# total_char_length += char_length
# print(total_char_length, char_length, bytes_left)
# result[total_char_length] = 0
# return StringRef(result, total_char_length + 1)
@always_inline
fn bytecount(self) -> Int:
return len(self.inner)
@always_inline
fn __iter__(
self: Reference[Self],
) -> _StringIter[self.is_mutable, self.lifetime]:
return _StringIter(self[].inner)
@value
struct _StringIter[mutability: Bool, lifetime: AnyLifetime[mutability].type]():
var bytes_left: Int
var ptr: DTypePointer[DType.uint8]
fn __init__(inout self, src: Reference[String, mutability, lifetime]):
self.bytes_left = len(src[])
self.ptr = DTypePointer[DType.uint8](src[]._buffer.data)
@always_inline
fn __next__(inout self) -> String:
# Number of bytes of the current character
var char_length = int((self.ptr.load() >> 7 == 0).cast[DType.uint8]() * 1 + countl_zero(~self.ptr.load()))
# Copy N bytes + null terminator into new pointer and construct string.
var sp = DTypePointer[DType.uint8].alloc(char_length + 1)
memcpy(sp, self.ptr, char_length)
# Move iterator forward
self.bytes_left -= char_length
self.ptr += char_length
return StringSlice[mutability, lifetime](unsafe_from_utf8_strref=StringRef(sp, char_length))
@always_inline
fn __len__(self) -> Int:
return self.bytes_left
| gojo/gojo/uniutf8/string.mojo | false |
<filename>gojo/gojo/uniutf8/__init__.mojo
"""Almost all of the actual implementation in this module was written by @mzaks (https://github.com/mzaks)!
This would not be possible without his help.
"""
from .runes import rune_count_in_string
from .string import UnicodeString
| gojo/gojo/uniutf8/__init__.mojo | false |
from tests.wrapper import MojoTest
from gojo.bytes import buffer
from gojo.builtins.bytes import to_string
from gojo.bufio import Reader, Scanner, scan_words, scan_bytes, Writer, new_writer, new_reader
from gojo.io import read_all, FileWrapper
from gojo.strings import StringBuilder
fn test_read():
var test = MojoTest("Testing bufio.Reader.read")
# Create a reader from a string buffer
var s: String = "Hello"
var buf = buffer.new_buffer(s)
var reader = Reader(buf^)
# Read the buffer into List[UInt8] and then add more to List[UInt8]
var dest = List[UInt8](capacity=256)
_ = reader.read(dest)
dest.extend(String(" World!").as_bytes())
test.assert_equal(to_string(dest), "Hello World!")
fn test_read_all():
var test = MojoTest("Testing bufio.Reader with io.read_all")
var s: String = "0123456789"
var buf = buffer.new_reader(s)
var reader = Reader(buf^)
var result = read_all(reader)
var bytes = result[0]
bytes.append(0)
test.assert_equal(String(bytes), "0123456789")
# fn test_write_to():
# var test = MojoTest("Testing bufio.Reader.write_to")
# var buf = buffer.new_buffer("0123456789")
# var reader = Reader(buf^)
# # Create a new writer containing the content "Hello World"
# var writer = buffer.new_buffer("Hello World")
# # Write the content of the reader to the writer
# _ = reader.write_to(writer)
# # Check if the content of the writer is "Hello World0123456789"
# test.assert_equal(str(writer), "Hello World0123456789")
fn test_read_and_unread_byte():
var test = MojoTest("Testing bufio.Reader.read_byte and bufio.Reader.unread_byte")
# Read the first byte from the reader.
var example: String = "Hello, World!"
var buf = buffer.new_buffer(example^)
var reader = Reader(buf^)
var result = reader.read_byte()
test.assert_equal(int(result[0]), int(72))
var post_read_position = reader.read_pos
# Unread the first byte from the reader. Read position should be moved back by 1
_ = reader.unread_byte()
test.assert_equal(reader.read_pos, post_read_position - 1)
fn test_read_slice():
var test = MojoTest("Testing bufio.Reader.read_slice")
var buf = buffer.new_buffer("0123456789")
var reader = Reader(buf^)
var result = reader.read_slice(ord("5"))
test.assert_equal(to_string(result[0]), "012345")
fn test_read_bytes():
var test = MojoTest("Testing bufio.Reader.read_bytes")
var buf = buffer.new_buffer("01234\n56789")
var reader = Reader(buf^)
var result = reader.read_bytes(ord("\n"))
test.assert_equal(to_string(result[0]), "01234")
fn test_read_line():
var test = MojoTest("Testing bufio.Reader.read_line")
var buf = buffer.new_buffer("01234\n56789")
var reader = Reader(buf^)
var line: List[UInt8]
var b: Bool
line, b = reader.read_line()
test.assert_equal(String(line), "01234")
fn test_peek():
var test = MojoTest("Testing bufio.Reader.peek")
var buf = buffer.new_buffer("01234\n56789")
var reader = Reader(buf^)
# Peek doesn't advance the reader, so we should see the same content twice.
var result = reader.peek(5)
var second_result = reader.peek(5)
test.assert_equal(to_string(result[0]), "01234")
test.assert_equal(to_string(second_result[0]), "01234")
fn test_discard():
var test = MojoTest("Testing bufio.Reader.discard")
var buf = buffer.new_buffer("0123456789")
var reader = Reader(buf^)
var result = reader.discard(5)
test.assert_equal(result[0], 5)
# Peek doesn't advance the reader, so we should see the same content twice.
var second_result = reader.peek(5)
test.assert_equal(to_string(second_result[0]), "56789")
fn test_write():
var test = MojoTest("Testing bufio.Writer.write and flush")
# Create a new List[UInt8] Buffer Writer and use it to create the buffered Writer
# var buf = buffer.new_buffer()
var writer = new_writer(buffer.new_buffer())
# var writer = Writer(buf^)
# Write the content from src to the buffered writer's internal buffer and flush it to the List[UInt8] Buffer Writer.
var src = String("0123456789").as_bytes()
var result = writer.write(src)
_ = writer.flush()
test.assert_equal(result[0], 10)
test.assert_equal(str(writer.writer), "0123456789")
fn test_several_writes():
var test = MojoTest("Testing several bufio.Writer.write")
# Create a new List[UInt8] Buffer Writer and use it to create the buffered Writer
var buf = buffer.new_buffer()
var writer = Writer(buf^)
# Write the content from src to the buffered writer's internal buffer and flush it to the List[UInt8] Buffer Writer.
var src = String("0123456789").as_bytes()
for _ in range(100):
_ = writer.write(src)
_ = writer.flush()
test.assert_equal(len(writer.writer), 1000)
var text = str(writer.writer)
test.assert_equal(text[0], "0")
test.assert_equal(text[999], "9")
fn test_big_write():
var test = MojoTest("Testing a big bufio.Writer.write")
# Create a new List[UInt8] Buffer Writer and use it to create the buffered Writer
var buf = buffer.new_buffer()
var writer = Writer(buf^)
# Build a string larger than the size of the Bufio struct's internal buffer.
var builder = StringBuilder(capacity=5000)
for _ in range(500):
_ = builder.write_string("0123456789")
# When writing, it should bypass the Bufio struct's buffer and write directly to the underlying bytes buffer writer. So, no need to flush.
var text = str(builder)
_ = writer.write(text.as_bytes())
test.assert_equal(len(writer.writer), 5000)
test.assert_equal(text[0], "0")
test.assert_equal(text[4999], "9")
fn test_write_byte():
var test = MojoTest("Testing bufio.Writer.write_byte")
# Create a new List[UInt8] Buffer Writer and use it to create the buffered Writer
var buf = buffer.new_buffer("Hello")
var writer = Writer(buf^)
# Write a byte with the value of 32 to the writer's internal buffer and flush it to the List[UInt8] Buffer Writer.
var result = writer.write_byte(32)
_ = writer.flush()
test.assert_equal(result[0], 1)
test.assert_equal(str(writer.writer), "Hello ")
fn test_write_string():
var test = MojoTest("Testing bufio.Writer.write_string")
# Create a new List[UInt8] Buffer Writer and use it to create the buffered Writer
var buf = buffer.new_buffer("Hello")
var writer = Writer(buf^)
# Write a string to the writer's internal buffer and flush it to the List[UInt8] Buffer Writer.
var result = writer.write_string(" World!")
_ = writer.flush()
test.assert_equal(result[0], 7)
test.assert_equal(str(writer.writer), "Hello World!")
fn test_read_from():
var test = MojoTest("Testing bufio.Writer.read_from")
# Create a new List[UInt8] Buffer Writer and use it to create the buffered Writer
var buf = buffer.new_buffer("Hello")
var writer = Writer(buf^)
# Read from a ReaderFrom struct into the Buffered Writer's internal buffer and flush it to the List[UInt8] Buffer Writer.
var src = String(" World!").as_bytes()
var reader_from = buffer.new_buffer(src)
var result = writer.read_from(reader_from)
_ = writer.flush()
test.assert_equal(int(result[0]), 7)
test.assert_equal(str(writer.writer), "Hello World!")
# TODO: Add big file read/write to make sure buffer usage is correct
fn main():
test_read()
test_read_all()
# test_write_to()
test_read_and_unread_byte()
test_read_slice()
test_peek()
test_discard()
test_write()
test_several_writes()
test_big_write()
test_write_byte()
test_write_string()
test_read_from()
| gojo/tests/test_bufio.mojo | false |
from tests.wrapper import MojoTest
from gojo.bytes import buffer
from gojo.io import FileWrapper
from gojo.bufio import Reader, Scanner, scan_words, scan_bytes, scan_runes
fn test_scan_words():
var test = MojoTest("Testing bufio.scan_words")
# Create a reader from a string buffer
var s: String = "Testing this string!"
var buf = buffer.new_buffer(s)
var r = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner[split=scan_words](r^)
var expected_results = List[String]("Testing", "this", "string!")
var i = 0
while scanner.scan():
test.assert_equal(scanner.current_token(), expected_results[i])
i += 1
fn test_scan_lines():
var test = MojoTest("Testing bufio.scan_lines")
# Create a reader from a string buffer
var s: String = "Testing\nthis\nstring!"
var buf = buffer.new_buffer(s)
var r = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner(r^)
var expected_results = List[String]("Testing", "this", "string!")
var i = 0
while scanner.scan():
test.assert_equal(scanner.current_token(), expected_results[i])
i += 1
fn scan_no_newline_test(test_case: String, result_lines: List[String], test: MojoTest):
# Create a reader from a string buffer
var buf = buffer.new_buffer(test_case)
var r = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner(r^)
var i = 0
while scanner.scan():
test.assert_equal(scanner.current_token(), result_lines[i])
i += 1
fn test_scan_lines_no_newline():
var test = MojoTest("Testing bufio.scan_lines with no final newline")
var test_case = "abcdefghijklmn\nopqrstuvwxyz"
var result_lines = List[String]("abcdefghijklmn", "opqrstuvwxyz")
scan_no_newline_test(test_case, result_lines, test)
fn test_scan_lines_cr_no_newline():
var test = MojoTest("Testing bufio.scan_lines with no final newline but carriage return")
var test_case = "abcdefghijklmn\nopqrstuvwxyz\r"
var result_lines = List[String]("abcdefghijklmn", "opqrstuvwxyz")
scan_no_newline_test(test_case, result_lines, test)
fn test_scan_lines_empty_final_line():
var test = MojoTest("Testing bufio.scan_lines with an empty final line")
var test_case = "abcdefghijklmn\nopqrstuvwxyz\n\n"
var result_lines = List[String]("abcdefghijklmn", "opqrstuvwxyz", "")
scan_no_newline_test(test_case, result_lines, test)
fn test_scan_lines_cr_empty_final_line():
var test = MojoTest("Testing bufio.scan_lines with an empty final line and carriage return")
var test_case = "abcdefghijklmn\nopqrstuvwxyz\n\r"
var result_lines = List[String]("abcdefghijklmn", "opqrstuvwxyz", "")
scan_no_newline_test(test_case, result_lines, test)
fn test_scan_bytes():
var test = MojoTest("Testing bufio.scan_bytes")
var test_cases = List[String]("", "a", "abc", "abc def\n\t\tgh ")
for i in range(len(test_cases)):
var test_case = test_cases[i]
# Create a reader from a string buffer
var buf = buffer.new_buffer(test_case)
var reader = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner[split=scan_bytes](reader^)
var j = 0
while scanner.scan():
test.assert_equal(scanner.current_token(), test_case[j])
j += 1
fn test_file_wrapper_scanner() raises:
var test = MojoTest("testing io.FileWrapper and bufio.Scanner")
var file = FileWrapper("tests/data/test_multiple_lines.txt", "r")
# Create a scanner from the reader
var scanner = Scanner(file^)
var expected_results = List[String]("11111", "22222", "33333", "44444", "55555")
var i = 0
while scanner.scan():
test.assert_equal(scanner.current_token(), expected_results[i])
i += 1
fn test_scan_runes():
var test = MojoTest("Testing bufio.scan_runes")
# Create a reader from a string buffer
var s: String = "πͺπ₯πͺ"
var buf = buffer.new_buffer(s)
var r = Reader(buf^)
# Create a scanner from the reader
var scanner = Scanner[split=scan_runes](r^)
var expected_results = List[String]("πͺ", "π₯", "πͺ")
var i = 0
while scanner.scan():
test.assert_equal(scanner.current_token(), expected_results[i])
i += 1
fn main() raises:
test_scan_words()
test_scan_lines()
test_scan_lines_no_newline()
test_scan_lines_cr_no_newline()
test_scan_lines_empty_final_line()
test_scan_lines_cr_empty_final_line()
test_scan_bytes()
test_file_wrapper_scanner()
test_scan_runes()
| gojo/tests/test_bufio_scanner.mojo | false |
<filename>gojo/tests/test_builtins_bytes.mojo
from tests.wrapper import MojoTest
from testing import testing
from gojo.builtins.bytes import Byte, index_byte
fn test_index_byte():
var test = MojoTest("Testing builtins.List[Byte] slice")
var bytes = String("hello\n").as_bytes()
test.assert_equal(index_byte(bytes, ord("\n")), 5)
fn test_size_and_len():
var test = MojoTest("Testing builtins.List[Byte].size and builtins.List[Byte].__len__")
var bytes = List[Byte](capacity=16)
# Size is the number of bytes used, len is the number of bytes allocated.
test.assert_equal(bytes.capacity, 16)
test.assert_equal(len(bytes), 0)
fn main():
# test_slice_out_of_bounds()
test_index_byte()
test_size_and_len()
| gojo/tests/test_builtins_bytes.mojo | false |
from tests.wrapper import MojoTest
from gojo.bytes import new_buffer
from gojo.bytes.buffer import Buffer
fn test_read() raises:
var test = MojoTest("Testing bytes.Buffer.read")
var s: String = "Hello World!"
var buf = new_buffer(s)
var dest = List[UInt8](capacity=16)
_ = buf.read(dest)
dest.append(0)
test.assert_equal(String(dest), s)
fn test_read_byte() raises:
var test = MojoTest("Testing bytes.Buffer.read_byte")
var s: String = "Hello World!"
var buf = new_buffer(s)
var result = buf.read_byte()
test.assert_equal(int(result[0]), 72)
fn test_unread_byte() raises:
var test = MojoTest("Testing bytes.Buffer.unread_byte")
var s: String = "Hello World!"
var buf = new_buffer(s)
var result = buf.read_byte()
test.assert_equal(int(result[0]), 72)
test.assert_equal(buf.offset, 1)
_ = buf.unread_byte()
test.assert_equal(buf.offset, 0)
fn test_read_bytes() raises:
var test = MojoTest("Testing bytes.Buffer.read_bytes")
var s: String = "Hello World!"
var buf = new_buffer(s)
var result = buf.read_bytes(ord("o"))
var text = result[0]
text.append(0)
test.assert_equal(String(text), String("Hello"))
fn test_read_slice() raises:
var test = MojoTest("Testing bytes.Buffer.read_slice")
var s: String = "Hello World!"
var buf = new_buffer(s)
var result = buf.read_slice(ord("o"))
var text = List[UInt8](result[0])
text.append(0)
test.assert_equal(String(text), String("Hello"))
fn test_read_string() raises:
var test = MojoTest("Testing bytes.Buffer.read_string")
var s: String = "Hello World!"
var buf = new_buffer(s)
var result = buf.read_string(ord("o"))
test.assert_equal(String(result[0]), String("Hello"))
fn test_next() raises:
var test = MojoTest("Testing bytes.Buffer.next")
var buf = new_buffer("Hello World!")
var text = List[UInt8](buf.next(5))
text.append(0)
test.assert_equal(String(text), String("Hello"))
fn test_write() raises:
var test = MojoTest("Testing bytes.Buffer.write")
var b = List[UInt8](capacity=16)
var buf = new_buffer(b^)
_ = buf.write(String("Hello World!").as_bytes_slice())
test.assert_equal(str(buf), String("Hello World!"))
fn test_write_string() raises:
var test = MojoTest("Testing bytes.Buffer.write_string")
var b = List[UInt8](capacity=16)
var buf = new_buffer(b^)
_ = buf.write_string("\nGoodbye World!")
test.assert_equal(str(buf), String("\nGoodbye World!"))
fn test_write_byte() raises:
var test = MojoTest("Testing bytes.Buffer.write_byte")
var b = List[UInt8](capacity=16)
var buf = new_buffer(b^)
_ = buf.write_byte(0x41)
test.assert_equal(str(buf), String("A"))
fn test_new_buffer() raises:
var test = MojoTest("Testing bytes.new_buffer")
var b = String("Hello World!").as_bytes()
var buf = new_buffer(b^)
test.assert_equal(str(buf), "Hello World!")
buf = new_buffer("Goodbye World!")
test.assert_equal(str(buf), "Goodbye World!")
buf = new_buffer()
test.assert_equal(str(buf), "")
fn main() raises:
test_read()
test_read_byte()
test_unread_byte()
test_read_slice()
test_read_bytes()
test_read_string()
test_next()
test_write()
test_write_string()
test_write_byte()
test_new_buffer()
| gojo/tests/test_bytes_buffer.mojo | false |