hexdump - code review?
Posted: Fri Dec 17, 2010 4:56 pm
I've implemented a simple hexdump program, imitating the behavior of hexdump -C. I became a victim of Bug #262, but fortunately the bug reporter mentioned the yield key word - which turned out to be a nicer solution for my problem than implementing IEnumerator.
My first impression: Code written in Cobra looks mostly nice and interoperability with .NET is good. There are multiple places to look for documentation (Cobra web site, MSDN) and it took me a while to find answers. I miss the REPL and introspection from other languages.
Here's my program if somebody has the time to have a look at it. I'm thankful for any suggestions for improvements to help me learn Cobra.
My first impression: Code written in Cobra looks mostly nice and interoperability with .NET is good. There are multiple places to look for documentation (Cobra web site, MSDN) and it took me a while to find answers. I miss the REPL and introspection from other languages.
Here's my program if somebody has the time to have a look at it. I'm thankful for any suggestions for improvements to help me learn Cobra.
class Hexdump
def main
args = CobraCore.commandLineArgs
if args.count < 2
binary_name = args[0].split(c'/').toList.get(-1)
print r'Usage: [binary_name] \[filename\]'
return
line_chars = ''
for n, byte in FileByteStream(args[1]).numbered
line_chars += if(0x1f < byte < 0xff, Convert.toChar(byte), c'.').toString
if (n % 16) == 0
line = String.format('{0:x8}', n)
print '[line] ' stop
hex = String.format('{0:x2}', byte)
print '[hex] ' stop
if (n+1) % 16 == 0
print ' |[line_chars]|'
line_chars = ''
else if (n+1) % 8 == 0
print ' ' stop
n += 1
num = 3*(16 - (n % 16)) + if(0 < (n % 16) <= 8, 1 , 0)
last_line = if(num == 0, '', String(c' ',num) + ' |[line_chars]|')
print last_line
print String.format('{0:x8}', n)
class FileByteStream
var _input
cue init(filename as String)
base.init
try
_input = File.openRead(filename)
catch ioe as IOException
print 'I/O Error: [ioe.message]'
def read as int*
current = _input.readByte
while current <> -1
yield current
current = _input.readByte
yield break
def numbered as KeyValuePair<of int, int>*
n = 0
for byte in .read
yield KeyValuePair<of int, int>(n, byte)
n += 1