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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
 * BSD 3-Clause License
 *
 * Copyright (c) 2019-2020, InterlockLedger Network
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
//=============================================================================
//! This module implements a simple data serializer/deserialzer that can be
//! used to read/write data serializations in memory. Most of the functions
//! here where designed to use pre-allocated memory segments and/or vectors
//! in place. As such, this module is not recommended for complex
//! serializations or large values.
//!
//! If you want to use the operation `?` to remap the errors form this just
//! implement the trait [`std::convert::From`] to convert [`ErrorKind`] into
//! your own error type.
#[cfg(test)]
mod tests;

/// Errors generated by this
#[derive(Debug)]
pub enum ErrorKind {
    UnableToRead,
    UnableToWrite,
}

pub type Result<T> = std::result::Result<T, ErrorKind>;

//=============================================================================
// SimpleDataSerializer
//-----------------------------------------------------------------------------
/// This trait implements a simple serializer for basic data types.
/// It follows the format used by Java's `java.io.DataOutputStream` and write
/// all values using the big endian format.
///
/// This trait also allows the definition of a custom Result type thar will
/// allow its methods to be used with the operatior `?`.
pub trait SimpleDataSerializer {
    /// Writes the byte slice.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write(&mut self, v: &[u8]) -> Result<()>;

    /// Writes an u8 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_u8(&mut self, v: u8) -> Result<()>;

    /// Writes an u16 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_u16(&mut self, v: u16) -> Result<()> {
        self.write(&v.to_be_bytes())
    }

    /// Writes an u32 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_u32(&mut self, v: u32) -> Result<()> {
        self.write(&v.to_be_bytes())
    }

    /// Writes an u64 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_u64(&mut self, v: u64) -> Result<()> {
        self.write(&v.to_be_bytes())
    }

    /// Writes an i8 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_i8(&mut self, v: i8) -> Result<()> {
        self.write_u8(v as u8)
    }

    /// Writes an i16 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_i16(&mut self, v: i16) -> Result<()> {
        self.write_u16(v as u16)
    }

    /// Writes an i32 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;

    fn write_i32(&mut self, v: i32) -> Result<()> {
        self.write_u32(v as u32)
    }

    /// Writes an i64 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_i64(&mut self, v: i64) -> Result<()> {
        self.write_u64(v as u64)
    }

    /// Writes a f32 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_f32(&mut self, v: f32) -> Result<()> {
        self.write(&v.to_be_bytes())
    }

    /// Writes a f64 value.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_f64(&mut self, v: f64) -> Result<()> {
        self.write(&v.to_be_bytes())
    }

    /// Writes a byte array. The size of the byte array is encoded
    /// as an u16 value followed by the bytes of the array.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn write_byte_array(&mut self, v: &[u8]) -> Result<()> {
        self.write_u16(v.len() as u16)?;
        self.write(v)
    }
}

//=============================================================================
// SimpleDataDeserializer
//-----------------------------------------------------------------------------
macro_rules! simpledatadeserializer_read_impl {
    ($type: ty, $func_name:ident, $doc: expr) => {
        #[doc = $doc]
        fn $func_name(&mut self) -> Result<$type> {
            const DATA_SIZE: usize = std::mem::size_of::<$type>();
            self.read(DATA_SIZE)?;
            let mut tmp: [u8; DATA_SIZE] = [0; DATA_SIZE];
            tmp.copy_from_slice(self.data());
            Ok(<$type>::from_be_bytes(tmp))
        }
    };
}

/// This trait implements a simple deserializer for basic data types.
/// It follows the format used by Java's `java.io.DataOutputStream` so it
/// reads the values using the big endian format.
///
/// This trait also allows the definition of a custom Result type thar will
/// allow its methods to be used with the operatior `?`.
pub trait SimpleDataDeserializer {
    /// The slice with the last data read.
    fn data(&self) -> &[u8];

    /// Reads the specified umber of bytes. The data read will available
    /// by [`Self::data()`].
    ///
    /// Arguments:
    /// - `size`: Number of bytes to read;
    fn read(&mut self, size: usize) -> Result<()>;

    /// Reads an u8 value.
    fn read_u8(&mut self) -> Result<u8> {
        self.read(1)?;
        Ok(self.data()[0])
    }

    /// Reads an i8 value.
    fn read_i8(&mut self) -> Result<i8> {
        Ok(self.read_u8()? as i8)
    }

