factor/basis/tools/hexdump/hexdump.factor

53 lines
1.3 KiB
Factor
Raw Normal View History

2008-11-13 20:48:11 -05:00
! Copyright (C) 2008 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
USING: arrays ascii byte-arrays byte-vectors command-line
grouping io io.encodings.binary io.files io.streams.string
kernel math math.parser namespaces sequences splitting strings ;
2008-11-13 20:48:11 -05:00
IN: tools.hexdump
<PRIVATE
: write-header ( len -- )
"Length: " write
[ number>string write ", " write ]
[ >hex write "h" write nl ] bi ;
: write-offset ( lineno -- )
16 * >hex 8 char: 0 pad-head write "h: " write ;
2008-11-13 20:48:11 -05:00
: >hex-digit ( digit -- str )
>hex 2 char: 0 pad-head ;
2008-11-13 20:48:11 -05:00
: >hex-digits ( bytes -- str )
2009-04-09 22:03:42 -04:00
[ >hex-digit " " append ] { } map-as concat
48 char: \s pad-tail ;
2008-11-13 20:48:11 -05:00
: >ascii ( bytes -- str )
[ [ printable? ] keep char: . ? ] "" map-as ;
2008-11-13 20:48:11 -05:00
: write-hex-line ( bytes lineno -- )
write-offset [ >hex-digits write ] [ >ascii write ] bi nl ;
2009-02-13 12:57:45 -05:00
: hexdump-bytes ( bytes -- )
2009-02-13 10:55:38 -05:00
[ length write-header ]
[ 16 <groups> [ write-hex-line ] each-index ] bi ;
2009-02-13 10:55:38 -05:00
2008-11-13 20:48:11 -05:00
PRIVATE>
GENERIC: hexdump. ( byte-array -- )
2009-02-13 10:55:38 -05:00
M: byte-array hexdump. hexdump-bytes ;
M: byte-vector hexdump. hexdump-bytes ;
2008-11-13 20:48:11 -05:00
: hexdump ( byte-array -- str )
2008-11-13 20:48:11 -05:00
[ hexdump. ] with-string-writer ;
2009-06-05 23:49:07 -04:00
: hexdump-file ( path -- )
binary file-contents hexdump. ;
: hexdump-main ( -- )
command-line get [ hexdump-file ] each ;
MAIN: hexdump-main