Created
September 12, 2012 07:55
-
-
Save fowlmouth/3705038 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import endians | |
proc swapEndian16*(outp, inp: pointer) = | |
## copies `inp` to `outp` swapping bytes. Both buffers are supposed to | |
## contain at least 2 bytes. | |
var i = cast[cstring](inp) | |
var o = cast[cstring](outp) | |
o[0] = i[1] | |
o[1] = i[0] | |
when cpuEndian == bigEndian: | |
proc bigEndian16(outp, inp: pointer) {.inline.} = copyMem(outp, inp, 2) | |
else: | |
proc bigEndian16*(outp, inp: pointer) {.inline.} = swapEndian16(outp, inp) | |
proc readBE*[T: int16|uint16](src: var string; pos: var int; outp: var T) = | |
bigEndian16(addr outp, addr src[pos]) | |
inc pos, 2 | |
proc readBE*[T: float32|int32|uint32](src: var string; pos: var int; outp: var T) = | |
bigEndian32(addr outp, addr src[pos]) | |
inc pos, 4 | |
proc readBE*[T: float64|int64|uint64](src: var string; pos: var int; outp: var T) = | |
bigEndian64(addr outp, addr src[pos]) | |
inc pos, 8 | |
proc writeBE*[T: int16|uint16](dest: var string; pos: var int; val: var T) = | |
bigEndian16(addr dest[pos], addr val) | |
inc pos, 2 | |
proc writeBE*[T: int32|uint32|float32](dest: var string; pos: var int; val: var T) = | |
bigEndian32(addr dest[pos], addr val) | |
inc pos, 4 | |
proc writeBE*[T: int64|uint64|float64](dest: var string; pos: var int; val: var T) = | |
bigEndian64(addr dest[pos], addr val) | |
inc pos, 8 | |
proc readInt16(src: var string; pos: var int): int16 = | |
readBE src, pos, result | |
proc readInt32(src: var string; pos: var int): int32 = | |
readBE src, pos, result | |
proc readInt64(src: var string; pos: var int): int64 = | |
readBE src, pos, result | |
when isMainModule: | |
var | |
s2 = "" | |
ani16 = 9001'u16 | |
ani32 = low(int32) | |
ani64 = high(int64)-1 | |
i = 0 | |
template dumpvars() = echo ani32, " ", ani16, " ", ani64 | |
s2.setlen 50 | |
writeBE s2, i, ani32 | |
writeBE s2, i, ani16 | |
writeBE s2, i, ani64 | |
s2.setlen i | |
dumpvars() | |
echo(repr(s2), " ", len(s2)) | |
ani16 = 0 | |
ani32 = 0 | |
ani64 = 0 | |
i = 0 | |
readBE s2, i, ani32 | |
readBE s2, i, ani16 | |
readBE s2, i, ani64 | |
dumpvars() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment