File tree Expand file tree Collapse file tree 3 files changed +48
-1
lines changed
Expand file tree Collapse file tree 3 files changed +48
-1
lines changed Original file line number Diff line number Diff line change 11## additions and changes
22
3- - Added module ` pointers ` containing ` toUncheckedArray `
3+ - Added module ` pointers ` containing ` toUncheckedArray ` and pointer arithmetic operators and indexing
Original file line number Diff line number Diff line change @@ -15,3 +15,31 @@ proc toUncheckedArray*[T](a: ptr T): ptr UncheckedArray[T] {.inline.} =
1515 pa[0 ] += 5
1616 doAssert a[1 ] == 105
1717 cast [ptr UncheckedArray [T]](a)
18+
19+ template `+` * [T](p: ptr T, off: int ): ptr T =
20+ runnableExamples:
21+ var a = @ [10 , 11 , 12 ]
22+ let pa = a[0 ].addr
23+ doAssert (pa + 1 )[] == 11
24+ doAssert pa[2 ] == 12
25+ pa[1 ] = 2
26+ doAssert a[1 ] == 2
27+ type T = typeof (p[]) # pending https://github.com/nim-lang/Nim/issues/13527
28+ cast [ptr T](cast [ByteAddress ](p) +% off * sizeof (T))
29+
30+ template `-` * [T](p: ptr T, off: int ): ptr T =
31+ type T = typeof (p[])
32+ cast [ptr T](cast [ByteAddress ](p) -% off * sizeof (T))
33+
34+ template `[]` * [T](p: ptr T, off: int ): T =
35+ (p + off )[]
36+
37+ template `[]=` * [T](p: ptr T, off: int , val: T) =
38+ (p + off )[] = val
39+
40+ proc `+=` * [T](p: var ptr T, off: int ) {.inline .} =
41+ # not a template to avoid double evaluation issues
42+ p = p + off
43+
44+ proc `-=` * [T](p: var ptr T, off: int ) {.inline .} =
45+ p = p - off
Original file line number Diff line number Diff line change 1+ import fusion/ pointers
2+
3+ block :
4+ var a = @ [10 , 11 , 12 ]
5+ let pa = a[0 ].addr
6+ let pb = pa + 1
7+ doAssert pb[] == 11
8+ doAssert (pb - 1 )[] == 10
9+ pa[] = 100
10+ doAssert a[0 ] == 100
11+ doAssert pa[1 ] == 11
12+
13+ var pc = pa
14+ pc += 1
15+ doAssert pc[] == 11
16+ doAssert pc[0 ] == 11
17+ doAssert pc == pb
18+ pc -= 1
19+ doAssert pc == pa
You can’t perform that action at this time.
0 commit comments