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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Methods for mutating [`Inspectable`]s.
//!
//! Refer to the [documentation here][crate::inspect#mutating].
use core::ops::RangeBounds;
use crate::inspect::*;
impl<'ser, 'obj, 'otherser> Inspectable<'ser>
where
'otherser: 'ser,
{
// Replaces one Inspectable with another. The replacement
// must have a lifetime at least as long as the one it is
// replacing.
pub fn replace(&'obj mut self, other: Inspectable<'otherser>) {
*self = other;
}
}
impl<'ser, 'obj> Inspectable<'ser> {
/// Clones an Inspectable AST and applies the given function to
/// the node indicated by the given Path on the resulting clone.
///
/// Panics if the Path fails to find a node.
#[must_use]
pub fn clone_and_mutate<F>(
&'obj self,
path: &crate::inspect::traverse::PathBuilder,
f: F,
) -> Inspectable<'ser>
where
F: FnOnce(&mut Inspectable<'ser>),
{
let mut c = self.clone();
c.mutate(path, f);
c
}
/// Applies the given function to the node in the Inspectable AST indicated by the given Path.
///
/// Panics if the Path fails to find a node.
pub fn mutate<F>(&'obj mut self, path: &crate::inspect::traverse::PathBuilder, f: F)
where
F: FnOnce(&mut Inspectable<'ser>),
{
self.find(path).apply(f)
}
/// Applies the given function to the Inspectable
pub fn apply<F>(&'obj mut self, f: F)
where
F: FnOnce(&mut Inspectable<'ser>),
{
f(self);
}
/// Remove the nth list item or dict entry.
///
/// Panics if this is not an [`Inspectable::Dict`] or [`Inspectable::List`].
pub fn remove_nth(&'obj mut self, idx: usize) {
match self {
Inspectable::Dict(x) => x.remove_nth(idx),
Inspectable::List(x) => x.remove_nth(idx),
_ => panic!("Remove Nth mutation only available on Dicts and Lists"),
}
}
/// Attempts an [`InString::truncate`] operation on the Inspectable.
///
/// Panics if this is not an [`Inspectable::String`].
pub fn truncate(&'obj mut self) {
match self {
Inspectable::String(instring) => instring.truncate(),
_ => panic!("Truncate mutation only available on ByteStrings"),
}
}
/// Attempts an [`InString::set_content_byterange`] operation on the Inspectable.
///
/// Panics if this is not an [`Inspectable::String`].
pub fn set_content_byterange<R>(&'obj mut self, range: R, byte: u8)
where
R: RangeBounds<usize>,
{
match self {
Inspectable::String(instring) => instring.set_content_byterange(range, byte),
_ => panic!("Set Content ByteRange mutation only available on ByteStrings"),
}
}
/// Applies one of the following operations on the Inspectable, depending on its type:
/// * [`InString::clear_content`]
/// * [`InInt::clear_content`]
/// * [`Vec::clear`] for [`Inspectable::Raw`]
/// * [`InDict::clear_content`]
/// * [`InList::clear_content`]
pub fn clear_content(&'obj mut self) {
match self {
Inspectable::String(x) => x.clear_content(),
Inspectable::Int(x) => x.clear_content(),
Inspectable::Raw(x) => x.to_mut().clear(),
Inspectable::Dict(x) => x.clear_content(),
Inspectable::List(x) => x.clear_content(),
}
}
}
impl<'ser, 'obj, 'other> Inspectable<'ser> {
/// Removes all entries in the dict with the given key.
/// Note that it's normally an error for a bencode dict to have
/// multiple identical keys.
///
/// Assumes that all entries' keys are Byte Strings, which is
/// also required for valid bencode.
pub fn remove_entry(&'obj mut self, dict_key: &'other [u8]) {
match self {
Inspectable::Dict(x) => x.remove_entry(dict_key),
_ => panic!("Remove Entry mutation only available on Dicts"),
}
}
}
impl<'ser, 'obj> InInt<'ser> {
/// Sets the InInt to a specified i64 value.
/// Allocates a String.
pub fn set(&'obj mut self, value: i64) {
*self.bytes.to_mut() = value.to_string();
}
/// Set the integer to 0.
pub fn clear_content(&'obj mut self) {
self.set(0);
}
}
impl<'ser, 'obj> InDict<'ser> {
/// Sets the InInt to a specified i64 value.
/// Allocates a String.
pub fn clear_content(&'obj mut self) {
self.items.clear();
}
/// Remove the nth entry in the dict.
pub fn remove_nth(&'obj mut self, idx: usize) {
self.items.remove(idx);
}
/// Sorts the dictionary's entries by key, so that valid bencode is
/// produced (assuming no other problems, like duplicate keys.)
///
/// Assumes all entries' keys are byte strings ([`Inspectable::String`]
/// objects). Panics otherwise.
///
/// # Example
/// ```
/// # use bendy::inspect::*;
/// let mut d = Inspectable::new_dict();
/// d.dict().items.push(InDictEntry::new(
/// Inspectable::new_string(b"zzz"),
/// Inspectable::new_int(1),
/// ));
/// d.dict().items.push(InDictEntry::new(
/// Inspectable::new_string(b"aaa"),
/// Inspectable::new_int(0),
/// ));
/// d.dict().sort();
/// assert_eq!(&d.emit(), b"d3:aaai0e3:zzzi1ee");
/// ```
pub fn sort(&'obj mut self) {
self.items.sort_unstable_by(|a, b| {
let a = &*a.key.string_ref().bytes;
let b = &*b.key.string_ref().bytes;
a.cmp(b)
});
}
}
impl<'ser, 'obj, 'other> InDict<'ser> {
/// Removes all entries in the dict with the given key.
/// Note that it's normally an error for a bencode dict to have
/// multiple identical keys.
///
/// Assumes that all entries' keys are Byte Strings, which is
/// also required for valid bencode.
pub fn remove_entry(&'obj mut self, dict_key: &'other [u8]) {
self.items
.retain(|entry| entry.key.string_ref().bytes != dict_key);
}
}
impl<'ser, 'obj> InList<'ser> {
/// Empties the list.
pub fn clear_content(&'obj mut self) {
self.items.clear();
}
/// Removes the nth item in the list.
pub fn remove_nth(&'obj mut self, idx: usize) {
self.items.remove(idx);
}
}
impl<'ser, 'obj> InString<'ser> {
/// Set a fake length for the bytestring. This will change
/// its length prefix when emitted as bencode.
pub fn set_fake_length(&'obj mut self, length: usize) {
self.fake_length = Some(length);
}
/// Unset the fake length. This will cause the length
/// prefix to be correctly calculated and used when
/// emitted as bencode.
pub fn clear_fake_length(&'obj mut self) {
self.fake_length = None;
}
/// Change the contents of the bytestring. Takes a string
/// which is coerced into a [`Vec<u8>`].
pub fn set_content_string(&'obj mut self, other: String) {
self.bytes = Cow::Owned(other.into());
}
/// Change the contents of the bytestring.
pub fn set_content_vec(&'obj mut self, other: Vec<u8>) {
self.bytes = Cow::Owned(other);
}
/// Truncates the bytestring to half its size. Empties it
/// if the bytestring is too short to be truncated.
pub fn truncate(&'obj mut self) {
let bytes = self.bytes.to_mut();
let len = bytes.len();
let new_len = len / 2;
if len <= new_len {
bytes.clear();
return;
}
bytes.truncate(new_len);
}
/// Empties the bytestring. Unless a fake length has been set,
/// this will emit as the bencode `0:`.
pub fn clear_content(&'obj mut self) {
self.bytes.to_mut().clear();
}
/// Set the specified [`Range`][std::ops::Range] of bytes in the bytestring to a specified byte.
pub fn set_content_byterange<R>(&'obj mut self, range: R, byte: u8)
where
R: RangeBounds<usize>,
{
let len = self.bytes.len();
let (start, stop) = normalize_range(range, len);
let bytes = self.bytes.to_mut();
for i in start..stop {
let mref = bytes
.get_mut(i)
.expect("Tried to replace byte outside of ByteString");
*mref = byte;
}
}
}
impl<'me, 'other, 'ser> InString<'ser>
where
'other: 'ser,
{
/// Change the contents of the bytestring. Takes an [`&str`]
/// and stores a reference to its raw bytes in a [`Cow`].
pub fn set_content_str(&'me mut self, other: &'other str) {
self.bytes = Cow::from(other.as_bytes());
}
/// Change the contents of the bytestring. Takes a
/// reference to raw bytes and stores them in a [`Cow`].
pub fn set_content_u8(&'me mut self, other: &'other [u8]) {
self.bytes = Cow::from(other);
}
}
// Not happy about this. Couldn't find a way to get an iterator from a `RangeBounds`.
// And the `Range` type doesn't allow e.g. `..`, `4..`, `..49`, `2..=6` etc to be used.
fn normalize_range<R>(range: R, max_end: usize) -> (usize, usize)
where
R: RangeBounds<usize>,
{
// Unstable for now. See: https://github.com/rust-lang/rust/issues/137300
// if range.is_empty() {
// panic!("Can't set byterange contents with an empty range");
// }
let beg = range.start_bound();
let end = range.end_bound();
let start = match beg {
core::ops::Bound::Included(n) => *n,
// Excluded start bound can't be expressed using the range
// syntax, so I haven't tested it. Probably doesn't matter?
core::ops::Bound::Excluded(n) => n + 1,
core::ops::Bound::Unbounded => 0,
};
let stop = match end {
core::ops::Bound::Included(n) => *n + 1,
core::ops::Bound::Excluded(n) => *n,
core::ops::Bound::Unbounded => max_end,
};
if start >= stop {
panic!("Can't set byterange contents with an empty range");
}
(start, stop)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn set_byterange_test() {
let mut i = inspect(b"5:AAAAA");
assert_eq!(5, i.string().bytes.len());
i.string().set_content_byterange(.., b'0');
assert_eq!(b"5:00000", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0.., b'0');
assert_eq!(b"5:00000", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..=4, b'0');
assert_eq!(b"5:00000", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..5, b'0');
assert_eq!(b"5:00000", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..=0, b'0');
assert_eq!(b"5:0AAAA", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..1, b'0');
assert_eq!(b"5:0AAAA", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..=1, b'0');
assert_eq!(b"5:00AAA", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..2, b'0');
assert_eq!(b"5:00AAA", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..3, b'0');
assert_eq!(b"5:000AA", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..4, b'0');
assert_eq!(b"5:0000A", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(2..4, b'0');
assert_eq!(b"5:AA00A", i.emit().as_slice());
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(2..5, b'0');
assert_eq!(b"5:AA000", i.emit().as_slice());
}
#[test]
#[should_panic]
fn empty_0() {
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(0..0, b'0');
}
#[test]
#[should_panic]
fn empty_1() {
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(1..1, b'0');
}
#[test]
#[should_panic]
fn empty_reversed() {
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(5..1, b'0');
}
#[test]
#[should_panic]
fn out_of_bounds_range_inclusive() {
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(2..=5, b'0');
}
#[test]
#[should_panic]
fn out_of_bounds_range() {
let mut i = inspect(b"5:AAAAA");
i.string().set_content_byterange(2..6, b'0');
}
#[test]
fn replace_test() {
let buf = b"\
l\
i99e\
5:hello\
d\
3:one\
i11e\
3:two\
i22e\
e\
e";
let mut i = inspect(buf);
let l = i.list();
l.nth(0).replace(Inspectable::new_string(b"aaa"));
l.nth(1).replace(inspect(b"li1ei2ei3ee"));
l.nth(2).replace(Inspectable::new_int(5));
assert_eq!(b"l3:aaali1ei2ei3eei5ee", i.emit().as_slice());
}
}