Ever find yourself thinking "I wish I could quickly print the contents of this byte buffer somewhere"?
The idea
This is the same as my GameMaker script, but for Haxe!
Bytes does not have an inherent position, so position is supplied as an argument if necessary.
The code
public static function print(bytes:haxe.io.Bytes, pos:Int = -1) { // header: var perRow = 20; var size = bytes.length; var out = new StringBuf(); out.add('Bytes(size: $size'); if (pos >= 0) out.add(', pos: $pos'); out.add('):'); var start = 0; inline function printChars(till:Int) { out.add(" | "); for (k in start ... till) { var c = bytes.get(k); if (c >= 32 && c < 128) { out.addChar(c); } else out.addChar(".".code); } } for (i in 0 ... size) { if (i % perRow == 0) { if (i > 0) printChars(i); out.add('\n'); out.add(StringTools.lpad("" + i, ' ', 6)); out.add(' |'); start = i; } out.addChar(i == pos ? '>'.code : ' '.code); var c = bytes.get(i); var hex = c >> 4; out.addChar(hex >= 10 ? ('A'.code - 10 + hex) : '0'.code + hex); hex = c & 15; out.addChar(hex >= 10 ? ('A'.code - 10 + hex) : '0'.code + hex); } // last row padding: if (size % perRow != 0) { for (_ in 0 ... perRow - size % perRow) out.add(' '); } printChars(size); return out.toString(); }
Example
Snippet:
trace(print(Bytes.ofString("hello there!"))); var b = Bytes.alloc(128); var s = Bytes.ofString("hi!"); b.blit(4, s, 0, s.length); trace(print(b, 4));
Output:
src/Main.hx:50: Bytes(size: 12): 0 | 68 65 6C 6C 6F 20 74 68 65 72 65 21 | hello there! src/Main.hx:54: Bytes(size: 128, pos: 4): 0 | 00 00 00 00>68 69 21 00 00 00 00 00 00 00 00 00 00 00 00 00 | ....hi!............. 20 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | .................... 40 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | .................... 60 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | .................... 80 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | .................... 100 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | .................... 120 | 00 00 00 00 00 00 00 00 | ........
And that's all!