factor/basis/classes/struct/bit-accessors/bit-accessors.factor

48 lines
1.6 KiB
Factor
Raw Normal View History

2009-10-08 00:51:18 -04:00
! Copyright (C) 2009 Daniel Ehrenberg
! See http://factorcode.org/license.txt for BSD license.
2011-10-14 13:23:52 -04:00
USING: alien.accessors fry kernel locals math math.bitwise
math.order sequences ;
2009-10-08 00:51:18 -04:00
IN: classes.struct.bit-accessors
! Bitfield accessors are little-endian on all platforms
! Why not? It's unspecified in C
2009-10-08 00:51:18 -04:00
: ones-between ( start end -- n )
2011-10-14 13:23:52 -04:00
[ on-bits ] bi@ swap unmask ;
2009-10-08 00:51:18 -04:00
:: manipulate-bits ( offset bits step-quot -- quot shift-amount offset' bits' )
offset 8 /mod :> ( i start-bit )
2009-10-08 00:51:18 -04:00
start-bit bits + 8 min :> end-bit
start-bit end-bit ones-between :> mask
end-bit start-bit - :> used-bits
i mask start-bit step-quot call( i mask start-bit -- quot )
2009-10-08 00:51:18 -04:00
used-bits
i 1 + 8 *
bits used-bits - ; inline
:: bit-manipulator ( offset bits
step-quot: ( i mask start-bit -- quot )
combine-quot: ( prev-quot shift-amount next-quot -- quot )
-- quot )
offset bits step-quot manipulate-bits
2012-06-18 17:32:39 -04:00
[ 2drop ] [
step-quot combine-quot bit-manipulator
combine-quot call( prev shift next -- quot )
2012-06-18 17:32:39 -04:00
] if-zero ; inline recursive
2009-10-08 00:51:18 -04:00
: bit-reader ( offset bits -- quot: ( alien -- n ) )
[ neg '[ _ alien-unsigned-1 _ bitand _ shift ] ]
[ swap '[ _ _ bi _ shift bitor ] ]
bit-manipulator ;
2009-10-08 14:10:51 -04:00
:: write-bits ( n alien i mask start-bit -- )
n start-bit shift mask bitand
alien i alien-unsigned-1 mask bitnot bitand
bitor alien i set-alien-unsigned-1 ; inline
2009-10-08 14:10:51 -04:00
: bit-writer ( offset bits -- quot: ( n alien -- ) )
[ '[ _ _ _ write-bits ] ]
[ '[ _ [ [ _ neg shift ] dip @ ] 2bi ] ]
bit-manipulator ;