Skip to content

Instantly share code, notes, and snippets.

@iffy
Last active February 13, 2019 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iffy/a961cdd7625a54e6b179aa2f0d200b54 to your computer and use it in GitHub Desktop.
Save iffy/a961cdd7625a54e6b179aa2f0d200b54 to your computer and use it in GitHub Desktop.
Print out memory in Nim
import strutils
import terminal
template lowerHex(x:untyped):untyped =
toHex(x).toLower()
proc charRepr(x:byte):char =
case x
of 32..126: result = chr(x)
else: result = '.'
proc dumpMem*(p:pointer, N:int, total:int = 0) =
## Print out a chunk of memory
var total = total
if total < N:
total = N
if p == nil:
echo "WARNING: Attempted to dumpMem on nil pointer"
return
var c = 0
var cp = cast[ptr UncheckedArray[byte]](p)
while c < total:
stdout.resetAttributes()
stdout.write(lowerHex(cast[int](cp) + c))
stdout.write(" ")
if c < N:
stdout.setStyle({styleBright})
for i in 0 ..< 8:
if c >= N:
stdout.resetAttributes()
stdout.write(lowerHex(cp[c]))
stdout.write(" ")
c.inc()
stdout.write(" ")
for i in 0 ..< 8:
if c >= N:
stdout.resetAttributes()
stdout.write(lowerHex(cp[c]))
stdout.write(" ")
c.inc()
stdout.resetAttributes()
stdout.write(" |")
for i in 0 ..< 16:
let n = c-16+i
if n >= N:
stdout.resetAttributes()
else:
stdout.setStyle({styleBright})
stdout.write(charRepr(cp[n]))
stdout.resetAttributes()
stdout.write("|\L")
stdout.write("\L")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment