1 ! Copyright (C) 2007, 2008 Slava Pestov, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.functions sequences
4 sequences.private words namespaces macros hints
5 combinators fry io.binary combinators.smart ;
9 : clear-bit ( x n -- y ) 2^ bitnot bitand ; inline
10 : set-bit ( x n -- y ) 2^ bitor ; inline
11 : bit-clear? ( x n -- ? ) 2^ bitand 0 = ; inline
12 : unmask ( x n -- ? ) bitnot bitand ; inline
13 : unmask? ( x n -- ? ) unmask 0 > ; inline
14 : mask ( x n -- ? ) bitand ; inline
15 : mask? ( x n -- ? ) mask 0 > ; inline
16 : wrap ( m n -- m' ) 1- bitand ; inline
17 : bits ( m n -- m' ) 2^ wrap ; inline
18 : mask-bit ( m n -- m' ) 2^ mask ; inline
19 : on-bits ( n -- m ) 2^ 1- ; inline
20 : toggle-bit ( m n -- m' ) 2^ bitxor ; inline
22 : shift-mod ( n s w -- n )
23 [ shift ] dip 2^ wrap ; inline
25 : bitroll ( x s w -- y )
27 [ shift-mod ] [ [ - ] keep shift-mod ] 3bi bitor ; inline
29 : bitroll-32 ( n s -- n' ) 32 bitroll ; inline
31 : bitroll-64 ( n s -- n' ) 64 bitroll ; inline
34 : w+ ( int int -- int ) + 32 bits ; inline
35 : w- ( int int -- int ) - 32 bits ; inline
36 : w* ( int int -- int ) * 32 bits ; inline
39 MACRO: flags ( values -- )
40 [ 0 ] [ [ dup word? [ execute ] when bitor ] curry compose ] reduce ;
45 GENERIC: (bitfield-quot) ( spec -- quot )
47 M: integer (bitfield-quot) ( spec -- quot )
48 [ swapd shift bitor ] curry ;
50 M: pair (bitfield-quot) ( spec -- quot )
51 first2 over word? [ [ swapd execute ] dip ] [ ] ?
52 [ shift bitor ] append 2curry ;
56 MACRO: bitfield ( bitspec -- )
57 [ 0 ] [ (bitfield-quot) compose ] reduce ;
68 0 swap [ [ 1+ ] when ] each-bit
69 ] B{ } map-as '[ HEX: ff bitand _ nth-unsafe ]
70 (( byte -- table )) define-declared
72 \ byte-bit-count make-inline
76 GENERIC: (bit-count) ( x -- n )
82 [ -8 shift byte-bit-count ]
83 [ -16 shift byte-bit-count ]
84 [ -24 shift byte-bit-count ]
90 [ byte-bit-count ] [ -8 shift (bit-count) ] bi +
95 : bit-count ( x -- n )
96 dup 0 < [ bitnot ] when (bit-count) ; inline
98 ! Signed byte array to integer conversion
99 : signed-le> ( bytes -- x )
100 [ le> ] [ length 8 * 1- on-bits ] bi
101 2dup > [ bitnot bitor ] [ drop ] if ;
103 : signed-be> ( bytes -- x )
104 <reversed> signed-le> ;