1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: accessors ascii byte-arrays byte-vectors combinators
5 command-line destructors fry io io.encodings io.encodings.binary
6 io.encodings.string io.encodings.utf8 io.files io.streams.string
7 kernel literals locals math math.parser namespaces sequences
8 sequences.private strings typed ;
14 CONSTANT: line# "00000000 "
17 7 [ CHAR: 0 = over 0 > and ] [
20 { CHAR: 9 [ CHAR: a ] }
21 { CHAR: f [ CHAR: 0 ] }
28 8 [ CHAR: 0 swap line# set-nth ] each-integer ;
30 CONSTANT: hex-digits $[
31 256 <iota> [ >hex 2 CHAR: 0 pad-head " " append ] map
34 : all-bytes ( bytes -- from to bytes )
35 [ 0 swap length ] keep ; inline
37 : each-byte ( from to bytes quot: ( elt -- ) -- )
38 '[ _ nth-unsafe @ ] each-integer-from ; inline
40 : write-bytes ( from to bytes stream -- )
41 '[ hex-digits nth-unsafe _ stream-write ] each-byte ; inline
43 : write-space ( from to bytes stream -- )
44 [ drop - 16 + ] dip '[
45 3 * CHAR: \s <string> _ stream-write
46 ] unless-zero ; inline
48 : write-ascii ( from to bytes stream -- )
50 [ printable? ] keep CHAR: . ? _ stream-write1
53 TYPED: write-hex-line ( from: fixnum to: fixnum bytes: byte-array -- )
54 line# write inc-line# output-stream get {
60 :: hexdump-bytes ( from to bytes -- )
64 [ [ 16 * dup 16 + bytes write-hex-line ] each-integer ]
65 [ [ len swap - len bytes write-hex-line ] unless-zero ] bi*
66 len >hex 8 CHAR: 0 pad-head print ;
68 : hexdump-stream ( stream -- )
70 all-bytes [ write-hex-line ] [ length + ] bi
71 ] 16 (each-stream-block) >hex 8 CHAR: 0 pad-head print ;
75 GENERIC: hexdump. ( byte-array -- )
77 M: byte-array hexdump. all-bytes hexdump-bytes ;
79 M: byte-vector hexdump. all-bytes underlying>> hexdump-bytes ;
81 M: string hexdump. utf8 encode hexdump. ;
84 : hexdump ( byte-array -- str )
85 [ hexdump. ] with-string-writer ;
87 : hexdump-file ( path -- )
88 binary <file-reader> [ hexdump-stream ] with-disposal ;
92 input-stream get binary re-decode hexdump-stream