pkbuffer 0.7.0

Buffer objects made for arbitrary casting and addressing!
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
use crate::Error;
use memchr::memmem;

/// The trait by which all buffer objects are derived.
pub trait Buffer {
    /// Get the length of this `Buffer` object.
    fn len(&self) -> usize;
    /// Get the `Buffer` object as a pointer.
    fn as_ptr(&self) -> *const u8;
    /// Get the `Buffer` object as a mutable pointer.
    fn as_mut_ptr(&mut self) -> *mut u8;
    /// Get the `Buffer` object as a slice.
    fn as_slice(&self) -> &[u8];
    /// Get the `Buffer` object as a mutable slice.
    fn as_mut_slice(&mut self) -> &mut [u8];

    /// Get a pointer to the end of the buffer.
    ///
    /// Note that this pointer is not safe to use because it points at the very end of
    /// the buffer, which contains no data. It is merely a reference pointer for calculations
    /// such as boundaries and size.
    fn eob(&self) -> *const u8 {
        unsafe { self.as_ptr().add(self.len()) }
    }
    /// Get a pointer range of this buffer. See [slice::as_ptr_range](slice::as_ptr_range) for more details.
    fn as_ptr_range(&self) -> std::ops::Range<*const u8> {
        std::ops::Range::<*const u8> { start: self.as_ptr(), end: self.eob() }
    }
    /// Get a mutable pointer range of this buffer. See [slice::as_mut_ptr_range](slice::as_mut_ptr_range) for more details.
    fn as_mut_ptr_range(&mut self) -> std::ops::Range<*mut u8> {
        std::ops::Range::<*mut u8> { start: self.as_mut_ptr(), end: self.eob() as *mut u8 }
    }
    /// Check whether or not this buffer is empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Validate that the given *pointer* object is within the range of this buffer.
    fn validate_ptr(&self, ptr: *const u8) -> bool {
        self.as_ptr_range().contains(&ptr)
    }
    /// Convert an *offset* to a [`u8`](u8) pointer.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the offset is out of bounds
    /// of the buffer.
    fn offset_to_ptr(&self, offset: usize) -> Result<*const u8, Error> {
        if offset >= self.len() {
            return Err(Error::OutOfBounds(self.len(),offset));
        }

        unsafe { Ok(self.as_ptr().add(offset)) }
    }
    /// Convert an *offset* to a mutable [`u8`](u8) pointer.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the offset is out of bounds
    /// of the buffer.
    fn offset_to_mut_ptr(&mut self, offset: usize) -> Result<*mut u8, Error> {
        if offset >= self.len() {
            return Err(Error::OutOfBounds(self.len(),offset));
        }

        unsafe { Ok(self.as_mut_ptr().add(offset)) }
    }
    /// Convert a *pointer* to an offset into the buffer.
    ///
    /// Returns an [`Error::InvalidPointer`](Error::InvalidPointer) error if the given pointer is not
    /// within the range of this buffer.
    fn ptr_to_offset(&self, ptr: *const u8) -> Result<usize, Error> {
        if !self.validate_ptr(ptr) { return Err(Error::InvalidPointer(ptr)); }

        Ok(ptr as usize - self.as_ptr() as usize)
    }
    /// Convert this buffer to a [`u8`](u8) [`Vec`](Vec) object.
    fn to_vec(&self) -> Vec<u8> {
        self.as_slice().to_vec()
    }
    /// Swap two bytes at the given offsets. This panics if the offsets are out of bounds. See [`slice::swap`](slice::swap)
    /// for more details.
    fn swap(&mut self, a: usize, b: usize) {
        self.as_mut_slice().swap(a, b);
    }
    /// Swap two bytes at the given offsets.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if either offset is out of bounds.
    fn try_swap(&mut self, a: usize, b: usize) -> Result<(), Error> {
        if a >= self.len() { return Err(Error::OutOfBounds(self.len(), a)); }
        if b >= self.len() { return Err(Error::OutOfBounds(self.len(), b)); }
        self.as_mut_slice().swap(a, b);
        Ok(())
    }
    /// Reverse the buffer. See [`slice::reverse`](slice::reverse) for more details.
    fn reverse(&mut self) {
        self.as_mut_slice().reverse();
    }
    /// Reverse the buffer, returning an error on failure.
    ///
    /// Currently this cannot fail, but is provided for API consistency.
    fn try_reverse(&mut self) -> Result<(), Error> {
        self.as_mut_slice().reverse();
        Ok(())
    }
    /// Return an iterator object ([`BufferIter`](BufferIter)) into the buffer.
    fn iter(&self) -> BufferIter<'_> {
        BufferIter { buffer: self.as_slice(), index: 0 }
    }
    /// Return a mutable iterator object ([`BufferIterMut`](BufferIterMut)) into the buffer.
    fn iter_mut(&mut self) -> BufferIterMut<'_> {
        BufferIterMut { buffer: self.as_mut_slice(), index: 0 }
    }
    /// Save this buffer to disk.
    fn save<P: AsRef<std::path::Path>>(&self, filename: P) -> Result<(), Error> {
        std::fs::write(filename, self.as_slice())?;
        Ok(())
    }
    /// Get the given byte or range of bytes from the buffer. See [`slice::get`](slice::get) for more details.
    fn get<I: std::slice::SliceIndex<[u8]>>(&self, index: I) -> Option<&I::Output> {
        self.as_slice().get(index)
    }
    /// Get the given byte or range of bytes from the buffer as mutable. See [`slice::get_mut`](slice::get_mut) for more details.
    fn get_mut<I: std::slice::SliceIndex<[u8]>>(&mut self, index: I) -> Option<&mut I::Output> {
        self.as_mut_slice().get_mut(index)
    }
    /// Read an arbitrary *size* amount of bytes from the given *offset*.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the read runs out of boundaries.
    fn read(&self, offset: usize, size: usize) -> Result<&[u8], Error> {
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        Ok(&self.as_slice()[offset..offset + size])
    }
    /// Read an arbitrary *size* amount of bytes from the given *offset*, but mutable.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the read runs out of boundaries.
    fn read_mut(&mut self, offset: usize, size: usize) -> Result<&mut [u8], Error> {
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        Ok(&mut self.as_mut_slice()[offset..offset + size])
    }
    /// Read a value of type `T` from the buffer at the given offset, without requiring alignment.
    ///
    /// This uses safe byte-copying to read the value, so it works regardless of alignment.
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the read would go out of bounds.
    fn read_val<T: Copy>(&self, offset: usize) -> Result<T, Error> {
        let size = std::mem::size_of::<T>();
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let bytes = &self.as_slice()[offset..offset + size];

        // Copy bytes safely into the value using zeroed and copy_nonoverlapping
        let mut value: T = unsafe { std::mem::zeroed() };
        unsafe {
            std::ptr::copy_nonoverlapping(bytes.as_ptr(), &mut value as *mut T as *mut u8, size);
        }
        Ok(value)
    }
    /// Read a series of values of type `T` from the buffer at the given offset.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the read would go out of bounds.
    fn read_val_array<T: Copy>(&self, offset: usize, count: usize) -> Result<Vec<T>, Error> {
        let size = std::mem::size_of::<T>() * count;
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let bytes = &self.as_slice()[offset..offset + size];
        let mut result = Vec::with_capacity(count);
        for i in 0..count {
            let mut value: T = unsafe { std::mem::zeroed() };
            let start = i * std::mem::size_of::<T>();
            let _end = start + std::mem::size_of::<T>();
            unsafe {
                std::ptr::copy_nonoverlapping(bytes.as_ptr().add(start), &mut value as *mut T as *mut u8, std::mem::size_of::<T>());
            }
            result.push(value);
        }
        Ok(result)
    }
    /// Get a slice reference of `T` values from the buffer at the given offset.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the read would go out of bounds.
    fn get_slice_ref<T>(&self, offset: usize, count: usize) -> Result<&[T], Error> {
        let size = std::mem::size_of::<T>() * count;
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let ptr = self.offset_to_ptr(offset)?;
        Ok(unsafe { std::slice::from_raw_parts(ptr as *const T, count) })
    }
    /// Get a mutable slice reference of `T` values from the buffer at the given offset.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the read would go out of bounds.
    fn get_mut_slice_ref<T>(&mut self, offset: usize, count: usize) -> Result<&mut [T], Error> {
        let size = std::mem::size_of::<T>() * count;
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let ptr = self.offset_to_mut_ptr(offset)?;
        Ok(unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, count) })
    }
    /// Get a reference to `T` at the given offset, verifying alignment.
    ///
    /// Returns an [`Error::AlignmentMismatch`](Error::AlignmentMismatch) error if the offset
    /// is not aligned for type `T`. Returns an [`Error::OutOfBounds`](Error::OutOfBounds)
    /// error if the read would go out of bounds.
    fn get_aligned_ref<T: Copy>(&self, offset: usize) -> Result<&T, Error> {
        let align = std::mem::align_of::<T>();
        if offset % align != 0 {
            return Err(Error::AlignmentMismatch(offset, align));
        }
        let size = std::mem::size_of::<T>();
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let ptr = self.offset_to_ptr(offset)?;
        Ok(unsafe { &*(ptr as *const T) })
    }
    /// Get a mutable reference to `T` at the given offset, verifying alignment.
    ///
    /// Returns an [`Error::AlignmentMismatch`](Error::AlignmentMismatch) error if the offset
    /// is not aligned for type `T`. Returns an [`Error::OutOfBounds`](Error::OutOfBounds)
    /// error if the read would go out of bounds.
    fn get_aligned_mut<T: Copy>(&mut self, offset: usize) -> Result<&mut T, Error> {
        let align = std::mem::align_of::<T>();
        if offset % align != 0 {
            return Err(Error::AlignmentMismatch(offset, align));
        }
        let size = std::mem::size_of::<T>();
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let ptr = self.offset_to_mut_ptr(offset)?;
        Ok(unsafe { &mut *(ptr as *mut T) })
    }
    /// Write an arbitrary [`u8`](u8) [slice](slice) to the given *offset*.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the write runs out of boundaries
    /// of the buffer.
    fn write<B: AsRef<[u8]>>(&mut self, offset: usize, data: B) -> Result<(), Error> {
        let buf = data.as_ref();
        let from_ptr = buf.as_ptr();
        let to_ptr = self.offset_to_mut_ptr(offset)?;
        let size = buf.len();

        if offset+size > self.len() {
            return Err(Error::OutOfBounds(self.len(),offset+size));
        }

        unsafe { std::ptr::copy(from_ptr, to_ptr, size); }

        Ok(())
    }
    /// Write a value of type `T` to the buffer at the given offset, without requiring alignment.
    ///
    /// This uses safe byte-copying to write the value, so it works regardless of alignment.
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the write would go out of bounds.
    fn write_val<T: Copy>(&mut self, offset: usize, data: &T) -> Result<(), Error> {
        let size = std::mem::size_of::<T>();
        if offset + size > self.len() {
            return Err(Error::OutOfBounds(self.len(), offset + size));
        }
        let from_ptr = data as *const T as *const u8;
        let to_ptr = self.offset_to_mut_ptr(offset)?;
        unsafe {
            std::ptr::copy_nonoverlapping(from_ptr, to_ptr, size);
        }
        Ok(())
    }
    /// Start the buffer object with the given byte data.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the write runs out of boundaries.
    fn start_with<B: AsRef<[u8]>>(&mut self, data: B) -> Result<(), Error> {
        self.write(0, data)
    }
    /// End the buffer object with the given byte data.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the write runs out of boundaries.
    fn end_with<B: AsRef<[u8]>>(&mut self, data: B) -> Result<(), Error> {
        let buf = data.as_ref();

        if buf.len() > self.len() { return Err(Error::OutOfBounds(self.len(),buf.len())); }

        self.write(self.len()-buf.len(), data)
    }
    /// Search for the given [`u8`](u8) [slice](slice) *data* within the given buffer.
    ///
    /// On success, this returns an iterator to all found offsets which match the given search term.
    /// Typically, the error returned is an [`Error::OutOfBounds`](Error::OutOfBounds) error, when the search
    /// term exceeds the size of the buffer.
    fn search<B: AsRef<[u8]>>(&self, data: B) -> Result<BufferSearchIter, Error> {
        BufferSearchIter::new(self.as_slice(), data.as_ref())
    }
    /// Return a search iterator for a dynamic byte pattern within the binary.
    ///
    /// This function uses an [`Option<u8>`](Option) wrapper to represent wildcards in the search terms.
    /// For example, a search term for a four-byte sequence wrapped in `0xFF`, use this:
    ///
    /// ```rust
    /// let search = vec![Some(0xFFu8), None, None, None, None, Some(0xFFu8)];
    /// ```
    ///
    /// For more information about searching, see [`Buffer::search`](Buffer::search).
    fn search_dynamic<'a, B: AsRef<[Option<u8>]>>(&'a self, data: B) -> Result<BufferSearchDynamicIter<'a>, Error> {
        BufferSearchDynamicIter::new(self.as_slice(), data)
    }
    /// Check if this buffer contains the following [`u8`](u8) [slice](slice) sequence.
    fn contains<B: AsRef<[u8]>>(&self, data: B) -> bool {
        let buf = data.as_ref();

        if buf.len() > self.len() { return false; }

        let mut offset = 0usize;

        for i in 0..self.len() {
            if offset >= buf.len() { break; }

            if *self.get(i).unwrap() != buf[offset] { offset = 0; continue; }
            else { offset += 1; }
        }

        offset == buf.len()
    }
    /// Check if this buffer starts with the byte sequence *needle*. See [`slice::starts_with`](slice::starts_with).
    fn starts_with<B: AsRef<[u8]>>(&self, needle: B) -> bool {
        self.as_slice().starts_with(needle.as_ref())
    }
    /// Check if this buffer ends with the byte sequence *needle*. See [`slice::ends_with`](slice::ends_with).
    fn ends_with<B: AsRef<[u8]>>(&self, needle: B) -> bool {
        self.as_slice().ends_with(needle.as_ref())
    }
    /// Rotate the buffer left at midpoint *mid*. See [`slice::rotate_left`](slice::rotate_left).
    fn rotate_left(&mut self, mid: usize) {
        self.as_mut_slice().rotate_left(mid);
    }
    /// Rotate the buffer left at midpoint *mid*.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if *mid* is greater than the buffer length.
    fn try_rotate_left(&mut self, mid: usize) -> Result<(), Error> {
        if mid > self.len() { return Err(Error::OutOfBounds(self.len(), mid)); }
        self.as_mut_slice().rotate_left(mid);
        Ok(())
    }
    /// Rotate the buffer right at midpoint *mid*. See [`slice::rotate_right`](slice::rotate_right).
    fn rotate_right(&mut self, mid: usize) {
        self.as_mut_slice().rotate_right(mid);
    }
    /// Rotate the buffer right at midpoint *mid*.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if *mid* is greater than the buffer length.
    fn try_rotate_right(&mut self, mid: usize) -> Result<(), Error> {
        if mid > self.len() { return Err(Error::OutOfBounds(self.len(), mid)); }
        self.as_mut_slice().rotate_right(mid);
        Ok(())
    }
    /// Fill the given buffer with the given *value*. See [`slice::fill`](slice::fill).
    fn fill(&mut self, value: u8) {
        self.as_mut_slice().fill(value);
    }
    /// Fill the given buffer with the given *value*, returning an error on failure.
    ///
    /// Currently this cannot fail, but is provided for API consistency.
    fn try_fill(&mut self, value: u8) -> Result<(), Error> {
        self.as_mut_slice().fill(value);
        Ok(())
    }
    /// Fill the given buffer with the given closure *f*. See [`slice::fill_with`](slice::fill_with).
    fn fill_with<F>(&mut self, f: F)
    where
        F: FnMut() -> u8
    {
        self.as_mut_slice().fill_with(f)
    }
    /// Fill the given buffer with the given closure *f*, returning an error on failure.
    ///
    /// Currently this cannot fail, but is provided for API consistency.
    fn try_fill_with<F>(&mut self, f: F) -> Result<(), Error>
    where
        F: FnMut() -> u8
    {
        self.as_mut_slice().fill_with(f);
        Ok(())
    }
    /// Clone the given [`u8`](u8) [slice](slice) data *src* into the given buffer.
    fn clone_from_data<B: AsRef<[u8]>>(&mut self, src: B) {
        self.as_mut_slice().clone_from_slice(src.as_ref());
    }
    /// Clone the given [`u8`](u8) [slice](slice) data *src* into the given buffer.
    ///
    /// Returns an [`Error::SizeMismatch`](Error::SizeMismatch) error if the source slice length
    /// does not equal the buffer length.
    fn try_clone_from_data<B: AsRef<[u8]>>(&mut self, src: B) -> Result<(), Error> {
        let src = src.as_ref();
        if src.len() != self.len() { return Err(Error::SizeMismatch(self.len(), src.len())); }
        self.as_mut_slice().clone_from_slice(src);
        Ok(())
    }
    /// Copy the given [`u8`](u8) [slice](slice) data *src* into the given buffer.
    fn copy_from_data<B: AsRef<[u8]>>(&mut self, src: B) {
        self.as_mut_slice().copy_from_slice(src.as_ref());
    }
    /// Copy the given [`u8`](u8) [slice](slice) data *src* into the given buffer.
    ///
    /// Returns an [`Error::SizeMismatch`](Error::SizeMismatch) error if the source slice length
    /// does not equal the buffer length.
    fn try_copy_from_data<B: AsRef<[u8]>>(&mut self, src: B) -> Result<(), Error> {
        let src = src.as_ref();
        if src.len() != self.len() { return Err(Error::SizeMismatch(self.len(), src.len())); }
        self.as_mut_slice().copy_from_slice(src);
        Ok(())
    }
    /// Copy from within the given buffer. See [`slice::copy_within`](slice::copy_within).
    fn copy_within<R>(&mut self, src: R, dest: usize)
    where
        R: std::ops::RangeBounds<usize>
    {
        self.as_mut_slice().copy_within(src, dest)
    }
    /// Copy from within the given buffer.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the source range or
    /// destination offset is out of bounds.
    fn try_copy_within<R>(&mut self, src: R, dest: usize) -> Result<(), Error>
    where
        R: std::ops::RangeBounds<usize>
    {
        use std::ops::Bound;

        let start = match src.start_bound() {
            Bound::Included(i) => *i,
            Bound::Excluded(i) => *i + 1,
            Bound::Unbounded => 0,
        };
        let end = match src.end_bound() {
            Bound::Included(i) => *i + 1,
            Bound::Excluded(i) => *i,
            Bound::Unbounded => self.len(),
        };

        if start > self.len() { return Err(Error::OutOfBounds(self.len(), start)); }
        if end > self.len() { return Err(Error::OutOfBounds(self.len(), end)); }
        if dest > self.len() { return Err(Error::OutOfBounds(self.len(), dest)); }

        self.as_mut_slice().copy_within(src, dest);
        Ok(())
    }
    /// Swap the data in this buffer with the given [`u8`](u8) [slice](slice) reference.
    fn swap_with_data<B: AsMut<[u8]>>(&mut self, mut other: B) {
        self.as_mut_slice().swap_with_slice(other.as_mut());
    }
    /// Swap the data in this buffer with the given [`u8`](u8) [slice](slice) reference.
    ///
    /// Returns an [`Error::SizeMismatch`](Error::SizeMismatch) error if the other slice length
    /// does not equal the buffer length.
    fn try_swap_with_data<B: AsMut<[u8]>>(&mut self, mut other: B) -> Result<(), Error> {
        let other = other.as_mut();
        if other.len() != self.len() { return Err(Error::SizeMismatch(self.len(), other.len())); }
        self.as_mut_slice().swap_with_slice(other);
        Ok(())
    }
    /// Check if this buffer is ASCII. See [`slice::is_ascii`](slice::is_ascii).
    fn is_ascii(&self) -> bool {
        self.as_slice().is_ascii()
    }
    /// Check if this buffer is equal while ignoring case of letters. See [`slice::eq_ignore_ascii_case`](slice::eq_ignore_ascii_case).
    fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
        self.as_slice().eq_ignore_ascii_case(other)
    }
    /// Make this buffer ASCII uppercase. See [`slice::make_ascii_uppercase`](slice::make_ascii_uppercase).
    fn make_ascii_uppercase(&mut self) {
        self.as_mut_slice().make_ascii_uppercase();
    }
    /// Make this buffer ASCII lowercase. See [`slice::make_ascii_lowercase`](slice::make_ascii_lowercase).
    fn make_ascii_lowercase(&mut self) {
        self.as_mut_slice().make_ascii_lowercase();
    }
    /// Sort this buffer. See [`slice::sort`](slice::sort).
    fn sort(&mut self) {
        self.as_mut_slice().sort();
    }
    /// Sort this buffer, returning an error on failure.
    ///
    /// Currently this cannot fail, but is provided for API consistency.
    fn try_sort(&mut self) -> Result<(), Error> {
        self.as_mut_slice().sort();
        Ok(())
    }
    /// Sort by the given closure comparing each individual byte. See [`slice::sort_by`](slice::sort_by).
    fn sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&u8, &u8) -> std::cmp::Ordering
    {
        self.as_mut_slice().sort_by(compare);
    }
    /// Sort by the given closure comparing each individual byte, returning an error on failure.
    ///
    /// Currently this cannot fail, but is provided for API consistency.
    fn try_sort_by<F>(&mut self, compare: F) -> Result<(), Error>
    where
        F: FnMut(&u8, &u8) -> std::cmp::Ordering
    {
        self.as_mut_slice().sort_by(compare);
        Ok(())
    }
    /// Sorts the slice with a key extraction function. See [`slice::sort_by_key`](slice::sort_by_key).
    fn sort_by_key<K, F>(&mut self, f: F)
    where
        F: FnMut(&u8) -> K,
        K: std::cmp::Ord,
    {
        self.as_mut_slice().sort_by_key(f);
    }
    /// Sorts the slice with a key extraction function, returning an error on failure.
    ///
    /// Currently this cannot fail, but is provided for API consistency.
    fn try_sort_by_key<K, F>(&mut self, f: F) -> Result<(), Error>
    where
        F: FnMut(&u8) -> K,
        K: std::cmp::Ord,
    {
        self.as_mut_slice().sort_by_key(f);
        Ok(())
    }
    /// Creates a new `Buffer` object by repeating the current buffer *n* times. See [`slice::repeat`](slice::repeat).
    fn repeat(&self, n: usize) -> Vec<u8> {
        self.as_slice().repeat(n)
    }
    /// Creates a new `Buffer` object by repeating the current buffer *n* times.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the repeat count would cause
    /// arithmetic overflow.
    fn try_repeat(&self, n: usize) -> Result<Vec<u8>, Error> {
        let Some(_len) = self.len().checked_mul(n) else {
            return Err(Error::OutOfBounds(usize::MAX, self.len().saturating_mul(n)));
        };
        Ok(self.as_slice().repeat(n))
    }
}

