factor/core/checksums/crc32/crc32.factor

42 lines
956 B
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2006 Doug Coleman
! See http://factorcode.org/license.txt for BSD license.
USING: kernel math sequences sequences.private namespaces
words io io.binary io.files io.streams.string quotations
2008-04-30 17:11:55 -04:00
definitions checksums ;
IN: checksums.crc32
2007-09-20 18:09:08 -04:00
: crc32-polynomial HEX: edb88320 ; inline
: crc32-table V{ } ; inline
2007-09-20 18:09:08 -04:00
256 [
8 [
[ 2/ ] [ even? ] bi [ crc32-polynomial bitxor ] unless
2007-09-20 18:09:08 -04:00
] times >bignum
] map 0 crc32-table copy
2007-09-20 18:09:08 -04:00
: (crc32) ( crc ch -- crc )
>bignum dupd bitxor
mask-byte crc32-table nth-unsafe >bignum
swap -8 shift bitxor ; inline
2008-04-30 17:11:55 -04:00
SINGLETON: crc32
2007-09-20 18:09:08 -04:00
2008-04-30 17:11:55 -04:00
INSTANCE: crc32 checksum
: init-crc32 ( input checksum -- x y input )
drop [ HEX: ffffffff dup ] dip ; inline
2008-04-30 17:11:55 -04:00
: finish-crc32 ( x y -- bytes )
bitxor 4 >be ; inline
2008-04-30 17:11:55 -04:00
M: crc32 checksum-bytes
init-crc32
[ (crc32) ] each
finish-crc32 ;
M: crc32 checksum-lines
init-crc32
[ [ (crc32) ] each CHAR: \n (crc32) ] each
finish-crc32 ;