File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ # # https://forum.nim-lang.org/t/1188#7366
2
+ # # https://forum.nim-lang.org/t/1188#7374
3
+ # # https://forum.nim-lang.org/t/1188#17709
4
+ template ptrMath * (body: untyped ) =
5
+ template `+` [T](p: ptr T, off: SomeInteger ): ptr T =
6
+ # cast[ptr type(p[])](cast[ByteAddress](p) +% off * sizeof(p[]))
7
+ cast [ptr T](cast [ByteAddress ](p) +% off * sizeof (T))
8
+
9
+ template `+=` [T](p: ptr T, off: SomeInteger ) =
10
+ p = p + off
11
+
12
+ template `-` [T](p: ptr T, off: SomeInteger ): ptr T =
13
+ # cast[ptr type(p[])](cast[ByteAddress](p) -% off * sizeof(p[]))
14
+ cast [ptr T](cast [ByteAddress ](p) -% off * sizeof (T))
15
+
16
+ template `-=` [T](p: ptr T, off: SomeInteger ) =
17
+ p = p - off
18
+
19
+ template `[]` [T](p: ptr T, off: SomeInteger ): T =
20
+ (p + off )[]
21
+
22
+ template `[]=` [T](p: ptr T, off: SomeInteger , val: T) =
23
+ (p + off )[] = val
24
+
25
+ body
26
+
27
+ when isMainModule :
28
+ ptrMath:
29
+ var a: array [0 .. 3 , int ]
30
+ for i in a.low.. a.high:
31
+ a[i] += i
32
+ var p = addr (a[0 ])
33
+ p += 1
34
+ p[0 ] -= 2
35
+ echo p[0 ], " " , p[1 ]
You can’t perform that action at this time.
0 commit comments