mango/host/assembler/print.fnl

45 lines
1.1 KiB
Fennel

(local {:map map} (require :deps.lume))
(fn string->bytes [s]
(table.pack (string.byte s 1 -1)))
(fn bytes->string [x] (string.char (table.unpack x)))
(fn show-bytes [byte-string]
"print a string as human readble bytes"
(let [formatted (map (string->bytes byte-string)
(λ [byte]
(if byte
(string.format :%02x byte)
"##")))]
(table.concat formatted " ")))
(fn show-ascii [byte-string]
(-> byte-string
(string->bytes)
(map (lambda [byte] (if (< 31 byte 126) byte 46)))
(bytes->string)))
(fn pad-string [s count]
(string.format (.. :%- count :s) s))
(fn print-string [byte-string]
(let [row-len 8
len (length byte-string)
full-rows (math.floor (/ len row-len))
rest (math.modf len full-rows)]
(for [i 0 full-rows 1]
(let [row (byte-string:sub
(+ 1 (* row-len i))
(+ row-len (* row-len i)))]
(when (< 0 (length row))
(print (..
:| (pad-string (show-bytes row) (- (* 3 row-len) 1))
:|
" "
:|
(pad-string (show-ascii row) row-len)
:|)))))))
{: print-string}