math.bits: Clarify docs. Don't support negative numbers for make-bits. Fixes #893.

db4
Doug Coleman 2014-06-06 14:24:39 -07:00
parent 9b91d78dc4
commit 6b9c7c6772
3 changed files with 12 additions and 9 deletions

View File

@ -22,12 +22,12 @@ HELP: <bits>
HELP: make-bits
{ $values { "number" integer } { "bits" bits } }
{ $description "Creates a " { $link bits } " object out of the given number, using its log base 2 as the length. This implies that the last element (unless the number is zero), corresponding to the most significant bit, will be " { $link t } "." }
{ $description "Creates a sequence of bits " { $link bits } " in ascending significance. Throws an error on negative numbers." }
{ $examples
{ $example "USING: math.bits prettyprint arrays ;" "0b1101 make-bits >array ." "{ t f t t }" }
{ $example "USING: math.bits prettyprint arrays ;" "-3 make-bits >array ." "{ t f }" }
{ $example "USING: math.bits prettyprint arrays ;" "64 make-bits >array ." "{ f f f f t }" }
} ;
HELP: unbits
HELP: bits>number
{ $values { "seq" sequence } { "number" integer } }
{ $description "Turns a sequence of booleans, of the same format made by the " { $link bits } " class, and calculates the number that it represents as little-endian." } ;
{ $description "Converts a sequence of booleans into a number." } ;

View File

@ -11,9 +11,8 @@ IN: math.bits.tests
[ 6 ] [ 0b111111 make-bits length ] unit-test
[ 0 ] [ 0 make-bits length ] unit-test
[ 2 ] [ 3 make-bits length ] unit-test
[ 2 ] [ -3 make-bits length ] unit-test
[ 1 ] [ 1 make-bits length ] unit-test
[ 1 ] [ -1 make-bits length ] unit-test
[ -3 make-bits length ] [ non-negative-integer-expected? ] must-fail-with
! Odd bug
[ t ] [
@ -30,5 +29,5 @@ IN: math.bits.tests
1067811677921310779 >bignum make-bits last
] unit-test
[ 6 ] [ 6 make-bits unbits ] unit-test
[ 6 ] [ 6 3 <bits> >array unbits ] unit-test
[ 6 ] [ 6 make-bits bits>number ] unit-test
[ 6 ] [ 6 3 <bits> >array bits>number ] unit-test

View File

@ -6,7 +6,11 @@ IN: math.bits
TUPLE: bits { number read-only } { length read-only } ;
C: <bits> bits
: check-negative-bits ( n -- n )
dup 0 < [ non-negative-integer-expected ] when ; inline
: make-bits ( number -- bits )
check-negative-bits
[ T{ bits f 0 0 } ] [ dup abs log2 1 + <bits> ] if-zero ; inline
M: bits length length>> ; inline
@ -15,5 +19,5 @@ M: bits nth-unsafe number>> swap bit? ; inline
INSTANCE: bits immutable-sequence
: unbits ( seq -- number )
: bits>number ( seq -- number )
<reversed> 0 [ [ 1 shift ] dip [ 1 + ] when ] reduce ;