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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//! Tooling for packing and unpacking from streams
//!
//! This will allow us to expose some standard way of serializing
//! data.

use crate::deser::{ReadError, WriteError};
use std::num::{NonZeroU32, NonZeroU64};

/// The structure to support (de)serialization of binary data format used by
/// jormungandr.
///
/// ## Reading data
///
/// The structure is generally intended to read from any implementor of
/// `std::io::Read`. On top of that it supports specialized methods for `&[u8]`
/// (which is also `std::io::Read`) to facilitate zero-copy operations.
///
/// ## Writing data
///
/// Data can be written into any `std::io::Write` implementor.
pub struct Codec<I> {
    inner: I,
}

impl<I> Codec<I> {
    pub fn new(inner: I) -> Self {
        Codec { inner }
    }

    pub fn into_inner(self) -> I {
        self.inner
    }
}

impl Codec<()> {
    pub const fn u8_size() -> usize {
        std::mem::size_of::<u8>()
    }

    pub const fn u16_size() -> usize {
        std::mem::size_of::<u16>()
    }

    pub const fn u32_size() -> usize {
        std::mem::size_of::<u32>()
    }

    pub const fn u64_size() -> usize {
        std::mem::size_of::<u64>()
    }

    pub const fn u128_size() -> usize {
        std::mem::size_of::<u128>()
    }

    pub const fn i8_size() -> usize {
        std::mem::size_of::<i8>()
    }

    pub const fn i16_size() -> usize {
        std::mem::size_of::<i16>()
    }

    pub const fn i32_size() -> usize {
        std::mem::size_of::<i32>()
    }

    pub const fn i64_size() -> usize {
        std::mem::size_of::<i64>()
    }

    pub const fn i128_size() -> usize {
        std::mem::size_of::<i128>()
    }
}

impl Codec<&[u8]> {
    #[inline]
    pub fn get_slice(&mut self, n: usize) -> Result<&[u8], ReadError> {
        if self.inner.as_ref().len() < n {
            return Err(ReadError::NotEnoughBytes(self.inner.as_ref().len(), n));
        }
        let res = &self.inner[..n];
        self.inner = &self.inner[n..];
        Ok(res)
    }

    #[inline]
    pub fn skip_bytes(&mut self, pos: usize) {
        self.inner = &self.inner[pos..];
    }

    #[inline]
    pub fn bytes_left(&self) -> usize {
        self.inner.len()
    }

    #[inline]
    pub fn has_bytes_left(&self) -> bool {
        self.bytes_left() != 0
    }
}

impl<R: std::io::Read> Codec<R> {
    #[inline]
    pub fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, ReadError> {
        let res = self.inner.read_to_end(buf)?;
        Ok(res)
    }

    #[inline]
    pub fn get_u8(&mut self) -> Result<u8, ReadError> {
        let mut buf = [0u8; 1];
        self.inner.read_exact(&mut buf)?;
        Ok(buf[0])
    }

    #[inline]
    pub fn get_be_u16(&mut self) -> Result<u16, ReadError> {
        let mut buf = [0u8; 2];
        self.inner.read_exact(&mut buf)?;
        Ok(u16::from_be_bytes(buf))
    }

    #[inline]
    pub fn get_le_u16(&mut self) -> Result<u16, ReadError> {
        let mut buf = [0u8; 2];
        self.inner.read_exact(&mut buf)?;
        Ok(u16::from_le_bytes(buf))
    }

    #[inline]
    pub fn get_be_u32(&mut self) -> Result<u32, ReadError> {
        let mut buf = [0u8; 4];
        self.inner.read_exact(&mut buf)?;
        Ok(u32::from_be_bytes(buf))
    }

    #[inline]
    pub fn get_le_u32(&mut self) -> Result<u32, ReadError> {
        let mut buf = [0u8; 4];
        self.inner.read_exact(&mut buf)?;
        Ok(u32::from_le_bytes(buf))
    }

    #[inline]
    pub fn get_be_u64(&mut self) -> Result<u64, ReadError> {
        let mut buf = [0u8; 8];
        self.inner.read_exact(&mut buf)?;
        Ok(u64::from_be_bytes(buf))
    }

    #[inline]
    pub fn get_le_u64(&mut self) -> Result<u64, ReadError> {
        let mut buf = [0u8; 8];
        self.inner.read_exact(&mut buf)?;
        Ok(u64::from_le_bytes(buf))
    }

    #[inline]
    pub fn get_be_u128(&mut self) -> Result<u128, ReadError> {
        let mut buf = [0u8; 16];
        self.inner.read_exact(&mut buf)?;
        Ok(u128::from_be_bytes(buf))
    }

    #[inline]
    pub fn get_le_u128(&mut self) -> Result<u128, ReadError> {
        let mut buf = [0u8; 16];
        self.inner.read_exact(&mut buf)?;
        Ok(u128::from_le_bytes(buf))
    }

    #[inline]
    pub fn get_nz_u32(&mut self) -> Result<NonZeroU32, ReadError> {
        let val = self.get_be_u32()?;
        NonZeroU32::new(val)
            .ok_or_else(|| ReadError::StructureInvalid("received zero u32".to_string()))
    }

    #[inline]
    pub fn get_nz_u64(&mut self) -> Result<NonZeroU64, ReadError> {
        let val = self.get_be_u64()?;
        NonZeroU64::new(val)
            .ok_or_else(|| ReadError::StructureInvalid("received zero u64".to_string()))
    }

    #[inline]
    pub fn get_bytes(&mut self, n: usize) -> Result<Vec<u8>, ReadError> {
        let mut buf = vec![0u8; n];
        self.inner.read_exact(&mut buf)?;
        Ok(buf)
    }

    #[inline]
    pub fn copy_to_slice(&mut self, slice: &mut [u8]) -> Result<(), ReadError> {
        self.inner.read_exact(slice)?;
        Ok(())
    }
}

impl<W: std::io::Write> Codec<W> {
    #[inline]
    pub fn put_u8(&mut self, v: u8) -> Result<(), WriteError> {
        self.inner.write_all(&[v])?;
        Ok(())
    }

    #[inline]
    pub fn put_be_u16(&mut self, v: u16) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_le_u16(&mut self, v: u16) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_be_u32(&mut self, v: u32) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_le_u32(&mut self, v: u32) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_be_u64(&mut self, v: u64) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_le_u64(&mut self, v: u64) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_be_u128(&mut self, v: u128) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_le_u128(&mut self, v: u128) -> Result<(), WriteError> {
        self.inner.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    #[inline]
    pub fn put_bytes(&mut self, v: &[u8]) -> Result<(), WriteError> {
        self.inner.write_all(v)?;
        Ok(())
    }
}

impl<T> Codec<std::io::Cursor<T>> {
    #[inline]
    pub fn position(&mut self) -> usize {
        self.inner.position() as usize
    }

    #[inline]
    pub fn set_position(&mut self, pos: usize) {
        self.inner.set_position(pos as u64)
    }
}