/// An iterator for a [`Buffer`](Buffer) object.
pub struct BufferIter<'a> {
    buffer: &'a [u8],
    index: usize,
}
impl<'a> BufferIter<'a> {
    /// Creates a new [`Buffer`](Buffer) iterator object.
    pub fn new(buffer: &'a [u8], index: usize) -> Self {
        Self { buffer, index }
    }
}
impl<'a> Iterator for BufferIter<'a> {
    type Item = &'a u8;

    fn next(&mut self) -> Option<&'a u8> {
        if self.index >= self.buffer.len() { return None; }

        let result = &self.buffer[self.index];
        self.index += 1;

        Some(result)
    }
}

/// A mutable iterator for a [`Buffer`](Buffer) object.
pub struct BufferIterMut<'a> {
    buffer: &'a mut [u8],
    index: usize,
}
impl<'a> BufferIterMut<'a> {
    /// Create a new mutable iterator for a [`Buffer`](Buffer) object.
    pub fn new(buffer: &'a mut [u8], index: usize) -> Self {
        Self { buffer, index }
    }
}
impl<'a> Iterator for BufferIterMut<'a> {
    type Item = &'a mut u8;

    fn next(&mut self) -> Option<&'a mut u8> {
        if self.index >= self.buffer.len() { return None; }

