]> gitweb.factorcode.org Git - factor.git/commitdiff
base62: adding a base63 encoder/decoder.
authorJohn Benediktsson <mrjbq7@gmail.com>
Sun, 13 Dec 2020 18:22:58 +0000 (10:22 -0800)
committerJohn Benediktsson <mrjbq7@gmail.com>
Sun, 13 Dec 2020 18:22:58 +0000 (10:22 -0800)
extra/base62/authors.txt [new file with mode: 0644]
extra/base62/base62-tests.factor [new file with mode: 0644]
extra/base62/base62.factor [new file with mode: 0644]
extra/base62/summary.txt [new file with mode: 0644]

diff --git a/extra/base62/authors.txt b/extra/base62/authors.txt
new file mode 100644 (file)
index 0000000..e091bb8
--- /dev/null
@@ -0,0 +1 @@
+John Benediktsson
diff --git a/extra/base62/base62-tests.factor b/extra/base62/base62-tests.factor
new file mode 100644 (file)
index 0000000..24c334d
--- /dev/null
@@ -0,0 +1,13 @@
+USING: base62 math.parser strings tools.test ;
+
+{ "" } [ "" >base62 >string ] unit-test
+{ "" } [ "" base62> >string ] unit-test
+
+{ "0" } [ B{ 0 } >base62 >string ] unit-test
+{ B{ 0 } } [ "0" base62> ] unit-test
+
+{ "00" } [ B{ 0 0 } >base62 >string ] unit-test
+{ B{ 0 0 } } [ "00" base62> ] unit-test
+
+{ "Q0DRQksv" } [ "SIMPLE" >base62 >string ] unit-test
+{ "SIMPLE" } [ "Q0DRQksv" base62> >string ] unit-test
diff --git a/extra/base62/base62.factor b/extra/base62/base62.factor
new file mode 100644 (file)
index 0000000..40c29ca
--- /dev/null
@@ -0,0 +1,44 @@
+! Copyright (C) 2020 John Benediktsson.
+! See http://factorcode.org/license.txt for BSD license.
+
+USING: base64.private byte-arrays checksums checksums.sha
+io.binary kernel kernel.private literals math sequences ;
+
+IN: base62
+
+ERROR: malformed-base62 ;
+
+<PRIVATE
+
+<<
+CONSTANT: alphabet $[
+    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+    >byte-array
+]
+>>
+
+PRIVATE>
+
+: ch>base62 ( ch -- ch )
+    alphabet nth ; inline
+
+: base62>ch ( ch -- ch )
+    $[ alphabet alphabet-inverse ] nth
+    [ malformed-base62 ] unless* { fixnum } declare ; inline
+
+:: >base62 ( seq -- base62 )
+    BV{ } clone :> accum
+    seq [ zero? not ] find [ drop seq length ] unless :> i
+    seq i tail-slice be>
+    [ 62 /mod ch>base62 accum push ] until-zero
+    i alphabet first '[ _ accum push ] times
+    accum reverse! B{ } like ;
+
+:: base62> ( base62 -- seq )
+    BV{ } clone :> accum
+    base62 alphabet first '[ _ = not ] find
+    [ drop base62 length ] unless :> i
+    0 base62 [ [ 62 * ] dip base62>ch + ] i each-from
+    [ 256 /mod accum push ] until-zero
+    i [ 0 accum push ] times
+    accum reverse! B{ } like ;
diff --git a/extra/base62/summary.txt b/extra/base62/summary.txt
new file mode 100644 (file)
index 0000000..25ebfa4
--- /dev/null
@@ -0,0 +1 @@
+Base62 encoding/decoding