tor_bytes/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![warn(clippy::cognitive_complexity)]
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_duration_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39#![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43#![allow(clippy::needless_lifetimes)] // See arti#1765
44//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
45
46mod err;
47mod impls;
48mod reader;
49mod secretbuf;
50mod writer;
51
52pub use err::{EncodeError, Error};
53pub use reader::{Cursor, Reader};
54pub use secretbuf::SecretBuf;
55pub use writer::Writer;
56
57/// Result type returned by this crate for [`Reader`]-related methods.
58pub type Result<T> = std::result::Result<T, Error>;
59/// Result type returned by this crate for [`Writer`]-related methods.
60pub type EncodeResult<T> = std::result::Result<T, EncodeError>;
61
62/// Trait for an object that can be encoded onto a Writer by reference.
63///
64/// Implement this trait in order to make an object writeable.
65///
66/// Most code won't need to call this directly, but will instead use
67/// it implicitly via the Writer::write() method.
68///
69/// # Example
70///
71/// ```
72/// use tor_bytes::{Writeable, Writer, EncodeResult};
73/// #[derive(Debug, Eq, PartialEq)]
74/// struct Message {
75///   flags: u32,
76///   cmd: u8
77/// }
78///
79/// impl Writeable for Message {
80///     fn write_onto<B:Writer+?Sized>(&self, b: &mut B) -> EncodeResult<()> {
81///         // We'll say that a "Message" is encoded as flags, then command.
82///         b.write_u32(self.flags);
83///         b.write_u8(self.cmd);
84///         Ok(())
85///     }
86/// }
87///
88/// let msg = Message { flags: 0x43, cmd: 0x07 };
89/// let mut writer: Vec<u8> = Vec::new();
90/// writer.write(&msg);
91/// assert_eq!(writer, &[0x00, 0x00, 0x00, 0x43, 0x07 ]);
92/// ```
93pub trait Writeable {
94    /// Encode this object into the writer `b`.
95    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> EncodeResult<()>;
96}
97
98/// Trait for an object that can be encoded and consumed by a Writer.
99///
100/// Implement this trait in order to make an object that can be
101/// written more efficiently by absorbing it into the writer.
102///
103/// Most code won't need to call this directly, but will instead use
104/// it implicitly via the Writer::write_and_consume() method.
105pub trait WriteableOnce: Sized {
106    /// Encode this object into the writer `b`, and consume it.
107    fn write_into<B: Writer + ?Sized>(self, b: &mut B) -> EncodeResult<()>;
108}
109
110impl<W: Writeable + Sized> WriteableOnce for W {
111    fn write_into<B: Writer + ?Sized>(self, b: &mut B) -> EncodeResult<()> {
112        self.write_onto(b)
113    }
114}
115
116impl<W: Writeable + ?Sized> Writeable for &W {
117    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> EncodeResult<()> {
118        (*self).write_onto(b)
119    }
120}
121
122// ----------------------------------------------------------------------
123
124/// Trait for an object that can be extracted from a Reader.
125///
126/// Implement this trait in order to make an object that can (maybe)
127/// be decoded from a reader.
128//
129/// Most code won't need to call this directly, but will instead use
130/// it implicitly via the Reader::extract() method.
131///
132/// # Correctness (determinism), and error handling
133///
134/// The `take_from` method should produce consistent and deterministic results.
135///
136/// If `take_from` returns `Ok`, consuming some data,
137/// a future call with a reader which has that consumed data as a prefix,
138/// must consume the same data and succeed with an equivalent value.
139///
140/// If `take_from` returns `Err`, it is allowed to have consumed
141/// none, any, or all, of the `Reader`.
142///
143/// If `take_from` returns `Error::Incomplete`:
144/// then calling `take_from` again on a similar `Reader`
145/// (ie, where the old reader is a prefix of the new, or vice versa)
146/// must do one of the following:
147///  * Succeed, consuming at least as many bytes as
148///    were available in the previous reader plus `deficit`.
149///  * Return `Error::Incomplete` with a consistent value of `deficit`.
150///
151/// If `take_from` fails another way with some reader, it must fail the same way
152/// with all other readers which have that reader as a prefix.
153///
154/// (Here, "prefix" and "length" relate only to the remaining bytes in the `Reader`,
155/// irrespective of the length or value of any bytes which were previously consumed.)
156///
157/// (tor-socksproto relies on these properties.)
158///
159/// Specific implementations may provide stronger guarantees.
160///
161/// # Example
162///
163/// ```
164/// use tor_bytes::{Readable,Reader,Result};
165/// #[derive(Debug, Eq, PartialEq)]
166/// struct Message {
167///   flags: u32,
168///   cmd: u8
169/// }
170///
171/// impl Readable for Message {
172///     fn take_from(r: &mut Reader<'_>) -> Result<Self> {
173///         // A "Message" is encoded as flags, then command.
174///         let flags = r.take_u32()?;
175///         let cmd = r.take_u8()?;
176///         Ok(Message{ flags, cmd })
177///     }
178/// }
179///
180/// let encoded = [0x00, 0x00, 0x00, 0x43, 0x07 ];
181/// let mut reader = Reader::from_slice(&encoded);
182/// let m: Message = reader.extract()?;
183/// assert_eq!(m, Message { flags: 0x43, cmd: 0x07 });
184/// reader.should_be_exhausted()?; // make sure there are no bytes left over
185/// # Result::Ok(())
186/// ```
187pub trait Readable: Sized {
188    /// Try to extract an object of this type from a Reader.
189    ///
190    /// Implementations should generally try to be efficient: this is
191    /// not the right place to check signatures or perform expensive
192    /// operations.  If you have an object that must not be used until
193    /// it is finally validated, consider making this function return
194    /// a wrapped type that can be unwrapped later on once it gets
195    /// checked.
196    fn take_from(b: &mut Reader<'_>) -> Result<Self>;
197}
198
199// ----------------------------------------------------------------------
200
201#[cfg(test)]
202mod test {
203    // @@ begin test lint list maintained by maint/add_warning @@
204    #![allow(clippy::bool_assert_comparison)]
205    #![allow(clippy::clone_on_copy)]
206    #![allow(clippy::dbg_macro)]
207    #![allow(clippy::mixed_attributes_style)]
208    #![allow(clippy::print_stderr)]
209    #![allow(clippy::print_stdout)]
210    #![allow(clippy::single_char_pattern)]
211    #![allow(clippy::unwrap_used)]
212    #![allow(clippy::unchecked_duration_subtraction)]
213    #![allow(clippy::useless_vec)]
214    #![allow(clippy::needless_pass_by_value)]
215    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
216    use super::*;
217
218    #[test]
219    fn writer() {
220        let mut v: Vec<u8> = Vec::new();
221        v.write_u8(0x57);
222        v.write_u16(0x6520);
223        v.write_u32(0x68617665);
224        v.write_u64(0x2061206d61636869);
225        v.write_all(b"ne in a plexiglass dome");
226        v.write_zeros(3);
227        assert_eq!(&v[..], &b"We have a machine in a plexiglass dome\0\0\0"[..]);
228    }
229}