-
Notifications
You must be signed in to change notification settings - Fork 6
/
codecs.cljc
74 lines (61 loc) · 1.78 KB
/
codecs.cljc
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
(ns axel-f.buddy.codecs
#?(:cljs (:require [goog.crypt :as crypt])
:clj (:import org.apache.commons.codec.binary.Hex)))
(defn str->bytes
"Convert string to byte array."
([^String s]
(str->bytes s "UTF-8"))
([^String s, ^String encoding]
#?(:clj (.getBytes s encoding)
:cljs (if (= encoding "UTF-8")
(crypt/stringToUtf8ByteArray s)
(crypt/stringToByteArray s)))))
(defn bytes->str
"Convert byte array to String."
([^bytes data]
(bytes->str data "UTF-8"))
([^bytes data, ^String encoding]
#?(:clj (String. data encoding)
:cljs (if (= encoding "UTF-8")
(crypt/utf8ByteArrayToString data)
(crypt/byteArrayToString data)))))
(defn bytes->hex
"Convert a byte array to hex encoded string."
[^bytes data]
(#?(:clj Hex/encodeHexString :cljs crypt/byteArrayToHex) data))
(defn hex->bytes
"Convert hexadecimal encoded string to bytes array."
[^String data]
(#?(:clj (Hex/decodeHex (.toCharArray data))
:cljs (crypt/hexToByteArray data))))
(defprotocol IByteArray
"Facility for convert input parameters
to bytes array with default implementation
for string an bytes array itself."
(-to-bytes [this] "Represent this as byte array."))
(defprotocol IString
(-to-string [this]))
(defn to-bytes
"Encode as bytes."
[v]
(-to-bytes v))
(defn to-string [v]
(-to-string v))
(extend-protocol IByteArray
#?(:clj (Class/forName "[B")
:cljs array)
(-to-bytes [it] it)
nil
(-to-bytes [_]
#?(:clj (byte-array 0)
:cljs #js []))
#?(:clj String
:cljs string)
(-to-bytes [data] (str->bytes data)))
(extend-protocol IString
#?(:clj (Class/forName "[B")
:cljs array)
(-to-string [data] (bytes->str data))
#?(:clj String
:cljs string)
(-to-string [it] it))