-
Notifications
You must be signed in to change notification settings - Fork 11
/
coerce.clj
40 lines (31 loc) · 848 Bytes
/
coerce.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
(ns net.ty.coerce
"Our beloved JVM does not implement unsigned types.
Some protocols rely heavily on unsigned types,
and we thus need to have ways of parsing those")
(def uint16-max "short maximum value" 0x10000)
(def uint32-max "integer maximum value" 0x100000000)
(defn ubyte->byte
[i]
(-> i short Short. .byteValue))
(defn ushort->short
[i]
(-> i int Integer. .shortValue short))
(defn uint->int
[i]
(-> i long Long. .intValue int))
(defn ulong->long
[i]
(-> i bigint .longValue long))
(defn byte->ubyte
[i]
(-> i short Short. (bit-and 0xff)))
(defn short->ushort
[i]
(-> i int Integer. (bit-and 0xffff)))
(defn int->uint
[i]
(-> i long Long. (bit-and 0xffffffff)))
(defn long->ulong
[i]
(let [buf (doto (java.nio.ByteBuffer/allocate 8) (.putLong i))]
(long (BigInteger. 1 (.array buf)))))