]> gitweb.factorcode.org Git - factor.git/blob - core/checksums/crc32/crc32.factor
endian: replaces io.binary and io.binary.fast.
[factor.git] / core / checksums / crc32 / crc32.factor
1 ! Copyright (C) 2006 Doug Coleman
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: checksums kernel math sequences sequences.private ;
4 IN: checksums.crc32
5
6 CONSTANT: crc32-polynomial 0xedb88320
7
8 CONSTANT: crc32-table V{ }
9
10 256 <iota> [
11     8 [
12         [ 2/ ] [ even? ] bi [ crc32-polynomial bitxor ] unless
13     ] times
14 ] map 0 crc32-table copy
15
16 : (crc32) ( crc ch -- crc )
17     dupd bitxor
18     0xff bitand crc32-table nth-unsafe
19     swap -8 shift bitxor ; inline
20
21 SINGLETON: crc32
22
23 INSTANCE: crc32 checksum
24
25 : init-crc32 ( input checksum -- x y input )
26     drop [ 0xffffffff dup ] dip ; inline
27
28 <PRIVATE
29 : 4>be ( n -- byte-array ) ! duplicated from io.binary, but in core
30     { -24 -16 -8 0 } [ shift 0xff bitand ] with B{ } map-as ;
31 PRIVATE>
32
33 : finish-crc32 ( x y -- bytes )
34     bitxor 4>be ; inline
35
36 M: crc32 checksum-bytes
37     init-crc32
38     [ (crc32) ] each
39     finish-crc32 ; inline
40
41 M: crc32 checksum-lines
42     init-crc32
43     [ [ (crc32) ] each CHAR: \n (crc32) ] each
44     finish-crc32 ; inline