bendy 0.6.1

A rust library for encoding and decoding bencode with enforced canonicalization rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Ways of traversing the AST-like structure of [`Inspectable`]s.
//!
//! Refer to the [documentation here][crate::inspect#traversing].

use smallvec::SmallVec;

use crate::inspect::*;

/// A `Step` in a search path, which selects what next traversal
/// will be applied to an [`Inspectable`] tree.
///
/// A search path is a list of Steps.
#[derive(Debug, Clone)]
pub enum Step<'a> {
    /// Searches for a child, which is either an [`Inspectable`] or a [Dict
    /// Entry][crate::inspect::InDictEntry].
    /// Only finds the first child matching the specific condition.
    Search(Search<'a>),

    /// Access the nth child of a List or Dict.
    Nth(usize),

    /// Accesses a Dict Entry with the given key.
    Entry(&'a [u8]),

    /// Assume current item is an Dict Entry, access the key.
    Key,

    /// Assume current item is an Dict Entry, access the value.
    Value,
}

/// An object that represents what to search for in a [`Step::Search`].
#[derive(Debug, Clone)]
pub enum Search<'a> {
    /// Search for a String with this exact value.
    ByteString(&'a [u8]),

    /// Search for a Dict Entry that has this exact key.
    DictKey(&'a [u8]),

    /// Search for this exact integer.
    Int(Cow<'a, str>),
}

type Path<'a> = SmallVec<[Step<'a>; 20]>;

/// A builder for a path. A path is a list of [`Step`]s undertaken to traverse
/// an [`Inspectable`] AST.
///
/// Use the methods provided to add new steps to the path, then provide a reference
/// to the [`PathBuilder`] to one of these methods:
/// * [`Inspectable::find`]
/// * [`Inspectable::find_ref`]
/// * [`Inspectable::clone_and_mutate`]
/// * [`Inspectable::mutate`]
///
/// Unlike the standard build pattern, no `.build()` function is needed to reify
/// the builder.
///
/// The methods named `into_*` all take ownership of the PathBuilder, add the step,
/// then return the builder. This reduces memory allocation, but may be inconvenient.
///
/// The methods without the `into_` prefix will create a clone of the PathBuilder,
/// add the step to that clone, then return the clone. This may be more convenient
/// if you are building multiple paths that all start with the same steps.
///
/// The builder can contain up to 20 steps before it needs to allocate. For fuzzing,
/// manually building structures using the [`Inspectable`] constructor methods is
/// recommended instead of mutating existing [`Inspectable`]s.
#[derive(Debug, Clone)]
pub struct PathBuilder<'a> {
    pub steps: Path<'a>,
}

impl<'obj, 'pb, 'step> PathBuilder<'pb>
where
    'step: 'pb,
{
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        PathBuilder {
            steps: Default::default(),
        }
    }

    /// Descend into a specific item in a list or entry in a dict, given its index.
    ///
    /// For dicts, MUST be followed by a call to one of: [`.key`][PathBuilder::key],
    /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
    /// or [`.into_value`][PathBuilder::into_value].
    pub fn into_nth(mut self, idx: usize) -> Self {
        self.steps.push(Step::Nth(idx));
        self
    }

    /// Descend into a specific item in a list or entry in a dict, given its index.
    ///
    /// For dicts, MUST be followed by a call to one of: [`.key`][PathBuilder::key],
    /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
    /// or [`.into_value`][PathBuilder::into_value].
    pub fn nth(&'obj self, idx: usize) -> Self {
        let next = self.clone();
        next.into_nth(idx)
    }

    /// Access a Dict Entry that has the given key byte string.
    ///
    /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
    /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
    /// or [`.into_value`][PathBuilder::into_value].
    pub fn into_entry(mut self, entry_key: &'step [u8]) -> PathBuilder<'pb> {
        self.steps.push(Step::Entry(entry_key));
        self
    }

    /// Access a Dict Entry that has the given key byte string.
    ///
    /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
    /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
    /// or [`.into_value`][PathBuilder::into_value].
    pub fn entry(&'obj self, entry_key: &'step [u8]) -> PathBuilder<'pb> {
        let next = self.clone();
        next.into_entry(entry_key)
    }

    /// Access the key part of a Dict Entry.
    pub fn into_key(mut self) -> Self {
        self.steps.push(Step::Key);
        self
    }

    /// Access the key part of a Dict Entry.
    pub fn key(&'obj self) -> Self {
        let next = self.clone();
        next.into_key()
    }

    /// Access the value part of a Dict Entry.
    pub fn into_value(mut self) -> Self {
        self.steps.push(Step::Value);
        self
    }

    /// Access the value part of a Dict Entry.
    pub fn value(&'obj self) -> Self {
        let next = self.clone();
        next.into_value()
    }

    /// Search for byte strings that are not dict keys.
    pub fn into_search_bytestring(mut self, bytestring: &'step [u8]) -> PathBuilder<'pb> {
        self.steps
            .push(Step::Search(Search::ByteString(bytestring)));
        self
    }

    /// Search for byte strings that are not dict keys.
    pub fn search_bytestring(&'obj self, bytestring: &'step [u8]) -> PathBuilder<'pb> {
        let next = self.clone();
        next.into_search_bytestring(bytestring)
    }

    /// Search for Dict Entries that have the given key.
    ///
    /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
    /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
    /// or [`.into_value`][PathBuilder::into_value].
    pub fn into_search_entry(mut self, dict_key: &'step [u8]) -> PathBuilder<'pb> {
        self.steps.push(Step::Search(Search::DictKey(dict_key)));
        self
    }

    /// Search for Dict Entries that have the given key.
    ///
    /// MUST be followed by a call to one of: [`.key`][PathBuilder::key],
    /// [`.into_key`][PathBuilder::into_key], [`.value`][PathBuilder::value],
    /// or [`.into_value`][PathBuilder::into_value].
    pub fn search_entry(&'obj self, dict_key: &'step [u8]) -> PathBuilder<'pb> {
        let next = self.clone();
        next.into_search_entry(dict_key)
    }

    /// Search for an integer, provided as a string slice.
    pub fn into_search_int(mut self, number: &'step str) -> PathBuilder<'pb> {
        self.steps.push(Step::Search(Search::Int(number.into())));
        self
    }

    /// Search for an integer, provided as a string slice.
    pub fn search_int(&'obj self, number: &'step str) -> PathBuilder<'pb> {
        let next = self.clone();
        next.into_search_int(number)
    }

    /// Search for an integer, this function converts an i64 to a string slice for you.
    pub fn into_search_int_i64(mut self, number: i64) -> PathBuilder<'pb> {
        self.steps
            .push(Step::Search(Search::Int(number.to_string().into())));
        self
    }

    /// Search for an integer, this function converts an i64 to a string slice for you.
    pub fn search_int_i64(&'obj self, number: i64) -> PathBuilder<'pb> {
        let next = self.clone();
        next.into_search_int_i64(number)
    }
}

