Skip to content

Instantly share code, notes, and snippets.

@aturley
Created August 1, 2016 19:25
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 aturley/e90824a27e712f6b95fc67eddcc8f9e2 to your computer and use it in GitHub Desktop.
Save aturley/e90824a27e712f6b95fc67eddcc8f9e2 to your computer and use it in GitHub Desktop.
Naive implementation of a simple hexdump utility in Pony.
class Notify is StdinNotify
let _main: Main tag
new create(main: Main tag) =>
_main = main
fun ref apply(data: Array[U8] iso) =>
_main.add_bytes(consume data)
fun dispose() =>
_main.done()
class HexDump
let _header: String = " 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"
let _bytes: Array[U8] box
let _row_num_fmt: FormatSettingsInt val = recover FormatSettingsInt.set_format(FormatHexBare).set_precision(8).set_width(9) end
let _byte_fmt: FormatSettingsInt val = recover FormatSettingsInt.set_format(FormatHexBare).set_precision(2).set_width(3) end
let _line_fmt: FormatSettingsHolder val = recover FormatSettingsHolder.set_width(_header.size() + 1) end
new create(bytes: Array[U8] box) =>
_bytes = bytes
fun _get_printable(byte: U8): U8 =>
if (byte < 32) or (byte > 126) then
'.'
else
byte
end
fun string(): Array[String] val =>
recover
let s = Array[String]
s.push(_header)
var line = String
var printable = String
for (loc, byte) in _bytes.pairs() do
if (loc % 16) == 0 then
line.append((loc / 16).string(_row_num_fmt))
end
line.append(byte.string(_byte_fmt))
printable.push(_get_printable(byte))
if ((loc % 16) == 15) or ((loc + 1) == _bytes.size()) then
s.push(line.string(_line_fmt) + "|" + printable + "|")
line = String
printable = String
end
end
s
end
actor Main
let _env: Env
var _bytes: Array[U8] trn = recover Array[U8] end
new create(env: Env) =>
_env = env
_env.input(recover Notify(this) end)
be add_bytes(bytes: Array[U8] val) =>
_bytes.append(bytes)
be done() =>
_env.out.printv(HexDump(_bytes = recover Array[U8] end).string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment