-
Notifications
You must be signed in to change notification settings - Fork 25
/
nio_helpers.clj
64 lines (54 loc) · 2.08 KB
/
nio_helpers.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
56
57
58
59
60
61
62
63
(ns konserve.nio-helpers
(:import [java.nio.channels Channels ReadableByteChannel]
[java.io Reader File InputStream
ByteArrayInputStream FileInputStream StringReader]
(java.util Arrays)
(java.nio ByteBuffer)))
(def
^{:doc "Type object for a Java primitive byte array."
:private true}
byte-array-type (class (make-array Byte/TYPE 0)))
(def
^{:doc "Type object for a Java primitive char array."
:private true}
char-array-type (class (make-array Character/TYPE 0)))
(defprotocol BlobToChannel
(blob->channel [input buffer-size]))
(extend-protocol BlobToChannel
InputStream
(blob->channel [input _buffer-size]
[(Channels/newChannel input)
(fn [bis buffer] (.read ^ReadableByteChannel bis ^ByteBuffer buffer))])
File
(blob->channel [input _buffer-size]
[(Channels/newChannel (FileInputStream. ^String input))
(fn [bis buffer] (.read ^ReadableByteChannel bis buffer))])
String
(blob->channel [input _buffer-size]
[(Channels/newChannel (ByteArrayInputStream. (.getBytes input)))
(fn [bis buffer] (.read ^ReadableByteChannel bis buffer))])
Reader
(blob->channel [input buffer-size]
[input
(fn [bis nio-buffer]
(let [char-array (make-array Character/TYPE buffer-size)
size (.read ^StringReader bis ^chars char-array)]
(try
(when-not (= size -1)
(let [char-array-copy (Arrays/copyOf ^chars char-array size)]
(.put ^ByteBuffer nio-buffer (.getBytes (String. char-array-copy)))))
size
(catch Exception e
(throw e)))))]))
(extend
byte-array-type
BlobToChannel
{:blob->channel (fn [input _]
[(Channels/newChannel (ByteArrayInputStream. input))
(fn [bis buffer] (.read ^ReadableByteChannel bis buffer))])})
(extend
char-array-type
BlobToChannel
{:blob->channel (fn [input _]
[(Channels/newChannel (ByteArrayInputStream. (.getBytes (String. ^chars input))))
(fn [bis buffer] (.read ^ReadableByteChannel bis buffer))])})