nuts_bytes/writer.rs
1// MIT License
2//
3// Copyright (c) 2023 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
23use crate::error::Error;
24use crate::put_bytes::PutBytes;
25use crate::to_bytes::ToBytes;
26
27/// A cursor like utility that writes structured data into an arbitrary target.
28///
29/// The target must implement the [`PutBytes`] trait which supports writing
30/// binary data into it.
31#[derive(Debug)]
32pub struct Writer<T> {
33 target: T,
34}
35
36impl<T: PutBytes> Writer<T> {
37 /// Creates a new `Writer` instance.
38 ///
39 /// The target, where the writer puts the binary data, is passed to the
40 /// function. Every type, that implements the [`PutBytes`] trait can be the
41 /// target of this writer.
42 pub fn new(target: T) -> Writer<T> {
43 Writer { target }
44 }
45
46 /// Serializes a data structure that implements the [`ToBytes`] trait.
47 ///
48 /// Returns the number of bytes actually serialized.
49 pub fn write<TB: ToBytes>(&mut self, value: &TB) -> Result<usize, Error> {
50 ToBytes::to_bytes(value, &mut self.target)
51 }
52
53 /// Consumes this `Writer`, returning the underlying target.
54 pub fn into_target(self) -> T {
55 self.target
56 }
57}
58
59impl<T> AsRef<T> for Writer<T> {
60 fn as_ref(&self) -> &T {
61 &self.target
62 }
63}