Debian Codegraph @

src/inspect/mod.rs

raw symbols SCIP
1 //! Reflection for testing
2 //!
3 //! Provides facilities for creating an AST-like object
4 //! tree from any valid bencode: [`Inspectable`]. Decoding bencode into
5 //! an [`Inspectable`] is done using recursion, so stack size limits
6 //! apply.
7 //!
8 //! Use for reflection, modifying, testing, and pretty printing.
9 //!
10 //! Not recommended for use in production code.
11 //!
12 //! # Overview
13 //!
14 //! See the Reflection chapter of the [README.md][r].
15 //!
16 //! # Creating
17 //!
18 //! The [`Inspectable`] docs explain how to create an `Inspectable` to get started.
19 //!
20 //! # Displaying / Outputting
21 //!
22 //! * Use [`.emit`][Inspectable::emit] to get the proper serialized bencode representation as a
23 //! byte vector.
24 //! * Derives [`Debug`][core::fmt::Debug].
25 //! * Provides [`.as_rust_string_literal`][Inspectable::as_rust_string_literal] for pretty printing.
26 //! Useful when inspecting structures, hard coding test cases, etc.
27 //! * Provided [`Display`][core::fmt::Display] implementation is similar to `.as_rust_string_literal`,
28 //! but does not insert newlines, tabs, etc. Useful for debug logs.
29 //!
30 //! # Coercion
31 //!
32 //! Mutable coercion of [`Inspectable`] to variant items: [`.string`][Inspectable::string],
33 //! [`.int`][`Inspectable::int`], [`.dict`][`Inspectable::dict`], [`.list`][`Inspectable::list`],
34 //! and [`.raw`][`Inspectable::raw`].
35 //!
36 //! Immutable coercion: [`.string_ref`][`Inspectable::string_ref`], [`.int_ref`][`Inspectable::int_ref`],
37 //! [`.dict_ref`][`Inspectable::dict_ref`], [`.list_ref`][`Inspectable::list_ref`],
38 //! and [`.raw_ref`][`Inspectable::raw_ref`].
39 //!
40 //! These coercion method names are reversed compared to the standard `_mut` idiom in Rust, because you
41 //! almost always want to mutate these objects, not just look at them. These methods will panic if
42 //! called on an [`Inspectable`] with the wrong enum variant.
43 //!
44 //! # Traversing
45 //!
46 //! Use [`inspect_path()`][ip] to create a [`PathBuilder`][pb], for use with
47 //! the [`.find`][Inspectable::find], [`.find_ref`][Inspectable::find_ref],
48 //! [`.clone_and_mutate`][Inspectable::clone_and_mutate], and [`.mutate`][Inspectable::mutate]
49 //! methods. These will drill down into the AST according to the
50 //! [`Step`][crate::inspect::traverse::Step]s in the [`Path`][pb].
51 //!
52 //! Searches in path traversal are implemented using recursion, so stack limits may
53 //! apply. One can also use a combination of coercion and the following methods to
54 //! traverse the AST without using Paths:
55 //!
56 //! * [`InList`]: [`.nth`][InList::nth], [`.nth_ref`][InList::nth_ref]
57 //! * [`InDict`]: [`.nth`][InDict::nth], [`.nth_ref`][InDict::nth_ref],
58 //! and [`.entry`][InDict::entry], [`.entry_ref`][InDict::entry_ref].
59 //! * [`InDictEntry`]: [`.key`][InDictEntry::key] and [`.value`][InDictEntry::value].
60 //!
61 //! The traversal methods will all panic on failure.
62 //!
63 //! # Mutating
64 //!
65 //! There are many ways to mutate an [`Inspectable`] AST. Some of them require first coercing the
66 //! [`Inspectable`] to its appropriate subtype. These are all best applied using these functions:
67 //! [`.clone_and_mutate`][Inspectable::clone_and_mutate] and [`.mutate`][Inspectable::mutate].
68 //! For convenience, there is also [`.apply`][Inspectable::apply].
69 //!
70 //! Here are all the mutation methods, grouped by the type they belong to. Methods on [`Inspectable`]
71 //! may only be used on the type variants specified in parentheses. They will panic if used on a type
72 //! variant they do not support. All of these except `.replace` are also available on their respective
73 //! type variants.
74 //!
75 //! * [`Inspectable`]
76 //! * [`.clear_content`][Inspectable::clear_content] (all)
77 //! * [`.remove_entry`][`Inspectable::remove_entry`] (dicts only)
78 //! * [`.remove_nth`][`Inspectable::remove_nth`] (dicts and lists)
79 //! * [`.replace`][Inspectable::replace] (all)
80 //! * [`.set_content_byterange`][Inspectable::set_content_byterange] (bytestrings only)
81 //! * [`.truncate`][Inspectable::truncate] (bytestrings only)
82 //! * [`InDict`]
83 //! * [`.sort`][InDict::sort]
84 //! * [`InInt`]
85 //! * [`.set`][InInt::set]
86 //! * [`InString`] (bytestrings)
87 //! * [`.clear_fake_length`][InString::clear_fake_length]
88 //! * [`.set_fake_length`][InString::set_fake_length]
89 //! * [`.set_content_str`][InString::set_content_str]
90 //! * [`.set_content_string`][InString::set_content_string]
91 //! * [`.set_content_u8`][InString::set_content_u8]
92 //! * [`.set_content_vec`][InString::set_content_vec]
93 //!
94 //! All properties of [`Inspectable`] and its type variants are public, so you may also make your own mutators.
95 //!
96 //! [r]: https://github.com/P3KI/bendy/blob/master/README.md#reflection
97 //! [pb]: crate::inspect::traverse::PathBuilder
98 //! [ip]: crate::inspect::inspect_path
99
100 #[cfg(not(feature = "std"))]
101 use alloc::{
102 borrow::Cow,
103 string::{String, ToString},
104 vec::Vec,
105 };
106 #[cfg(feature = "std")]
107 use std::{borrow::Cow, vec::Vec};
108
109 pub mod display;
110 pub mod mutate;
111 #[doc(hidden)]
112 pub mod parse;
113 pub mod traverse;
114
115 /// Attempt to decode a u8 buffer into an inspectable.
116 /// Panics on error. Use [`Inspectable::try_from`] for a
117 /// fallible alternative.
118 pub fn inspect<'ser>(buf: &'ser [u8]) -> Inspectable<'ser> {
119 Inspectable::try_from(buf).expect("Could not decode buffer into inspectable")
120 }
121
122 /// Builds a path that can be used to traverse from an Inspectable AST.
123 /// [Read here][crate::inspect#traversing] for details.
124 pub fn inspect_path<'ser>() -> traverse::PathBuilder<'ser> {
125 traverse::PathBuilder::new()
126 }
127
128 /// An object that represents something that bencode can
129 /// decode to. Usable for reflection, modification,
130 /// testing, and pretty printing.
131 ///
132 /// See the [module][crate::inspect] documentation for usage.
133 ///
134 /// # Construction
135 ///
136 /// You parse bencode into an Inspectable AST like this:
137 /// ```
138 /// # use bendy;
139 /// # use bendy::inspect::*;
140 /// let bencode = b"i10e";
141 /// let inspectable = bendy::inspect::inspect(bencode);
142 /// assert_eq!(inspectable.emit(), bencode);
143 /// ```
144 ///
145 /// Or use the [`Inspectable::try_from`] method for fallible construction.
146 #[derive(Debug, PartialEq, Eq, Clone)]
147 pub enum Inspectable<'ser> {
148 Int(InInt<'ser>),
149 String(InString<'ser>),
150 Raw(Cow<'ser, [u8]>),
151 Dict(InDict<'ser>),
152 List(InList<'ser>),
153 }
154
155 impl<'ser> Inspectable<'ser> {
156 /// Construct a new [`Inspectable::Raw`]
157 pub fn new_raw(buf: &'ser [u8]) -> Inspectable<'ser> {
158 Inspectable::Raw(Cow::from(buf))
159 }
160
161 /// Construct a new [`Inspectable::Int`]
162 pub fn new_int(i: i64) -> Inspectable<'ser> {
163 let inint = InInt {
164 bytes: Cow::Owned(i.to_string()),
165 };
166 Inspectable::Int(inint)
167 }
168
169 /// Construct a new [`Inspectable::String`]
170 pub fn new_string(buf: &'ser [u8]) -> Inspectable<'ser> {
171 Inspectable::String(InString::new(buf))
172 }
173
174 /// Construct a new [`Inspectable::Dict`]
175 pub fn new_dict() -> Inspectable<'ser> {
176 Inspectable::Dict(InDict::new())
177 }
178
179 /// Construct a new [`Inspectable::List`]
180 pub fn new_list() -> Inspectable<'ser> {
181 Inspectable::List(InList::new())
182 }
183
184 /// Get the serialized bencode representation of this [`Inspectable`]
185 pub fn emit(&self) -> Vec<u8> {
186 let mut res = Vec::new();
187
188 fn emit_str(s: &InString, out: &mut Vec<u8>) {
189 let len = s.len().to_string();
190 out.extend_from_slice(len.as_bytes());
191 out.push(b':');
192 out.extend_from_slice(s.content())
193 }
194
195 fn dispatch(i: &Inspectable, out: &mut Vec<u8>) {
196 match i {
197 Inspectable::String(x) => {
198 emit_str(x, out);
199 },
200 Inspectable::Raw(x) => {
201 out.extend_from_slice(x);
202 },
203 Inspectable::Int(x) => {
204 out.push(b'i');
205 out.extend_from_slice(x.bytes.as_bytes());
206 out.push(b'e');
207 },
208 Inspectable::List(x) => {
209 out.push(b'l');
210 for item in x.items.iter() {
211 dispatch(item, out);
212 }
213 out.push(b'e');
214 },
215 Inspectable::Dict(x) => {
216 out.push(b'd');
217 for InDictEntry { key, value } in x.items.iter() {
218 dispatch(key, out);
219 dispatch(value, out);
220 }
221 out.push(b'e');
222 },
223 }
224 }
225 dispatch(self, &mut res);
226 res
227 }
228 }
229
230 /// An [`Inspectable`] AST node representing a byte string.
231 /// Stores the raw bytes of the bytestring, in a [`Cow`].
232 #[doc(alias = "bytestring")]
233 #[doc(alias = "byte string")]
234 #[doc(alias = "string")]
235 #[derive(Debug, PartialEq, Eq, Clone)]
236 pub struct InString<'ser> {
237 /// The bytes in this ByteString. Does not include
238 /// the prefix length and prefix separator `:`.
239 pub bytes: Cow<'ser, [u8]>,
240 /// If set, will provide a fake length prefix when emitted.
241 pub fake_length: Option<usize>,
242 }
243
244 /// An [`Inspectable`] AST node representing an integer.
245 /// Stores the raw bytes of the integer, in a [`Cow`].
246 #[doc(alias = "int")]
247 #[doc(alias = "number")]
248 #[derive(Debug, PartialEq, Eq, Clone)]
249 pub struct InInt<'ser> {
250 /// The raw bytes making up the number.
251 /// Does not include the `i` prefix and `e` suffix.
252 pub bytes: Cow<'ser, str>,
253 }
254
255 /// An [`Inspectable`] AST node representing a dictionary entry.
256 /// This only appears in the [`InDict`] node, never as a variant
257 /// of [`Inspectables`][Inspectable].
258 #[doc(alias = "dict entry")]
259 #[doc(alias = "dictionary entry")]
260 #[derive(Debug, PartialEq, Eq, Clone)]
261 pub struct InDictEntry<'ser> {
262 /// This struct field MUST contain an Inspectable::String
263 /// for the resulting bencode to be valid.
264 pub key: Inspectable<'ser>,
265 pub value: Inspectable<'ser>,
266 }
267
268 /// An [`Inspectable`] AST node representing a dictionary.
269 #[doc(alias = "dict")]
270 #[doc(alias = "dictionary")]
271 #[derive(Debug, PartialEq, Eq, Clone)]
272 pub struct InDict<'ser> {
273 /// The entries in the dictionary.
274 /// Note that bendy will NOT decode a dict
275 /// if the keys are unsorted.
276 pub items: Vec<InDictEntry<'ser>>,
277 }
278
279 /// An [`Inspectable`] AST node representing a list.
280 #[derive(Debug, PartialEq, Eq, Clone)]
281 #[doc(alias = "list")]
282 #[doc(alias = "vec")]
283 pub struct InList<'ser> {
284 pub items: Vec<Inspectable<'ser>>,
285 }
286
287 impl<'ser> InInt<'ser> {
288 pub fn new(buf: &'ser str) -> Self {
289 InInt {
290 bytes: Cow::from(buf),
291 }
292 }
293
294 /// Returns an i64 of the value represented.
295 /// Panics if this is not possible.
296 #[must_use]
297 pub fn as_i64(&self) -> i64 {
298 self.bytes.parse().expect("Could not parse InInt as i64")
299 }
300 }
301
302 impl<'ser> InString<'ser> {
303 pub fn new(buf: &'ser [u8]) -> InString<'ser> {
304 InString {
305 bytes: Cow::from(buf),
306 fake_length: None,
307 }
308 }
309
310 /// Returns the number of bytes in the bytestring,
311 /// or the fake length of the bytestring if set.
312 pub fn len(&self) -> usize {
313 self.fake_length.unwrap_or_else(|| self.bytes.len())
314 }
315
316 /// Returns true if there are no bytes in the bytestring,
317 /// or if the fake length of the bytestring is 0 if set.
318 pub fn is_empty(&self) -> bool {
319 self.len() == 0
320 }
321
322 /// Convenience method to get an immutable reference
323 /// to the bytestring's contents.
324 pub fn content(&self) -> &[u8] {
325 &self.bytes
326 }
327 }
328
329 impl<'ser> InList<'ser> {
330 #[allow(clippy::new_without_default)]
331 pub fn new() -> Self {
332 InList { items: Vec::new() }
333 }
334 }
335
336 impl<'ser> InDict<'ser> {
337 #[allow(clippy::new_without_default)]
338 pub fn new() -> Self {
339 InDict { items: Vec::new() }
340 }
341 }
342
343 impl<'ser> InDictEntry<'ser> {
344 /// Creates a new dict entry. If the given key is not a byte string
345 /// ([`Inspectable::String`]) then bendy will not decode the resulting bencode.
346 pub fn new(key: Inspectable<'ser>, value: Inspectable<'ser>) -> Self {
347 InDictEntry { key, value }
348 }
349 }
350
351 #[cfg(test)]
352 mod tests {
353 use super::*;
354
355 #[test]
356 fn all_traversal_test() {
357 let buf = b"\
358 l\
359 i99e\
360 5:hello\
361 d\
362 3:one\
363 i11e\
364 3:two\
365 i22e\
366 5:zzzzz\
367 i33e\
368 e\
369 e";
370 let i = inspect(buf);
371 let l = i.list_ref();
372 assert_eq!(3, l.items.len());
373 assert_eq!(99, l.nth_ref(0).int_ref().as_i64());
374 assert_eq!(b"hello".as_slice(), &*l.nth_ref(1).string_ref().bytes);
375 let d = i.list_ref().nth_ref(2).dict_ref();
376 let t0 = d.nth_ref(0);
377 let t1 = d.nth_ref(1);
378 let t2 = d.entry_ref(b"zzzzz");
379 assert_eq!(b"one".as_slice(), &*t0.key.string_ref().bytes);
380 assert_eq!(b"two".as_slice(), &*t1.key.string_ref().bytes);
381 assert_eq!(b"zzzzz".as_slice(), &*t2.key.string_ref().bytes);
382 assert_eq!(11, t0.value.int_ref().as_i64());
383 assert_eq!(22, t1.value.int_ref().as_i64());
384 assert_eq!(33, t2.value.int_ref().as_i64());
385 }
386
387 #[test]
388 fn int_modify_test() {
389 let buf = b"i64e";
390 let mut i = inspect(buf);
391 assert_eq!(64, i.int().as_i64());
392 i.int().set(32);
393 assert_eq!(32, i.int().as_i64());
394 assert_eq!("i32e", i.to_string().as_str());
395 assert_eq!(b"i32e", i.emit().as_slice());
396
397 let buf = b"\
398 l\
399 i43770e\
400 d\
401 3:one\
402 i11e\
403 e\
404 e";
405 let mut i = inspect(buf);
406 i.list().nth(0).int().set(2);
407 i.list().nth(1).dict().nth(0).value.int().set(1);
408 assert_eq!(b"li2ed3:onei1eee", i.emit().as_slice());
409 }
410
411 #[test]
412 fn fake_bytestring_length_test() {
413 let buf = b"\
414 l\
415 5:hello\
416 d\
417 3:one\
418 i11e\
419 e\
420 e";
421 let mut i = inspect(buf);
422 i.list().nth(0).string().set_fake_length(20);
423 i.list()
424 .nth(1)
425 .dict()
426 .nth(0)
427 .key
428 .string()
429 .set_fake_length(0);
430 assert_eq!(b"l20:hellod0:onei11eee", i.emit().as_slice());
431 assert_eq!("l20:hellod0:onei11eee", i.to_string().as_str());
432 }
433
434 #[test]
435 fn bytestring_set_content_test() {
436 let buf = b"\
437 l\
438 5:hello\
439 5:world\
440 d\
441 5:hello\
442 5:world\
443 e\
444 e";
445 let mut i = inspect(buf);
446 i.list()
447 .nth(0)
448 .string()
449 .set_content_string("one".to_string());
450 i.list().nth(1).string().set_content_str("two");
451 let entry = i.list().nth(2).dict().nth(0);
452 entry.key.string().set_content_u8(b"three");
453 entry.value.string().set_content_vec(Vec::from(b"four"));
454 assert_eq!(b"l3:one3:twod5:three4:fouree", i.emit().as_slice());
455 assert_eq!("l3:one3:twod5:three4:fouree", i.to_string().as_str());
456
457 let mut i = inspect(b"5:hello");
458 i.string().set_content_u8(b"\x00\x01");
459 assert_eq!(b"2:\x00\x01", i.emit().as_slice());
460 assert_eq!("2:\\x00\\x01", i.to_string().as_str());
461 }
462 }