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
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46

            
47
mod err;
48
mod impls;
49
mod reader;
50
mod secretbuf;
51
mod writer;
52

            
53
pub use err::{EncodeError, Error};
54
pub use reader::{Cursor, Reader};
55
pub use secretbuf::SecretBuf;
56
pub use writer::Writer;
57

            
58
/// Result type returned by this crate for [`Reader`]-related methods.
59
pub type Result<T> = std::result::Result<T, Error>;
60
/// Result type returned by this crate for [`Writer`]-related methods.
61
pub type EncodeResult<T> = std::result::Result<T, EncodeError>;
62

            
63
/// Trait for an object that can be encoded onto a Writer by reference.
64
///
65
/// Implement this trait in order to make an object writeable.
66
///
67
/// Most code won't need to call this directly, but will instead use
68
/// it implicitly via the Writer::write() method.
69
///
70
/// # Example
71
///
72
/// ```
73
/// use tor_bytes::{Writeable, Writer, EncodeResult};
74
/// #[derive(Debug, Eq, PartialEq)]
75
/// struct Message {
76
///   flags: u32,
77
///   cmd: u8
78
/// }
79
///
80
/// impl Writeable for Message {
81
///     fn write_onto<B:Writer+?Sized>(&self, b: &mut B) -> EncodeResult<()> {
82
///         // We'll say that a "Message" is encoded as flags, then command.
83
///         b.write_u32(self.flags);
84
///         b.write_u8(self.cmd);
85
///         Ok(())
86
///     }
87
/// }
88
///
89
/// let msg = Message { flags: 0x43, cmd: 0x07 };
90
/// let mut writer: Vec<u8> = Vec::new();
91
/// writer.write(&msg);
92
/// assert_eq!(writer, &[0x00, 0x00, 0x00, 0x43, 0x07 ]);
93
/// ```
94
pub trait Writeable {
95
    /// Encode this object into the writer `b`.
96
    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> EncodeResult<()>;
97
}
98

            
99
/// Trait for an object that can be encoded and consumed by a Writer.
100
///
101
/// Implement this trait in order to make an object that can be
102
/// written more efficiently by absorbing it into the writer.
103
///
104
/// Most code won't need to call this directly, but will instead use
105
/// it implicitly via the Writer::write_and_consume() method.
106
pub trait WriteableOnce: Sized {
107
    /// Encode this object into the writer `b`, and consume it.
108
    fn write_into<B: Writer + ?Sized>(self, b: &mut B) -> EncodeResult<()>;
109
}
110

            
111
impl<W: Writeable + Sized> WriteableOnce for W {
112
78
    fn write_into<B: Writer + ?Sized>(self, b: &mut B) -> EncodeResult<()> {
113
78
        self.write_onto(b)
114
78
    }
115
}
116

            
117
impl<W: Writeable + ?Sized> Writeable for &W {
118
88
    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> EncodeResult<()> {
119
88
        (*self).write_onto(b)
120
88
    }
121
}
122

            
123
// ----------------------------------------------------------------------
124

            
125
/// Trait for an object that can be extracted from a Reader.
126
///
127
/// Implement this trait in order to make an object that can (maybe)
128
/// be decoded from a reader.
129
//
130
/// Most code won't need to call this directly, but will instead use
131
/// it implicitly via the Reader::extract() method.
132
///
133
/// # Correctness (determinism), and error handling
134
///
135
/// The `take_from` method should produce consistent and deterministic results.
136
///
137
/// If `take_from` returns `Ok`, consuming some data,
138
/// a future call with a reader which has that consumed data as a prefix,
139
/// must consume the same data and succeed with an equivalent value.
140
///
141
/// If `take_from` returns `Err`, it is allowed to have consumed
142
/// none, any, or all, of the `Reader`.
143
///
144
/// If `take_from` returns `Error::Incomplete`:
145
/// then calling `take_from` again on a similar `Reader`
146
/// (ie, where the old reader is a prefix of the new, or vice versa)
147
/// must do one of the following:
148
///  * Succeed, consuming at least as many bytes as
149
///    were available in the previous reader plus `deficit`.
150
///  * Return `Error::Incomplete` with a consistent value of `deficit`.
151
///
152
/// If `take_from` fails another way with some reader, it must fail the same way
153
/// with all other readers which have that reader as a prefix.
154
///
155
/// (Here, "prefix" and "length" relate only to the remaining bytes in the `Reader`,
156
/// irrespective of the length or value of any bytes which were previously consumed.)
157
///
158
/// (tor-socksproto relies on these properties.)
159
///
160
/// Specific implementations may provide stronger guarantees.
161
///
162
/// # Example
163
///
164
/// ```
165
/// use tor_bytes::{Readable,Reader,Result};
166
/// #[derive(Debug, Eq, PartialEq)]
167
/// struct Message {
168
///   flags: u32,
169
///   cmd: u8
170
/// }
171
///
172
/// impl Readable for Message {
173
///     fn take_from(r: &mut Reader<'_>) -> Result<Self> {
174
///         // A "Message" is encoded as flags, then command.
175
///         let flags = r.take_u32()?;
176
///         let cmd = r.take_u8()?;
177
///         Ok(Message{ flags, cmd })
178
///     }
179
/// }
180
///
181
/// let encoded = [0x00, 0x00, 0x00, 0x43, 0x07 ];
182
/// let mut reader = Reader::from_slice(&encoded);
183
/// let m: Message = reader.extract()?;
184
/// assert_eq!(m, Message { flags: 0x43, cmd: 0x07 });
185
/// reader.should_be_exhausted()?; // make sure there are no bytes left over
186
/// # Result::Ok(())
187
/// ```
188
pub trait Readable: Sized {
189
    /// Try to extract an object of this type from a Reader.
190
    ///
191
    /// Implementations should generally try to be efficient: this is
192
    /// not the right place to check signatures or perform expensive
193
    /// operations.  If you have an object that must not be used until
194
    /// it is finally validated, consider making this function return
195
    /// a wrapped type that can be unwrapped later on once it gets
196
    /// checked.
197
    fn take_from(b: &mut Reader<'_>) -> Result<Self>;
198
}
199

            
200
// ----------------------------------------------------------------------
201

            
202
#[cfg(test)]
203
mod test {
204
    // @@ begin test lint list maintained by maint/add_warning @@
205
    #![allow(clippy::bool_assert_comparison)]
206
    #![allow(clippy::clone_on_copy)]
207
    #![allow(clippy::dbg_macro)]
208
    #![allow(clippy::mixed_attributes_style)]
209
    #![allow(clippy::print_stderr)]
210
    #![allow(clippy::print_stdout)]
211
    #![allow(clippy::single_char_pattern)]
212
    #![allow(clippy::unwrap_used)]
213
    #![allow(clippy::unchecked_duration_subtraction)]
214
    #![allow(clippy::useless_vec)]
215
    #![allow(clippy::needless_pass_by_value)]
216
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
217
    use super::*;
218

            
219
    #[test]
220
    fn writer() {
221
        let mut v: Vec<u8> = Vec::new();
222
        v.write_u8(0x57);
223
        v.write_u16(0x6520);
224
        v.write_u32(0x68617665);
225
        v.write_u64(0x2061206d61636869);
226
        v.write_all(b"ne in a plexiglass dome");
227
        v.write_zeros(3);
228
        assert_eq!(&v[..], &b"We have a machine in a plexiglass dome\0\0\0"[..]);
229
    }
230
}