1 ! Copyright (C) 2020 John Benediktsson.
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: base64.private byte-arrays endian kernel kernel.private
5 literals math sequences ;
9 ERROR: malformed-base62 ;
15 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
22 : ch>base62 ( ch -- ch )
25 : base62>ch ( ch -- ch )
26 $[ alphabet alphabet-inverse ] nth
27 [ malformed-base62 ] unless* { fixnum } declare ; inline
29 :: >base62 ( seq -- base62 )
31 seq [ zero? not ] find [ drop seq length ] unless :> i
33 [ 62 /mod ch>base62 accum push ] until-zero
34 i alphabet first '[ _ accum push ] times
35 accum reverse! B{ } like ;
37 :: base62> ( base62 -- seq )
39 base62 alphabet first '[ _ = not ] find
40 [ drop base62 length ] unless :> i
41 0 base62 [ [ 62 * ] dip base62>ch + ] i each-from
42 [ 256 /mod accum push ] until-zero
43 i [ 0 accum push ] times
44 accum reverse! B{ } like ;