-
Notifications
You must be signed in to change notification settings - Fork 8
/
Pointer.mojo
49 lines (38 loc) · 1.2 KB
/
Pointer.mojo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from Pointer import Pointer
from Memory import memset_zero
from SIMD import SIMD
@register_passable
struct Coord:
var x: UI8
var y: UI8
struct Coords:
var data: Pointer[Coord]
var length: Int
fn __init__(inout self, length: Int) raises: # keyword raises https://docs.modular.com/mojo/programming-manual.html#fn-definitions
self.data = Pointer[Coord].alloc(length)
memset_zero(self.data, length)
self.length = length
fn __getitem__(self, index: Int) raises -> Coord:
if index > self.length - 1:
raise Error("Trying to access index out of bounds")
return self.data.load(index)
fn __del__(owned self):
self.data.free()
fn store_coord(inout self, offset: Int, value: Coord):
return self.data.store(offset, value)
var coords = Coords(5)
var second = coords[2]
print("second.x:", second.x)
second.x = 1
print("second.x = 1:", second.x)
print("pointer.data[2].x:", coords.data[2].x)
coords.store_coord(2, second) # or coords.data.store(2, second)
print("second.x = 1:", second.x)
print("pointer.data[2].x:", coords.data[2].x)
"""
second.x: 0
second.x = 1: 1
pointer.data[2].x: 0
second.x = 1: 1
pointer.data[2].x: 1
"""