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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/*
 * BSD 3-Clause License
 *
 * Copyright (c) 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 contains the implementation of [`Reader`] and [`Writer`] for
//! arrays, slices and vectors.
use super::*;
use std::cmp::min;

#[cfg(test)]
mod tests;

//=============================================================================
// MemoryReader
//-----------------------------------------------------------------------------
/// This trait provides an extension to [`Reader`] for memory backed readers.
///
/// New since 1.4.0.
pub trait MemoryReader: Reader {
    /// Returns the current size of the data.
    fn len(&self) -> usize;

    /// Returns true if this reader is empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the current offset of the data.
    fn offset(&self) -> usize;

    /// Sets the current offset. If offset is larger than the length, it will
    /// set the offset to to the length of the data.
    fn set_offset(&mut self, offset: usize);

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

    /// This method verifies if a certain amount of bytes can be read/extracted.
    ///
    /// Arguments:
    /// - `count`: Number of bytes to read;
    ///
    /// Retunrs:
    /// - `Ok(())`: If it is possible to read the specified amout of bytes;
    /// - `Err(ErrorKind::UnableToReadData)`: If there is not enough bytes to read;
    /// - `Err(ErrorKind::EndOfData)`: If there is no more data to read;
    fn assert_can_read(&self, count: usize) -> Result<()> {
        if count == 0 {
            Ok(())
        } else {
            match self.available() {
                0 => Err(ErrorKind::EndOfData),
                x if x < count => Err(ErrorKind::UnableToReadData),
                _ => Ok(()),
            }
        }
    }
}

//=============================================================================
// ByteArrayReader
//-----------------------------------------------------------------------------
/// [`ByteArrayReader`] implements a [`Reader`] that
/// can extract bytes from a borrowed slice of bytes.
pub struct ByteArrayReader<'a> {
    array: &'a [u8],
    offset: usize,
}

impl<'a> ByteArrayReader<'a> {
    pub fn new(buff: &'a [u8]) -> ByteArrayReader<'a> {
        ByteArrayReader {
            array: buff,
            offset: 0,
        }
    }

    /// Returns a reference to the inner data as a
    /// slice.
    pub fn as_slice(&self) -> &[u8] {
        self.array
    }

    /// Verifies if the specified number of bytes can be
    /// read from this struct.
    ///
    /// Returns:
    /// - `Result(())`: If it is possible to read the specified
    ///   number of bytes;
    /// - `Result(ErrorKind::UnableToReadData)`: If it is not
    ///   possible to read the specified number of bytes;
    pub fn can_read(&self, count: usize) -> Result<()> {
        self.assert_can_read(count)
    }
}

impl<'a> MemoryReader for ByteArrayReader<'a> {
    fn len(&self) -> usize {
        self.array.len()
    }

    fn offset(&self) -> usize {
        self.offset
    }

    fn set_offset(&mut self, offset: usize) {
        self.offset = std::cmp::min(offset, self.array.len());
    }
}

impl<'a> Reader for ByteArrayReader<'a> {
    fn read(&mut self) -> Result<u8> {
        self.can_read(1)?;
        let r = self.array[self.offset];
        self.offset += 1;
        Ok(r)
    }

    fn read_all(&mut self, buff: &mut [u8]) -> Result<()> {
        self.can_read(buff.len())?;
        buff.copy_from_slice(&self.array[self.offset..(self.offset + buff.len())]);
        self.offset += buff.len();
        Ok(())
    }

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

//=============================================================================
// VecReader
//-----------------------------------------------------------------------------
/// [`VecReader`] implements a [`Writer`] that uses a Vec<u8> a its backend.
///
/// It differs from [`ByteArrayReader`] by the fact that it copies the data
/// into a vector owned by it instead of borrowing the data from a byte array
/// slice.
pub struct VecReader {
    vector: Vec<u8>,
    offset: usize,
}

impl VecReader {
    /// Creates a new `VecReader` with the data copied
    /// from the specified slice.
    pub fn new(value: &[u8]) -> VecReader {
        let mut v: Vec<u8> = Vec::with_capacity(value.len());
        v.extend_from_slice(value);
        VecReader {
            vector: v,
            offset: 0,
        }
    }

    /// Verifies if the specified number of bytes can be
    /// read from this struct.
    ///
    /// Returns:
    /// - `Result(())`: If it is possible to read the specified
    ///   number of bytes;
    /// - `Result(ErrorKind::UnableToReadData)`: If it is not
    ///   possible to read the specified number of bytes;
    pub fn can_read(&self, count: usize) -> Result<()> {
        self.assert_can_read(count)
    }

    /// Returns a reference to the inner data as a
    /// slice.
    pub fn as_slice(&self) -> &[u8] {
        &self.vector
    }

    /// Returns aread-only reference to the inner vector.
    pub fn vec(&self) -> &Vec<u8> {
        &self.vector
    }
}

impl<'a> MemoryReader for VecReader {
    fn len(&self) -> usize {
        self.vector.len()
    }

    fn offset(&self) -> usize {
        self.offset
    }

    fn set_offset(&mut self, offset: usize) {
        self.offset = std::cmp::min(offset, self.vector.len());
    }

    fn available(&self) -> usize {
        self.vector.len() - self.offset
    }
}

impl<'a> Reader for VecReader {
    fn read(&mut self) -> Result<u8> {
        self.can_read(1)?;
        let r = self.vector[self.offset];
        self.offset += 1;
        Ok(r)
    }

    fn read_all(&mut self, buff: &mut [u8]) -> Result<()> {
        self.can_read(buff.len())?;
        let new_offs = self.offset + buff.len();
        buff.copy_from_slice(&self.vector[self.offset..new_offs]);
        self.offset = new_offs;
        Ok(())
    }

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

//=============================================================================
// Base VecWriter methods
//-----------------------------------------------------------------------------
macro_rules! basevecwriter_basic_impl {
    () => {
        /// Returns the current writing position.
        ///
        /// Returns:
        /// - The current offset. It is guaranteed to be at most
        /// the total size of the data.
        pub fn get_offset(&self) -> usize {
            self.offset
        }

        /// Sets the current writing position.
        ///
        /// Arguments:
        /// - `offset`: The new position. It if is larger
        ///   than the total length, it will assume the
        ///   total length;
        pub fn set_offset(&mut self, offset: usize) {
            self.offset = std::cmp::min(offset, self.vector.len());
        }

        /// Returns true if this instance is locked for writing.
        pub fn is_read_only(&self) -> bool {
            self.read_only
        }

        /// Sets the read-only flag.
        ///
        /// Arguments:
        /// - `read_only`: The new value;
        pub fn set_read_only(&mut self, read_only: bool) {
            self.read_only = read_only;
        }

        /// Verifies if the it is possible to write into this
        /// `VecWriter`.
        ///
        /// Returns:
        /// - `Ok(())`: If it is possible to write;
        /// - `Err(ErrorKind::UnableToWriteData)`: If it is not possible
        /// to write;
        pub fn can_write(&self) -> Result<()> {
            if self.read_only {
                Err(ErrorKind::UnableToWriteData)
            } else {
                Ok(())
            }
        }

        /// Returns the current data as a slice.
        pub fn as_slice(&self) -> &[u8] {
            &self.vector.as_slice()
        }

        /// Returns aread-only reference to the inner vector.
        pub fn vec(&self) -> &Vec<u8> {
            &self.vector
        }
    };
}

macro_rules! basevecwriter_writer_impl {
    () => {
        fn write(&mut self, value: u8) -> Result<()> {
            self.can_write()?;
            if self.offset == self.vector.len() {
                self.vector.push(value);
            } else {
                self.vector[self.offset] = value;
            }
            self.offset += 1;
            Ok(())
        }

        fn write_all(&mut self, buff: &[u8]) -> Result<()> {
            self.can_write()?;
            let new_offset = self.offset + buff.len();
            if new_offset > self.vector.len() {
                self.vector.resize(new_offset, 0);
            }
            self.vector[self.offset..new_offset].copy_from_slice(buff);
            self.offset = new_offset;
            Ok(())
        }

        fn as_writer(&mut self) -> &mut dyn Writer {
            self
        }
    };
}

//=============================================================================
// VecWriter
//-----------------------------------------------------------------------------
/// [`VecWriter`] implements a [`Writer`] that uses a Vec<u8> a its backend.
pub struct VecWriter {
    vector: Vec<u8>,
    offset: usize,
    read_only: bool,
}

impl VecWriter {
    /// Creates a new empty instance of this struct. The new struct
    /// is set as writeable by default.
    pub fn new() -> VecWriter {
        VecWriter {
            vector: Vec::new(),
            offset: 0,
            read_only: false,
        }
    }

    /// Creates a new empty instance of this struct with an
    /// initial capacity set.
    ///
    /// Arguments:
    /// - `capacity`: The reserved capacity;
    pub fn with_capacity(capacity: usize) -> VecWriter {
        VecWriter {
            vector: Vec::with_capacity(capacity),
            offset: 0,
            read_only: false,
        }
    }

    basevecwriter_basic_impl!();
}

impl Writer for VecWriter {
    basevecwriter_writer_impl!();
}

impl Default for VecWriter {
    fn default() -> Self {
        Self::new()
    }
}

/// New since 1.4.0.
#[allow(clippy::from_over_into)]
impl std::convert::Into<Vec<u8>> for VecWriter {
    fn into(self) -> Vec<u8> {
        self.vector
    }
}

//=============================================================================
// BorrowedVecWriter
//-----------------------------------------------------------------------------
/// [`BorrowedVecWriter`] implements a [`Writer`] that uses a borrowed Vec<u8>
/// as its backend.
///
/// The borrowed vector is used as is. This means that:
/// - Any existing data will be overwritten from the initial offset;
/// - The vector will be extended if required but will never shrink to
///   accomodate the amount of data written;
pub struct BorrowedVecWriter<'a> {
    vector: &'a mut Vec<u8>,
    initial_offset: usize,
    offset: usize,
    read_only: bool,
}

impl<'a> BorrowedVecWriter<'a> {
    /// Creates a new instance of this struct. The new struct
    /// is set as writeable by default.
    ///
    /// Arguments:
    /// - `vector`: The inner vector;
    pub fn new(vector: &'a mut Vec<u8>) -> Self {
        Self::with_offset(vector, 0)
    }

    /// Creates a new instance of this struct. The new struct
    /// is set as writeable by default.
    ///
    /// Arguments:
    /// - `vector`: The inner vector;
    /// - `offset`: The initial offset. If it is set to a value larger
    ///   than vector length, it will assume the vector length;
    pub fn with_offset(vector: &'a mut Vec<u8>, offset: usize) -> Self {
        let curr_offs = min(offset, vector.len());
        Self {
            vector,
            initial_offset: curr_offs,
            offset: curr_offs,
            read_only: false,
        }
    }

    basevecwriter_basic_impl!();

    /// Returns the number of bytes actually written.
    pub fn bytes_written(&self) -> usize {
        self.offset - self.initial_offset
    }
}

impl<'a> Writer for BorrowedVecWriter<'a> {
    basevecwriter_writer_impl!();
}

//=============================================================================
// ByteArrayWriter
//-----------------------------------------------------------------------------
/// [`ByteArrayWriter`] implements a [`Writer`] that uses a borrowed byte slice
/// as its backend.
///
/// New since 1.4.0.
pub struct ByteArrayWriter<'a> {
    array: &'a mut [u8],
    offset: usize,
}

impl<'a> ByteArrayWriter<'a> {
    /// Creates a new instance of this struct.
    ///
    /// Arguments:
    /// - `array`: The borrowed array;
    pub fn new(array: &'a mut [u8]) -> Self {
        Self { array, offset: 0 }
    }

    /// Returns the current writing position.
    ///
    /// Returns:
    /// - The current offset. It is guaranteed to be at most
    /// the total size of the data.
    pub fn get_offset(&self) -> usize {
        self.offset
    }

    /// Sets the current writing position.
    ///
    /// Arguments:
    /// - `offset`: The new position. It if is larger
    ///   than the total length, it will assume the
    ///   total length;
    pub fn set_offset(&mut self, offset: usize) {
        self.offset = std::cmp::min(offset, self.array.len());
    }

    /// Return the number of bytes available.
    #[inline]
    pub fn available(&self) -> usize {
        self.array.len() - self.offset
    }

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

impl<'a> Writer for ByteArrayWriter<'a> {
    fn write(&mut self, value: u8) -> Result<()> {
        self.can_write(1)?;
        self.array[self.offset] = value;
        self.offset += 1;
        Ok(())
    }

    fn write_all(&mut self, buff: &[u8]) -> Result<()> {
        self.can_write(buff.len())?;
        self.array[self.offset..self.offset + buff.len()].copy_from_slice(buff);
        self.offset += buff.len();
        Ok(())
    }

    fn as_writer(&mut self) -> &mut dyn Writer {
        self
    }
}