impl<'obj, 'ser, 'pb, 'pbobj> Inspectable<'ser> {
    /// Gets a mutable reference to the Inspectable pointed to by the given path.
    /// Panics if no Inspectable matches the given path.
    pub fn find(&'obj mut self, path: &'pbobj PathBuilder<'pb>) -> &'obj mut Inspectable<'ser> {
        let res = self.find_impl(&path.steps, 0);
        match res {
            None => panic!("Path did not resolve to an Inspectable: {:?}", path),
            Some(x) => x,
        }
    }

    /// Gets a reference to the Inspectable pointed to by the given path.
    /// Panics if no Inspectable matches the given path.
    pub fn find_ref(&'obj self, path: &'pbobj PathBuilder<'pb>) -> &'obj Inspectable<'ser> {
        let res = self.find_ref_impl(&path.steps, 0);
        match res {
            None => panic!("Path did not resolve to an Inspectable: {:?}", path),
            Some(x) => x,
        }
    }
}

macro_rules! finders {
    ($(($name:ident, $get:ident, $iter:ident, $( $mutable:ident )? ))*) => {$(
        impl<'obj, 'ser, 'pb, 'pbobj> Inspectable<'ser> {
            fn $name(
                &'obj $($mutable)? self,
                steps: &'pbobj Path<'pb>,
                pc: usize,
            ) -> Option<&'obj $($mutable)? Inspectable<'ser>> {
                let current_step = if let Some(x) = steps.get(pc) {
                    x
                } else {
                    return Some(self);
                };

                let descend_into_entry =
                    |entry: &'obj $($mutable)? InDictEntry<'ser>| -> Option<&'obj $($mutable)? Inspectable<'ser>> {
                        match steps.get(pc + 1) {
                            Some(Step::Key) => entry.key.$name(steps, pc + 2),
                            Some(Step::Value) => entry.value.$name(steps, pc + 2),
                            _ => panic!(
                                "A path that selects a dict entry must then select either its key or its value"
                            ),
                        }
                    };

                match (self, current_step) {
                    (Inspectable::Raw(_), _) => (),

                    (s @ Inspectable::Int(_), Step::Search(Search::Int(x))) => {
                        if *x == &*s.int_ref().bytes {
                            return Some(s);
                        }
                    },
                    (Inspectable::Int(_), _) => (),

                    (s @ Inspectable::String(_), Step::Search(Search::ByteString(x))) => {
                        if *x == &*s.string_ref().bytes {
                            return Some(s);
                        }
                    },
                    (Inspectable::String(_), Step::Search(_)) => (),
                    (Inspectable::String(_), _) => (),

                    (Inspectable::List(_), Step::Key) => (),
                    (Inspectable::List(_), Step::Value) => (),
                    (Inspectable::List(_), Step::Entry(_)) => (),
                    (Inspectable::List(in_list), Step::Nth(idx)) => {
                        let item = in_list.items.$get(*idx)?;
                        return item.$name(steps, pc + 1);
                    },
                    (Inspectable::List(in_list), Step::Search(_)) => {
                        return in_list
                            .items
                            .$iter()
                            .find_map(|item| item.$name(steps, pc));
                        },

                        (Inspectable::Dict(_), Step::Key) => (),
                        (Inspectable::Dict(_), Step::Value) => (),
                        (Inspectable::Dict(in_dict), Step::Nth(idx)) => {
                            let entry = in_dict.items.$get(*idx)?;
                            return descend_into_entry(entry);
                        },
                        (Inspectable::Dict(in_dict), Step::Entry(key)) => {
                            let entry = in_dict.items.$iter().find(|entry| {
                                let entry_key = if let Inspectable::String(x) = &entry.key {
                                    x
                                } else {
                                    return false;
                                };
                                entry_key.bytes == *key
                            })?;
                            return descend_into_entry(entry);
                        },
                        (Inspectable::Dict(in_dict), Step::Search(Search::DictKey(key))) => {
                            return in_dict.items.$iter().find_map(|entry| {
                                if let Inspectable::String(x) = &entry.key {
                                    if x.bytes == *key {
                                        return descend_into_entry(entry);
                                    }
                                }
                                entry.value.$name(steps, pc)
                            });
                        },
                        (Inspectable::Dict(in_dict), Step::Search(_)) => {
                            return in_dict
                                .items
                                .$iter()
                                .find_map(|InDictEntry { value, .. }| value.$name(steps, pc));
                            },
                };
                None
            }
        }
    )*};
}

