base32-crockford: separate Douglas Crockford version of Base 32.

clean-macosx-x86-32
John Benediktsson 2019-04-05 12:10:52 -07:00
parent 77c5a4b7ff
commit 83d6c5b382
4 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1 @@
John Benediktsson

View File

@ -0,0 +1,20 @@
! Copyright (C) 2019 John Benediktsson
! See http://factorcode.org/license.txt for BSD license
USING: base32-crockford tools.test ;
{ "16J" } [ 1234 base32-crockford> ] unit-test
{ "16JD" } [ 1234 base32-crockford-checksum> ] unit-test
{ "0" } [ 0 base32-crockford> ] unit-test
{ "00" } [ 0 base32-crockford-checksum> ] unit-test
[ -1 base32-crockford> ] must-fail
[ 1.0 base32-crockford> ] must-fail
{ 1234 } [ "16J" >base32-crockford ] unit-test
{ 1234 } [ "I6J" >base32-crockford ] unit-test
{ 1234 } [ "i6J" >base32-crockford ] unit-test
{ 1234 } [ "16JD" >base32-crockford-checksum ] unit-test
{ 1234 } [ "I6JD" >base32-crockford-checksum ] unit-test
{ 1234 } [ "i6JD" >base32-crockford-checksum ] unit-test
{ 0 } [ "0" >base32-crockford ] unit-test
{ 0 } [ "00" >base32-crockford-checksum ] unit-test

View File

@ -0,0 +1,43 @@
! Copyright (C) 2019 John Benediktsson
! See http://factorcode.org/license.txt for BSD license
USING: ascii assocs byte-arrays kernel literals math sequences ;
IN: base32-crockford
<PRIVATE
<<
CONSTANT: ALPHABET $[ "0123456789ABCDEFGHJKMNPQRSTVWXYZ" >byte-array ]
>>
CONSTANT: INVERSE $[ 256 [ ALPHABET index 0xff or ] B{ } map-integers ]
CONSTANT: CHECKSUM $[ ALPHABET "*~$=U" append ]
: normalize-base32 ( seq -- seq' )
CHAR: - swap remove >upper H{
{ CHAR: I CHAR: 1 }
{ CHAR: L CHAR: 1 }
{ CHAR: O CHAR: 0 }
} substitute ;
: parse-base32 ( seq -- base32 )
0 swap [ [ 32 * ] [ INVERSE nth + ] bi* ] each ;
PRIVATE>
: >base32-crockford ( seq -- base32 )
normalize-base32 parse-base32 ;
: base32-crockford> ( base32 -- seq )
dup 0 < [ non-negative-integer-expected ] when
[ dup 0 > ] [ 32 /mod ALPHABET nth ] "" produce-as nip
[ "0" ] when-empty reverse! ;
: >base32-crockford-checksum ( seq -- base32 )
normalize-base32 unclip-last [ parse-base32 ] dip
CHECKSUM index over 37 mod assert= ;
: base32-crockford-checksum> ( base32 -- seq )
[ base32-crockford> ] keep 37 mod CHECKSUM nth suffix ;

View File

@ -0,0 +1 @@
Douglas Crockford's Base 32 encoding/decoding