nuts_bytes/put_bytes.rs
1// MIT License
2//
3// Copyright (c) 2023,2024 Robin Doer
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to
7// deal in the Software without restriction, including without limitation the
8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22
23#[cfg(test)]
24mod tests;
25
26use std::mem;
27use thiserror::Error;
28
29/// Error type for the [`PutBytes`] trait.
30#[derive(Debug, Error, PartialEq)]
31pub enum PutBytesError {
32 /// No more space available when writing into a byte slice.
33 #[error("no more space available for writing")]
34 NoSpace,
35}
36
37/// Trait that describes a writer of binary data.
38///
39/// The [`Writer`](crate::Writer) utility accepts all types that implements
40/// this trait.
41pub trait PutBytes {
42 /// Appends all the given data in `buf` at the end of this writer.
43 ///
44 /// # Errors
45 ///
46 /// If not all data could be written, the implementator should
47 /// return a [`PutBytesError::NoSpace`] error.
48 fn put_bytes(&mut self, buf: &[u8]) -> Result<(), PutBytesError>;
49}
50
51/// `PutBytes` is implemented for `&mut [u8]` by copying into the slice,
52/// overwriting its data.
53///
54/// Note that putting bytes updates the slice to point to the yet unwritten part.
55/// The slice will be empty when it has been completely overwritten.
56///
57/// If the number of bytes to be written exceeds the size of the slice, the
58/// operation will return a [`PutBytesError::NoSpace`] error.
59impl PutBytes for &mut [u8] {
60 fn put_bytes(&mut self, buf: &[u8]) -> Result<(), PutBytesError> {
61 if self.len() >= buf.len() {
62 let (a, b) = mem::take(self).split_at_mut(buf.len());
63
64 a.copy_from_slice(buf);
65 *self = b;
66
67 Ok(())
68 } else {
69 Err(PutBytesError::NoSpace)
70 }
71 }
72}
73
74/// `PutBytes` is implemented for [`Vec<u8>`] by appending bytes to the `Vec`.
75impl PutBytes for Vec<u8> {
76 fn put_bytes(&mut self, buf: &[u8]) -> Result<(), PutBytesError> {
77 self.extend_from_slice(buf);
78 Ok(())
79 }
80}
81
82/// `PutBytes` is implemented for [&mut `Vec<u8>`] by appending bytes to the `Vec`.
83impl PutBytes for &mut Vec<u8> {
84 fn put_bytes(&mut self, buf: &[u8]) -> Result<(), PutBytesError> {
85 self.extend_from_slice(buf);
86 Ok(())
87 }
88}