Skip to content

Commit 1e1ed75

Browse files
committed
docs: add documentation about pointer arithmetics
1 parent 86e7a07 commit 1e1ed75

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

docs/basics/pointers.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,48 @@ print(head.next.unwrap().val.value) # 20
9696
print(head.next.unwrap().next.try_unwrap()) # None
9797
```
9898

99+
## Pointer Arithmetic
100+
101+
Typed pointers support C-style pointer arithmetic. Adding or subtracting an integer advances/retreats by that many elements (scaled by the pointed-to type's size):
102+
103+
```python
104+
from libdestruct import c_int, ptr, inflater
105+
from libdestruct.backing.memory_resolver import MemoryResolver
106+
import struct as pystruct
107+
108+
# Memory: [ptr to arr] [10] [20] [30]
109+
memory = bytearray(8 + 12)
110+
memory[0:8] = pystruct.pack("<q", 8) # pointer to offset 8
111+
memory[8:12] = pystruct.pack("<i", 10)
112+
memory[12:16] = pystruct.pack("<i", 20)
113+
memory[16:20] = pystruct.pack("<i", 30)
114+
115+
p = ptr(MemoryResolver(memory, 0), c_int)
116+
117+
print(p.unwrap().value) # 10
118+
print((p + 1).unwrap().value) # 20
119+
print((p + 2).unwrap().value) # 30
120+
```
121+
122+
### Indexing
123+
124+
Use `ptr[n]` as shorthand for `(ptr + n).unwrap()`:
125+
126+
```python
127+
print(p[0].value) # 10
128+
print(p[1].value) # 20
129+
print(p[2].value) # 30
130+
```
131+
132+
### Untyped Pointers
133+
134+
For pointers without a wrapper type, arithmetic advances by 1 byte per unit:
135+
136+
```python
137+
p_raw = ptr(MemoryResolver(memory, 0)) # no wrapper
138+
p2 = p_raw + 4 # advances by 4 bytes
139+
```
140+
99141
## Pointer String Representation
100142

101143
```python

0 commit comments

Comments
 (0)