finders!(
    (find_impl, get_mut, iter_mut, mut)
    (find_ref_impl, get, iter,)
);

macro_rules! variant_accessors {
    ($(($name:ident, $mutname:ident, $source:ident, $target:ty, $targettype:ty))*) => {$(
        impl<'obj, 'ser> Inspectable<'ser> {
            #[doc=concat!("Coercion to immutable reference to [`", stringify!($targettype), "`]. Panics on failure.")]
            pub fn $name(&'obj self) -> &'obj $target {
                match self {
                    Inspectable::$source(x) => x,
                    _ => panic!("Attempted to take non-{} Inspectable as {}", stringify!($source), stringify!($target))
                }
            }
            #[doc=concat!("Coercion to mutable reference to [`", stringify!($targettype), "`]. Panics on failure.")]
            pub fn $mutname(&'obj mut self) -> &'obj mut $target {
                match self {
                    Inspectable::$source(x) => x,
                    _ => panic!("Attempted to take non-{} Inspectable as mut_{}", stringify!($source), stringify!($target))
                }
            }
        }
    )*};
}

variant_accessors! {
    (string_ref, string, String, InString<'ser>, InString)
    (int_ref, int, Int, InInt<'ser>, InInt)
    (raw_ref, raw, Raw, Cow<'ser, [u8]>, [u8])
    (dict_ref, dict, Dict, InDict<'ser>, InDict)
    (list_ref, list, List, InList<'ser>, InList)
}

impl<'obj, 'ser> InList<'ser> {
    pub fn nth_ref(&'obj self, idx: usize) -> &'obj Inspectable<'ser> {
        self.items
            .get(idx)
            .expect("Could not access nth Inspectable in list")
    }

    pub fn nth(&'obj mut self, idx: usize) -> &'obj mut Inspectable<'ser> {
        self.items
            .get_mut(idx)
            .expect("Could not mutably access nth Inspectable in list")
    }
}

impl<'obj, 'ser> InDict<'ser> {
    pub fn nth_ref(&'obj self, idx: usize) -> &'obj InDictEntry<'ser> {
        self.items
            .get(idx)
            .expect("Could not access nth Inspectable in list")
    }

    pub fn nth(&'obj mut self, idx: usize) -> &'obj mut InDictEntry<'ser> {
        self.items
            .get_mut(idx)
            .expect("Could not mutably access nth Inspectable in list")
    }
}

impl<'obj, 'ser, 'other> InDict<'ser> {
    pub fn entry_ref(&'obj self, name: &'other [u8]) -> &'obj InDictEntry<'ser> {
        self.items
            .iter()
            .find(|InDictEntry { key, .. }| key.string_ref().bytes == name)
            .expect("Could not find a Dict Entry with requested key")
    }

    pub fn entry(&'obj mut self, name: &'other [u8]) -> &'obj mut InDictEntry<'ser> {
        self.items
            .iter_mut()
            .find(|InDictEntry { key, .. }| key.string_ref().bytes == name)
            .expect("Could not find a Dict Entry with requested key")
    }
}