Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@
- Added `progressInterval` argument to `asyncftpclient.newAsyncFtpClient` to control the interval
at which progress callbacks are called.

- Added `std/pointers` to handle `ptr[T]` variables without needing `cast`.

## Language changes

Expand Down
33 changes: 33 additions & 0 deletions lib/std/pointers.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
##[
Convenience procs to process `ptr[T]` variables without requiring `cast`.
]##

runnableExamples:
var a = @[10, 11, 12]
let pa = a[0].addr
doAssert (pa + 1)[] == 11
doAssert pa[2] == 12
pa[1] = 2
doAssert a[1] == 2


template `+`*[T](p: ptr T, off: int): ptr T =
type T = typeof(p[]) # pending https://github.com/nim-lang/Nim/issues/13527
cast[ptr T](cast[ByteAddress](p) +% off * sizeof(T))

template `-`*[T](p: ptr T, off: int): ptr T =
type T = typeof(p[])
cast[ptr T](cast[ByteAddress](p) -% off * sizeof(T))

template `[]`*[T](p: ptr T, off: int): T =
(p + off)[]

template `[]=`*[T](p: ptr T, off: int, val: T) =
(p + off)[] = val
Comment on lines +22 to +26
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are far too dangerous to have this innocent, common syntax.


proc `+=`*[T](p: var ptr T, off: int) {.inline.} =
# not a template to avoid double evaluation issues
p = p + off

proc `-=`*[T](p: var ptr T, off: int) {.inline.} =
p = p - off
19 changes: 19 additions & 0 deletions tests/stdlib/tpointers.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import std/pointers

block:
var a = @[10, 11, 12]
let pa = a[0].addr
let pb = pa + 1
doAssert pb[] == 11
doAssert (pb - 1)[] == 10
pa[] = 100
doAssert a[0] == 100
doAssert pa[1] == 11

var pc = pa
pc += 1
doAssert pc[] == 11
doAssert pc[0] == 11
doAssert pc == pb
pc -= 1
doAssert pc == pa