-
Notifications
You must be signed in to change notification settings - Fork 0
/
base45.clj
55 lines (51 loc) · 1.91 KB
/
base45.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
; https://datatracker.ietf.org/doc/draft-faltstrom-base45/
(ns org.vuxu.base45)
(def ^:const alphabet
"The Base45 Alphabet"
(vec (concat
(map char (range (int \0) (inc (int \9))))
(map char (range (int \A) (inc (int \Z))))
'(\space \$ \% \* \+ \- \. \/ \:))))
(def ^:const reverse-alphabet
"Reverse lookup for the Base45 Alphabet"
(->> alphabet
(map-indexed #(vector %2 %1))
(into {})))
(defn encode [string]
(transduce (comp
(map (fn [b] ; make unsigned bytes
(cond-> b
(neg? b) (+ 256))))
(partition-all 2)
(mapcat (fn [[a b]]
(if b
(let [n (+ (* 256 a) b)
e (quot n (* 45 45))
n (mod n (* 45 45))
d (quot n 45)
c (mod n 45)]
[c d e])
[(mod a 45) (quot a 45)])))
(map alphabet))
str
(.getBytes string "UTF8")))
(defn decode [string]
(when (-> string count (mod 3) (= 1))
(throw (IllegalArgumentException. "invalid length, is 1 mod 3")))
(->> string
(into []
(comp
(map reverse-alphabet)
(map #(or %1
(throw (IllegalArgumentException. "invalid character"))))
(partition-all 3)
(mapcat (fn [[a b c]]
(if c
(let [n (+ a (* 45 b) (* 45 45 c))]
(when (> n 65535)
(throw (IllegalArgumentException.
(str "triplet too high: " n))))
((juxt quot mod) n 256))
[(+ a (* 45 b))])))))
byte-array
(#(String. % "UTF8"))))