        let ptr = &mut self.buffer[self.index] as *mut u8;
        let result = unsafe { &mut *ptr };
        self.index += 1;

        Some(result)
    }
}

/// An iterator for searching over a [`Buffer`](Buffer)'s space for a given binary search term.
pub struct BufferSearchIter {
    offsets: Vec<usize>,
    offset_index: usize,
}
impl BufferSearchIter {
    /// Create a new search iterator over a buffer reference. Typically you'll just want to call [`Buffer::search`](Buffer::search) instead,
    /// but this essentially does the same thing.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the search term is longer than the buffer.
    pub fn new<B: AsRef<[u8]>>(buf: B, term: B) -> Result<Self, Error> {
        let buffer = buf.as_ref();
        let search = term.as_ref();

        if search.len() > buffer.len() { return Err(Error::OutOfBounds(buffer.len(),search.len())); }

        let offsets: Vec<usize> = memmem::find_iter(buffer, search).collect();

        Ok(Self { offsets: offsets, offset_index: 0 })
    }
}
impl Iterator for BufferSearchIter {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.offset_index >= self.offsets.len() { return None; }

        let offset = self.offsets[self.offset_index];
        self.offset_index += 1;

        Some(offset)
    }
}

/// An iterator for searching over a [`Buffer`](Buffer)'s space for a given dynamic search term.
pub struct BufferSearchDynamicIter<'a> {
    buffer: &'a [u8],
    term: Vec<Option<u8>>,
    term_index: usize,
    offsets: Vec<usize>,
    offset_index: usize,
}
impl<'a> BufferSearchDynamicIter<'a> {
    fn find_next_const(&self, index: Option<usize>) -> Option<usize> {
        let start;

        if index.is_none() {
            start = 0;
        }
        else {
            start = index.unwrap()+1;
        }

        for i in start..self.term.len() {
            if self.term[i].is_none() { continue; }
            return Some(i);
        }

        return None
    }

