| 1 | //! Methods for mutating [`Inspectable`]s. |
| 2 | //! |
| 3 | //! Refer to the [documentation here][crate::inspect#mutating]. |
| 4 | |
| 5 | use core::ops::RangeBounds; |
| 6 | |
| 7 | use crate::inspect::*; |
| 8 | |
| 9 | impl<'ser, 'obj, 'otherser> Inspectable<'ser> |
| 10 | where |
| 11 | 'otherser: 'ser, |
| 12 | { |
| 13 | // Replaces one Inspectable with another. The replacement |
| 14 | // must have a lifetime at least as long as the one it is |
| 15 | // replacing. |
| 16 | pub fn replace(&'obj mut self, other: Inspectable<'otherser>) { |
| 17 | *self = other; |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | impl<'ser, 'obj> Inspectable<'ser> { |
| 22 | /// Clones an Inspectable AST and applies the given function to |
| 23 | /// the node indicated by the given Path on the resulting clone. |
| 24 | /// |
| 25 | /// Panics if the Path fails to find a node. |
| 26 | #[must_use] |
| 27 | pub fn clone_and_mutate<F>( |
| 28 | &'obj self, |
| 29 | path: &crate::inspect::traverse::PathBuilder, |
| 30 | f: F, |
| 31 | ) -> Inspectable<'ser> |
| 32 | where |
| 33 | F: FnOnce(&mut Inspectable<'ser>), |
| 34 | { |
| 35 | let mut c = self.clone(); |
| 36 | c.mutate(path, f); |
| 37 | c |
| 38 | } |
| 39 | |
| 40 | /// Applies the given function to the node in the Inspectable AST indicated by the given Path. |
| 41 | /// |
| 42 | /// Panics if the Path fails to find a node. |
| 43 | pub fn mutate<F>(&'obj mut self, path: &crate::inspect::traverse::PathBuilder, f: F) |
| 44 | where |
| 45 | F: FnOnce(&mut Inspectable<'ser>), |
| 46 | { |
| 47 | self.find(path).apply(f) |
| 48 | } |
| 49 | |
| 50 | /// Applies the given function to the Inspectable |
| 51 | pub fn apply<F>(&'obj mut self, f: F) |
| 52 | where |
| 53 | F: FnOnce(&mut Inspectable<'ser>), |
| 54 | { |
| 55 | f(self); |
| 56 | } |
| 57 | |
| 58 | /// Remove the nth list item or dict entry. |
| 59 | /// |
| 60 | /// Panics if this is not an [`Inspectable::Dict`] or [`Inspectable::List`]. |
| 61 | pub fn remove_nth(&'obj mut self, idx: usize) { |
| 62 | match self { |
| 63 | Inspectable::Dict(x) => x.remove_nth(idx), |
| 64 | Inspectable::List(x) => x.remove_nth(idx), |
| 65 | _ => panic!("Remove Nth mutation only available on Dicts and Lists"), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// Attempts an [`InString::truncate`] operation on the Inspectable. |
| 70 | /// |
| 71 | /// Panics if this is not an [`Inspectable::String`]. |
| 72 | pub fn truncate(&'obj mut self) { |
| 73 | match self { |
| 74 | Inspectable::String(instring) => instring.truncate(), |
| 75 | _ => panic!("Truncate mutation only available on ByteStrings"), |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Attempts an [`InString::set_content_byterange`] operation on the Inspectable. |
| 80 | /// |
| 81 | /// Panics if this is not an [`Inspectable::String`]. |
| 82 | pub fn set_content_byterange<R>(&'obj mut self, range: R, byte: u8) |
| 83 | where |
| 84 | R: RangeBounds<usize>, |
| 85 | { |
| 86 | match self { |
| 87 | Inspectable::String(instring) => instring.set_content_byterange(range, byte), |
| 88 | _ => panic!("Set Content ByteRange mutation only available on ByteStrings"), |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | /// Applies one of the following operations on the Inspectable, depending on its type: |
| 93 | /// * [`InString::clear_content`] |
| 94 | /// * [`InInt::clear_content`] |
| 95 | /// * [`Vec::clear`] for [`Inspectable::Raw`] |
| 96 | /// * [`InDict::clear_content`] |
| 97 | /// * [`InList::clear_content`] |
| 98 | pub fn clear_content(&'obj mut self) { |
| 99 | match self { |
| 100 | Inspectable::String(x) => x.clear_content(), |
| 101 | Inspectable::Int(x) => x.clear_content(), |
| 102 | Inspectable::Raw(x) => x.to_mut().clear(), |
| 103 | Inspectable::Dict(x) => x.clear_content(), |
| 104 | Inspectable::List(x) => x.clear_content(), |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | impl<'ser, 'obj, 'other> Inspectable<'ser> { |
| 110 | /// Removes all entries in the dict with the given key. |
| 111 | /// Note that it's normally an error for a bencode dict to have |
| 112 | /// multiple identical keys. |
| 113 | /// |
| 114 | /// Assumes that all entries' keys are Byte Strings, which is |
| 115 | /// also required for valid bencode. |
| 116 | pub fn remove_entry(&'obj mut self, dict_key: &'other [u8]) { |
| 117 | match self { |
| 118 | Inspectable::Dict(x) => x.remove_entry(dict_key), |
| 119 | _ => panic!("Remove Entry mutation only available on Dicts"), |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | impl<'ser, 'obj> InInt<'ser> { |
| 125 | /// Sets the InInt to a specified i64 value. |
| 126 | /// Allocates a String. |
| 127 | pub fn set(&'obj mut self, value: i64) { |
| 128 | *self.bytes.to_mut() = value.to_string(); |
| 129 | } |
| 130 | |
| 131 | /// Set the integer to 0. |
| 132 | pub fn clear_content(&'obj mut self) { |
| 133 | self.set(0); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | impl<'ser, 'obj> InDict<'ser> { |
| 138 | /// Sets the InInt to a specified i64 value. |
| 139 | /// Allocates a String. |
| 140 | pub fn clear_content(&'obj mut self) { |
| 141 | self.items.clear(); |
| 142 | } |
| 143 | |
| 144 | /// Remove the nth entry in the dict. |
| 145 | pub fn remove_nth(&'obj mut self, idx: usize) { |
| 146 | self.items.remove(idx); |
| 147 | } |
| 148 | |
| 149 | /// Sorts the dictionary's entries by key, so that valid bencode is |
| 150 | /// produced (assuming no other problems, like duplicate keys.) |
| 151 | /// |
| 152 | /// Assumes all entries' keys are byte strings ([`Inspectable::String`] |
| 153 | /// objects). Panics otherwise. |
| 154 | /// |
| 155 | /// # Example |
| 156 | /// ``` |
| 157 | /// # use bendy::inspect::*; |
| 158 | /// let mut d = Inspectable::new_dict(); |
| 159 | /// d.dict().items.push(InDictEntry::new( |
| 160 | /// Inspectable::new_string(b"zzz"), |
| 161 | /// Inspectable::new_int(1), |
| 162 | /// )); |
| 163 | /// d.dict().items.push(InDictEntry::new( |
| 164 | /// Inspectable::new_string(b"aaa"), |
| 165 | /// Inspectable::new_int(0), |
| 166 | /// )); |
| 167 | /// d.dict().sort(); |
| 168 | /// assert_eq!(&d.emit(), b"d3:aaai0e3:zzzi1ee"); |
| 169 | /// ``` |
| 170 | pub fn sort(&'obj mut self) { |
| 171 | self.items.sort_unstable_by(|a, b| { |
| 172 | let a = &*a.key.string_ref().bytes; |
| 173 | let b = &*b.key.string_ref().bytes; |
| 174 | a.cmp(b) |
| 175 | }); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | impl<'ser, 'obj, 'other> InDict<'ser> { |
| 180 | /// Removes all entries in the dict with the given key. |
| 181 | /// Note that it's normally an error for a bencode dict to have |
| 182 | /// multiple identical keys. |
| 183 | /// |
| 184 | /// Assumes that all entries' keys are Byte Strings, which is |
| 185 | /// also required for valid bencode. |
| 186 | pub fn remove_entry(&'obj mut self, dict_key: &'other [u8]) { |
| 187 | self.items |
| 188 | .retain(|entry| entry.key.string_ref().bytes != dict_key); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | impl<'ser, 'obj> InList<'ser> { |
| 193 | /// Empties the list. |
| 194 | pub fn clear_content(&'obj mut self) { |
| 195 | self.items.clear(); |
| 196 | } |
| 197 | |
| 198 | /// Removes the nth item in the list. |
| 199 | pub fn remove_nth(&'obj mut self, idx: usize) { |
| 200 | self.items.remove(idx); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | impl<'ser, 'obj> InString<'ser> { |
| 205 | /// Set a fake length for the bytestring. This will change |
| 206 | /// its length prefix when emitted as bencode. |
| 207 | pub fn set_fake_length(&'obj mut self, length: usize) { |
| 208 | self.fake_length = Some(length); |
| 209 | } |
| 210 | |
| 211 | /// Unset the fake length. This will cause the length |
| 212 | /// prefix to be correctly calculated and used when |
| 213 | /// emitted as bencode. |
| 214 | pub fn clear_fake_length(&'obj mut self) { |
| 215 | self.fake_length = None; |
| 216 | } |
| 217 | |
| 218 | /// Change the contents of the bytestring. Takes a string |
| 219 | /// which is coerced into a [`Vec<u8>`]. |
| 220 | pub fn set_content_string(&'obj mut self, other: String) { |
| 221 | self.bytes = Cow::Owned(other.into()); |
| 222 | } |
| 223 | |
| 224 | /// Change the contents of the bytestring. |
| 225 | pub fn set_content_vec(&'obj mut self, other: Vec<u8>) { |
| 226 | self.bytes = Cow::Owned(other); |
| 227 | } |
| 228 | |
| 229 | /// Truncates the bytestring to half its size. Empties it |
| 230 | /// if the bytestring is too short to be truncated. |
| 231 | pub fn truncate(&'obj mut self) { |
| 232 | let bytes = self.bytes.to_mut(); |
| 233 | let len = bytes.len(); |
| 234 | let new_len = len / 2; |
| 235 | if len <= new_len { |
| 236 | bytes.clear(); |
| 237 | return; |
| 238 | } |
| 239 | bytes.truncate(new_len); |
| 240 | } |
| 241 | |
| 242 | /// Empties the bytestring. Unless a fake length has been set, |
| 243 | /// this will emit as the bencode `0:`. |
| 244 | pub fn clear_content(&'obj mut self) { |
| 245 | self.bytes.to_mut().clear(); |
| 246 | } |
| 247 | |
| 248 | /// Set the specified [`Range`][std::ops::Range] of bytes in the bytestring to a specified byte. |
| 249 | pub fn set_content_byterange<R>(&'obj mut self, range: R, byte: u8) |
| 250 | where |
| 251 | R: RangeBounds<usize>, |
| 252 | { |
| 253 | let len = self.bytes.len(); |
| 254 | let (start, stop) = normalize_range(range, len); |
| 255 | let bytes = self.bytes.to_mut(); |
| 256 | for i in start..stop { |
| 257 | let mref = bytes |
| 258 | .get_mut(i) |
| 259 | .expect("Tried to replace byte outside of ByteString"); |
| 260 | *mref = byte; |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | impl<'me, 'other, 'ser> InString<'ser> |
| 266 | where |
| 267 | 'other: 'ser, |
| 268 | { |
| 269 | /// Change the contents of the bytestring. Takes an [`&str`] |
| 270 | /// and stores a reference to its raw bytes in a [`Cow`]. |
| 271 | pub fn set_content_str(&'me mut self, other: &'other str) { |
| 272 | self.bytes = Cow::from(other.as_bytes()); |
| 273 | } |
| 274 | |
| 275 | /// Change the contents of the bytestring. Takes a |
| 276 | /// reference to raw bytes and stores them in a [`Cow`]. |
| 277 | pub fn set_content_u8(&'me mut self, other: &'other [u8]) { |
| 278 | self.bytes = Cow::from(other); |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // Not happy about this. Couldn't find a way to get an iterator from a `RangeBounds`. |
| 283 | // And the `Range` type doesn't allow e.g. `..`, `4..`, `..49`, `2..=6` etc to be used. |
| 284 | fn normalize_range<R>(range: R, max_end: usize) -> (usize, usize) |
| 285 | where |
| 286 | R: RangeBounds<usize>, |
| 287 | { |
| 288 | // Unstable for now. See: https://github.com/rust-lang/rust/issues/137300 |
| 289 | // if range.is_empty() { |
| 290 | // panic!("Can't set byterange contents with an empty range"); |
| 291 | // } |
| 292 | |
| 293 | let beg = range.start_bound(); |
| 294 | let end = range.end_bound(); |
| 295 | |
| 296 | let start = match beg { |
| 297 | core::ops::Bound::Included(n) => *n, |
| 298 | // Excluded start bound can't be expressed using the range |
| 299 | // syntax, so I haven't tested it. Probably doesn't matter? |
| 300 | core::ops::Bound::Excluded(n) => n + 1, |
| 301 | core::ops::Bound::Unbounded => 0, |
| 302 | }; |
| 303 | |
| 304 | let stop = match end { |
| 305 | core::ops::Bound::Included(n) => *n + 1, |
| 306 | core::ops::Bound::Excluded(n) => *n, |
| 307 | core::ops::Bound::Unbounded => max_end, |
| 308 | }; |
| 309 | |
| 310 | if start >= stop { |
| 311 | panic!("Can't set byterange contents with an empty range"); |
| 312 | } |
| 313 | |
| 314 | (start, stop) |
| 315 | } |
| 316 | |
| 317 | #[cfg(test)] |
| 318 | mod tests { |
| 319 | use super::*; |
| 320 | |
| 321 | #[test] |
| 322 | fn set_byterange_test() { |
| 323 | let mut i = inspect(b"5:AAAAA"); |
| 324 | assert_eq!(5, i.string().bytes.len()); |
| 325 | |
| 326 | i.string().set_content_byterange(.., b'0'); |
| 327 | assert_eq!(b"5:00000", i.emit().as_slice()); |
| 328 | |
| 329 | let mut i = inspect(b"5:AAAAA"); |
| 330 | i.string().set_content_byterange(0.., b'0'); |
| 331 | assert_eq!(b"5:00000", i.emit().as_slice()); |
| 332 | |
| 333 | let mut i = inspect(b"5:AAAAA"); |
| 334 | i.string().set_content_byterange(0..=4, b'0'); |
| 335 | assert_eq!(b"5:00000", i.emit().as_slice()); |
| 336 | |
| 337 | let mut i = inspect(b"5:AAAAA"); |
| 338 | i.string().set_content_byterange(0..5, b'0'); |
| 339 | assert_eq!(b"5:00000", i.emit().as_slice()); |
| 340 | |
| 341 | let mut i = inspect(b"5:AAAAA"); |
| 342 | i.string().set_content_byterange(0..=0, b'0'); |
| 343 | assert_eq!(b"5:0AAAA", i.emit().as_slice()); |
| 344 | |
| 345 | let mut i = inspect(b"5:AAAAA"); |
| 346 | i.string().set_content_byterange(0..1, b'0'); |
| 347 | assert_eq!(b"5:0AAAA", i.emit().as_slice()); |
| 348 | |
| 349 | let mut i = inspect(b"5:AAAAA"); |
| 350 | i.string().set_content_byterange(0..=1, b'0'); |
| 351 | assert_eq!(b"5:00AAA", i.emit().as_slice()); |
| 352 | |
| 353 | let mut i = inspect(b"5:AAAAA"); |
| 354 | i.string().set_content_byterange(0..2, b'0'); |
| 355 | assert_eq!(b"5:00AAA", i.emit().as_slice()); |
| 356 | |
| 357 | let mut i = inspect(b"5:AAAAA"); |
| 358 | i.string().set_content_byterange(0..3, b'0'); |
| 359 | assert_eq!(b"5:000AA", i.emit().as_slice()); |
| 360 | |
| 361 | let mut i = inspect(b"5:AAAAA"); |
| 362 | i.string().set_content_byterange(0..4, b'0'); |
| 363 | assert_eq!(b"5:0000A", i.emit().as_slice()); |
| 364 | |
| 365 | let mut i = inspect(b"5:AAAAA"); |
| 366 | i.string().set_content_byterange(2..4, b'0'); |
| 367 | assert_eq!(b"5:AA00A", i.emit().as_slice()); |
| 368 | |
| 369 | let mut i = inspect(b"5:AAAAA"); |
| 370 | i.string().set_content_byterange(2..5, b'0'); |
| 371 | assert_eq!(b"5:AA000", i.emit().as_slice()); |
| 372 | } |
| 373 | |
| 374 | #[test] |
| 375 | #[should_panic] |
| 376 | fn empty_0() { |
| 377 | let mut i = inspect(b"5:AAAAA"); |
| 378 | i.string().set_content_byterange(0..0, b'0'); |
| 379 | } |
| 380 | |
| 381 | #[test] |
| 382 | #[should_panic] |
| 383 | fn empty_1() { |
| 384 | let mut i = inspect(b"5:AAAAA"); |
| 385 | i.string().set_content_byterange(1..1, b'0'); |
| 386 | } |
| 387 | |
| 388 | #[test] |
| 389 | #[should_panic] |
| 390 | fn empty_reversed() { |
| 391 | let mut i = inspect(b"5:AAAAA"); |
| 392 | i.string().set_content_byterange(5..1, b'0'); |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | #[should_panic] |
| 397 | fn out_of_bounds_range_inclusive() { |
| 398 | let mut i = inspect(b"5:AAAAA"); |
| 399 | i.string().set_content_byterange(2..=5, b'0'); |
| 400 | } |
| 401 | |
| 402 | #[test] |
| 403 | #[should_panic] |
| 404 | fn out_of_bounds_range() { |
| 405 | let mut i = inspect(b"5:AAAAA"); |
| 406 | i.string().set_content_byterange(2..6, b'0'); |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn replace_test() { |
| 411 | let buf = b"\ |
| 412 | l\ |
| 413 | i99e\ |
| 414 | 5:hello\ |
| 415 | d\ |
| 416 | 3:one\ |
| 417 | i11e\ |
| 418 | 3:two\ |
| 419 | i22e\ |
| 420 | e\ |
| 421 | e"; |
| 422 | let mut i = inspect(buf); |
| 423 | let l = i.list(); |
| 424 | l.nth(0).replace(Inspectable::new_string(b"aaa")); |
| 425 | l.nth(1).replace(inspect(b"li1ei2ei3ee")); |
| 426 | l.nth(2).replace(Inspectable::new_int(5)); |
| 427 | assert_eq!(b"l3:aaali1ei2ei3eei5ee", i.emit().as_slice()); |
| 428 | } |
| 429 | } |