This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
bin.clj
85 lines (59 loc) · 1.79 KB
/
bin.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
(ns multistream.codec.bin
"Example binary codec which simply encodes and decodes raw byte arrays.
This codec is probably not going to be very useful in practice; if you're
working with raw bytes, you should just work with `InputStream` and
`OutputStream` directly."
(:require
[multistream.codec :as codec :refer [defcodec defdecoder defencoder]])
(:import
(java.io
InputStream
OutputStream)))
;; ## Encoding Protocol
(defprotocol BinaryData
"Protocol for values which can be encoded directly as a binary sequence."
(write-bytes!
[data output]
"Writes the binary data to the given output stream. Returns the number of
bytes written."))
(extend-protocol BinaryData
(class (byte-array 0))
(write-bytes!
[array ^OutputStream output]
(.write output ^bytes array)
(count array)))
;; ## Binary Codec
(defencoder BinaryEncoderStream
[^OutputStream output]
(write!
[this value]
(write-bytes! value output)))
(defdecoder BinaryDecoderStream
[^InputStream input ^bytes buffer]
(read!
[this]
(let [len (.read input buffer)]
(cond
(neg? len)
(codec/eof-error!)
(pos? len)
(let [data (byte-array len)]
(System/arraycopy buffer 0 data 0 len)
data)
:else nil))))
(defcodec BinaryCodec
[header buffer-size]
(encode-byte-stream
[this _ output-stream]
(->BinaryEncoderStream output-stream))
(decode-byte-stream
[this _ input-stream]
(->BinaryDecoderStream input-stream (byte-array buffer-size))))
(defn bin-codec
"Creates a new binary codec. A number may be given to specify the buffer size
in bytes for decoding operations."
[& {:as opts}]
(map->BinaryCodec
(merge {:buffer-size 1024}
opts
{:header "/bin/"})))