-
Notifications
You must be signed in to change notification settings - Fork 0
/
body.clj
53 lines (47 loc) · 1.33 KB
/
body.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
(ns iny.http.body
(:import [java.nio.charset
Charset]
[io.netty.channel
ChannelHandlerContext]
[io.netty.buffer
ByteBuf
Unpooled]
[io.netty.util
ReferenceCounted
ReferenceCountUtil]))
(defprotocol WritableBody
(^io.netty.buffer.ByteBuf ->buffer [_] [_ _]))
(defn release
[^ReferenceCounted buffer]
(when (and (instance? ReferenceCounted buffer) (pos? (.refCnt buffer)))
(ReferenceCountUtil/release buffer)))
(let [charset (Charset/forName "UTF-8")]
(extend-protocol WritableBody
(Class/forName "[B")
(->buffer
([b]
(Unpooled/copiedBuffer ^bytes b))
([b ^ChannelHandlerContext ctx]
(doto (-> ctx (.alloc) (.ioBuffer (alength ^bytes b)))
(.writeBytes ^bytes b))))
nil
(->buffer
([_]
Unpooled/EMPTY_BUFFER)
([_ _]
Unpooled/EMPTY_BUFFER))
String
(->buffer
([str]
(Unpooled/copiedBuffer ^String str charset))
([str ctx]
(->buffer ^bytes (.getBytes str) ctx)))
ByteBuf
(->buffer
([buf]
buf)
([^ByteBuf buf ^ChannelHandlerContext ctx]
(if (= (.alloc buf) (.alloc ctx))
buf
(doto (-> ctx (.alloc) (.ioBuffer (.readableBytes buf)))
(.writeBytes buf)))))))