! Copyright (C) 2009 Doug Coleman. ! See http://factorcode.org/license.txt for BSD license. USING: accessors alien.accessors assocs byte-arrays byte-vectors combinators combinators.short-circuit constructors destructors fry io io.binary io.encodings.binary io.streams.byte-array kernel locals macros math math.bitwise math.ranges sequences sequences.private vectors ; IN: bitstreams-bug TUPLE: widthed { bits integer read-only } { #bits integer read-only } ; : ( bits #bits -- widthed ) widthed boa ; inline : zero-widthed ( -- widthed ) 0 0 ; inline : zero-widthed? ( widthed -- ? ) zero-widthed = ; inline ERROR: not-enough-bits widthed n ; : widthed-bits ( widthed n -- bits ) dup 0 < [ not-enough-bits ] when 2dup [ #bits>> ] dip < [ not-enough-bits ] when [ [ bits>> ] [ #bits>> ] bi ] dip [ - neg shift ] keep ; inline : split-widthed ( widthed n -- widthed1 widthed2 ) 2dup [ #bits>> ] dip < [ drop zero-widthed ] [ [ widthed-bits ] [ [ [ bits>> ] [ #bits>> ] bi ] dip - [ bits ] keep ] 2bi ] if ; inline : widthed>bytes ( widthed -- bytes widthed ) [ 8 split-widthed dup zero-widthed? not ] [ swap bits>> ] B{ } produce-as nip swap ; inline