Skip to content

Commit

Permalink
Add reinterpretPtr.nim
Browse files Browse the repository at this point in the history
  • Loading branch information
demotomohiro committed Apr 12, 2024
1 parent d1756b0 commit e01762e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ This is similar to std/deques, but has fixed size storage that can be allocated

### [staticSeq](https://demotomohiro.github.io/littlesugar/staticSeq.html)
This is similar to seq, but internal storage size is fixed to `N` and it can be allocated on stack.

### [reinterpretPtr](https://demotomohiro.github.io/littlesugar/reinterpretPtr.html)
Reinterpret the given pointer to a different pointer type.
1 change: 1 addition & 0 deletions littlesugar.nimble
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ task docgen, "Generate html documents":
selfExec "doc --outdir:htmldocs --index:on src/littlesugar/setLambda.nim"
selfExec "doc --outdir:htmldocs --index:on src/littlesugar/staticDeque.nim"
selfExec "doc --outdir:htmldocs --index:on src/littlesugar/staticSeq.nim"
selfExec "doc --outdir:htmldocs --index:on src/littlesugar/reinterpretPtr.nim"
selfExec "buildIndex -o:htmldocs/theindex.html htmldocs"
25 changes: 25 additions & 0 deletions src/littlesugar/reinterpretPtr.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
func reinterpretPtr*[T: ptr](src: ptr or pointer): T =
## Reinterpret the given pointer to a different pointer type.
##
## This is same to cast, but only accepts a pointer type for safer type convertion.
## But it still can be unsafe.
cast[T](src)

when isMainModule:
var
a = 123
pa = a.addr
pa2: pointer = pa

doAssert reinterpretPtr[ptr int](pa2) is ptr int
doAssert reinterpretPtr[ptr int](pa2)[] == 123
doAssert not compiles(reinterpretPtr[ptr int](a))
doAssert reinterpretPtr[ptr int](nil) is ptr int
doAssert reinterpretPtr[ptr int](nil) == nil

var
s = "Hello"
cs = s.cstring
ps: pointer = cs
doAssert reinterpretPtr[cstring](ps) is cstring
doAssert reinterpretPtr[cstring](ps) == "Hello"

0 comments on commit e01762e

Please sign in to comment.