    /// Create a new search iterator over a buffer reference. Typically you'll just want to call [`Buffer::search_dynamic`](Buffer::search_dynamic) instead,
    /// but this essentially does the same thing.
    ///
    /// Returns an [`Error::OutOfBounds`](Error::OutOfBounds) error if the search term is longer than the buffer.
    pub fn new<B: AsRef<[Option<u8>]>>(buffer: &'a [u8], term: B) -> Result<Self, Error> {
        let search = term.as_ref();

        if search.len() > buffer.len() { return Err(Error::OutOfBounds(buffer.len(),search.len())); }

        let mut offsets = Vec::<usize>::new();
        let mut result = Self { buffer: buffer, term: search.to_vec(), term_index: 0, offsets: offsets.clone(), offset_index: 0 };
        let search_const = result.find_next_const(None);

        if search_const.is_none() { return Err(Error::SearchMatchesEverything); }
        let search_const = search_const.unwrap();
        let search_val = search[search_const].unwrap();

        for i in 0..=(buffer.len()-search.len()) {
            if buffer[i+search_const] == search_val { offsets.push(i); }
        }

        result.offsets = offsets;
        result.term_index = search_const;

        Ok(result)
    }
}
impl<'a> Iterator for BufferSearchDynamicIter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        'search: loop {
            if self.offset_index >= self.offsets.len() { return None; }

            let offset = self.offsets[self.offset_index];
            self.offset_index += 1;

            let found_slice = &self.buffer[offset..offset+self.term.len()];
            let mut search = self.term_index;

            while let Some(next_search) = self.find_next_const(Some(search)) {
                search = next_search;
                let term = self.term[search].unwrap();

                if found_slice[search] != term { continue 'search; }
            }

            return Some(offset);
        }
    }
}