1 ! Copyright (C) 2006, 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors byte-arrays byte-vectors checksums grouping
4 io.binary kernel locals make math sequences ;
7 : calculate-pad-length ( length -- length' )
8 [ 56 < 55 119 ? ] keep - ;
10 : pad-last-block ( bytes big-endian? length -- blocks )
13 [ 0x3f bitand calculate-pad-length <byte-array> % ]
14 [ 3 shift 8 rot [ >be ] [ >le ] if % ] bi
15 ] B{ } make 64 group ;
19 INSTANCE: block-checksum checksum
21 TUPLE: block-checksum-state < checksum-state
22 { bytes-read integer }
23 { block-size integer } ;
25 GENERIC: checksum-block ( bytes checksum-state -- )
27 ! Update the bytes-read before calculating checksum in case
28 ! checksum uses this in the calculation.
29 M:: block-checksum-state add-checksum-bytes ( state data -- state )
30 state block-size>> :> block-size
31 state bytes>> length :> initial-len
32 initial-len data length + block-size /mod :> ( n extra )
33 data state bytes>> [ push-all ] keep :> all-bytes
34 all-bytes block-size <groups>
35 extra zero? [ f ] [ unclip-last-slice ] if :> ( blocks remain )
37 state [ initial-len - ] change-bytes-read drop
40 state [ block-size + ] change-bytes-read
44 state [ extra + ] change-bytes-read
45 remain [ >byte-vector ] [ BV{ } clone ] if* >>bytes ;
47 M: block-checksum checksum-bytes
48 [ swap add-checksum-bytes get-checksum ] with-checksum-state ;
50 M: block-checksum checksum-stream
51 [ swap add-checksum-stream get-checksum ] with-checksum-state ;