]> gitweb.factorcode.org Git - factor.git/blob - extra/base62/base62.factor
factor: trim using lists
[factor.git] / extra / base62 / base62.factor
1 ! Copyright (C) 2020 John Benediktsson.
2 ! See http://factorcode.org/license.txt for BSD license.
3
4 USING: base64.private byte-arrays endian kernel kernel.private
5 literals math sequences ;
6
7 IN: base62
8
9 ERROR: malformed-base62 ;
10
11 <PRIVATE
12
13 <<
14 CONSTANT: alphabet $[
15     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
16     >byte-array
17 ]
18 >>
19
20 PRIVATE>
21
22 : ch>base62 ( ch -- ch )
23     alphabet nth ; inline
24
25 : base62>ch ( ch -- ch )
26     $[ alphabet alphabet-inverse ] nth
27     [ malformed-base62 ] unless* { fixnum } declare ; inline
28
29 :: >base62 ( seq -- base62 )
30     BV{ } clone :> accum
31     seq [ zero? not ] find [ drop seq length ] unless :> i
32     seq i tail-slice be>
33     [ 62 /mod ch>base62 accum push ] until-zero
34     i alphabet first '[ _ accum push ] times
35     accum reverse! B{ } like ;
36
37 :: base62> ( base62 -- seq )
38     BV{ } clone :> accum
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 ;