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