    simpledatadeserializer_read_impl!(u16, read_u16, "Reads an u16 value.");
    simpledatadeserializer_read_impl!(u32, read_u32, "Reads an u32 value.");
    simpledatadeserializer_read_impl!(u64, read_u64, "Reads an u16 value.");
    simpledatadeserializer_read_impl!(i16, read_i16, "Reads an i16 value.");
    simpledatadeserializer_read_impl!(i32, read_i32, "Reads an i32 value.");
    simpledatadeserializer_read_impl!(i64, read_i64, "Reads an i64 value.");
    simpledatadeserializer_read_impl!(f32, read_f32, "Reads an f32 value.");
    simpledatadeserializer_read_impl!(f64, read_f64, "Reads an f64 value.");

    /// Writes a byte array. The size of the byte array is encoded
    /// as an u16 value followed by the bytes of the array.
    ///
    /// Arguments:
    /// - `v`: The value to write;
    fn read_byte_array(&mut self) -> Result<()> {
        let size = self.read_u16()? as usize;
        self.read(size)
    }
}

impl SimpleDataSerializer for Vec<u8> {
    fn write(&mut self, v: &[u8]) -> Result<()> {
        self.extend_from_slice(v);
        Ok(())
    }

    fn write_u8(&mut self, v: u8) -> Result<()> {
        self.push(v);
        Ok(())
    }
}

//=============================================================================
// SimpleSliceSerializer
//-----------------------------------------------------------------------------
/// This struct implements a simple serializer that writes data into a borrowed
/// byte slice.
pub struct SimpleSliceSerializer<'a> {
    slice: &'a mut [u8],
    offset: usize,
}

impl<'a> SimpleSliceSerializer<'a> {
    /// Creates a new instance with a given initial capacity.
    pub fn new(slice: &'a mut [u8]) -> Self {
        Self { slice, offset: 0 }
    }

    /// Returns the current offset.
    pub fn offset(&self) -> usize {
        self.offset
    }

    /// Returns the number of available bytes.
    pub fn available(&self) -> usize {
        self.slice.len() - self.offset
    }

    fn can_write(&self, size: usize) -> Result<()> {
        if size <= self.available() {
            Ok(())
        } else {
            Err(ErrorKind::UnableToWrite)
        }
    }
}

impl<'a> SimpleDataSerializer for SimpleSliceSerializer<'a> {
    fn write(&mut self, v: &[u8]) -> Result<()> {
        self.can_write(v.len())?;
        self.slice[self.offset..self.offset + v.len()].copy_from_slice(v);
        self.offset += v.len();
        Ok(())
    }

    fn write_u8(&mut self, v: u8) -> Result<()> {
        self.can_write(1)?;
        self.slice[self.offset] = v;
        self.offset += 1;
        Ok(())
    }
}

//=============================================================================
// SimpleReader
//-----------------------------------------------------------------------------
/// This struct implements a simple data deserializer. It is the counterpart of
/// the [`SimpleDataSerializer`] trait.
///
/// The template parameter E is the type used to define the type of the error
/// that will compose the results. The actual value of E is defined by the
/// constructor.
pub struct SimpleSliceDeserializer<'a> {
    data: &'a [u8],
    offset: usize,
    data_offset: usize,
}

impl<'a> SimpleSliceDeserializer<'a> {
    /// Creates a new instance that reads data from the slice and returns the
    /// specified value on error.
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            offset: 0,
            data_offset: 0,
        }
    }

    /// Returns the current offset.
    pub fn offset(&self) -> usize {
        self.offset
    }

    /// Return the number of bytes availble.
    pub fn avaliable(&self) -> usize {
        self.data.len() - self.offset
    }

    /// Returns true if there is no more bytes to read.
    pub fn is_empty(&self) -> bool {
        self.avaliable() == 0
    }

    fn can_read(&self, size: usize) -> Result<()> {
        if size <= self.avaliable() {
            Ok(())
        } else {
            Err(ErrorKind::UnableToRead)
        }
    }
}

impl<'a> SimpleDataDeserializer for SimpleSliceDeserializer<'a> {
    fn data(&self) -> &[u8] {
        &self.data[self.data_offset..self.offset]
    }

    fn read(&mut self, size: usize) -> Result<()> {
        self.can_read(size)?;
        self.data_offset = self.offset;
        self.offset += size;
        Ok(())
    }
}