Make the swap procs safe for unaligned input ptrs (#9210)
* Make the swap procs safe for unaligned input ptrs The copy to a temporary local variable is often elided by a sufficiently smart compiler when it can prove the input pointer is aligned. Refs #9206 * Explain why copyMem is used
This commit is contained in:
parent
e66b51eb16
commit
1fe949b9d5
1 changed files with 12 additions and 9 deletions
|
|
@ -44,20 +44,23 @@ else:
|
||||||
const useBuiltinSwap = false
|
const useBuiltinSwap = false
|
||||||
|
|
||||||
when useBuiltinSwap:
|
when useBuiltinSwap:
|
||||||
|
template swapOpImpl(T: typedesc, op: untyped) =
|
||||||
|
## We have to use `copyMem` here instead of a simple deference because they
|
||||||
|
## may point to a unaligned address. A sufficiently smart compiler _should_
|
||||||
|
## be able to elide them when they're not necessary.
|
||||||
|
var tmp: T
|
||||||
|
copyMem(addr tmp, inp, sizeOf(T))
|
||||||
|
tmp = op(tmp)
|
||||||
|
copyMem(outp, addr tmp, sizeOf(T))
|
||||||
|
|
||||||
proc swapEndian64*(outp, inp: pointer) {.inline, nosideeffect.}=
|
proc swapEndian64*(outp, inp: pointer) {.inline, nosideeffect.}=
|
||||||
var i = cast[ptr uint64](inp)
|
swapOpImpl(uint64, builtin_bswap64)
|
||||||
var o = cast[ptr uint64](outp)
|
|
||||||
o[] = builtin_bswap64(i[])
|
|
||||||
|
|
||||||
proc swapEndian32*(outp, inp: pointer) {.inline, nosideeffect.}=
|
proc swapEndian32*(outp, inp: pointer) {.inline, nosideeffect.}=
|
||||||
var i = cast[ptr uint32](inp)
|
swapOpImpl(uint32, builtin_bswap32)
|
||||||
var o = cast[ptr uint32](outp)
|
|
||||||
o[] = builtin_bswap32(i[])
|
|
||||||
|
|
||||||
proc swapEndian16*(outp, inp: pointer) {.inline, nosideeffect.}=
|
proc swapEndian16*(outp, inp: pointer) {.inline, nosideeffect.}=
|
||||||
var i = cast[ptr uint16](inp)
|
swapOpImpl(uint16, builtin_bswap16)
|
||||||
var o = cast[ptr uint16](outp)
|
|
||||||
o[] = builtin_bswap16(i[])
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
proc swapEndian64*(outp, inp: pointer) =
|
proc swapEndian64*(outp, inp: pointer) =
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue