nuts_bytes/reader.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::from_bytes::FromBytes;
25use crate::take_bytes::TakeBytes;
26
27/// A cursor like utility that reads structured data from an arbitrary source.
28///
29/// The source must implement the [`TakeBytes`] trait which supports reading
30/// binary data from it.
31pub struct Reader<TB> {
32 source: TB,
33}
34
35impl<TB: TakeBytes> Reader<TB> {
36 /// Creates a new `Reader` instance.
37 ///
38 /// The source of the reader is passed to the function. Every type that
39 /// implements the [`TakeBytes`] trait can be the source of this reader.
40 pub fn new(source: TB) -> Reader<TB> {
41 Reader { source }
42 }
43
44 /// Deserializes from this binary representation into a data structure
45 /// which implements the [`FromBytes`] trait.
46 pub fn read<FB: FromBytes>(&mut self) -> Result<FB, Error> {
47 FromBytes::from_bytes(&mut self.source)
48 }
49}
50
51impl<TB> AsRef<TB> for Reader<TB> {
52 fn as_ref(&self) -> &TB {
53 &self.source
54 }
55}