Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add UFCS/MCS cast, and addrCast #28

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
[nim-lang/RFCs#245](https://github.com/nim-lang/RFCs/issues/245)
- Added module `astdsl` that contains macro `buildAst`. That is a DSL for convenient
construction of Nim ASTs.
- Added module `pointers` containing `toUncheckedArray`.
- Added `filepermissions.chmod` and `filepermissions.fromFilePermissions`,
convenience functions to change file permissions using Unix like octal file permissions.
- Added module `scripting` providing `withDir` to switch the directory temporarily. This
Expand All @@ -19,3 +18,4 @@
- Added `jssets` module, Set for the JavaScript target
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
- Added `jsheaders` module for [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) for the JavaScript target.
- Added module `pointers` containing `toUncheckedArray`, UFCS/MCS `cast`, `addrCast`
29 changes: 29 additions & 0 deletions src/fusion/pointers.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,32 @@ proc toUncheckedArray*[T](a: ptr T): ptr UncheckedArray[T] {.inline.} =
pa[0] += 5
doAssert a[1] == 105
cast[ptr UncheckedArray[T]](a)

template `cast`*[T](a:T, T2: typedesc): untyped =
## Same as `cast[T2](a)` but can be used in UFCS/MCS chains.
## Unsafe as it calls `cast`.
runnableExamples:
var a = [1'u8, 2, 3, 4]
# the MCS chain reads left to right:
let x1 = a.cast(array[2, uint16])[0].cast(char)
# instead of a zig-zag:
let x2 = cast[char](cast[array[2, uint16]](a)[0])
doAssert x1 == x2
cast[T2](a)

template addrCast*[T](a:T, T2: typedesc): untyped =
## Same as `cast[ptr T2](unsafeAddr(a))[]` but can be used in UFCS/MCS chains.
## Unsafe as it calls `cast`.
runnableExamples:
proc fn(a: var auto): auto =
a[0].inc
a
var a = [1'u8, 2, 3, 4]
let b = fn(a.addrCast(array[2, uint16]))
doAssert a == [2'u8, 2, 3, 4]
when system.cpuEndian == littleEndian:
doAssert b == [514'u16, 1027]
doAssert a.addrCast(uint32) == 67305986'u32
a.addrCast(uint32).inc
doAssert a == [3'u8, 2, 3, 4]
cast[ptr T2](unsafeAddr(a))[]