iona 0.1.1

A high-performance, memory mirror circular buffer
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
use core::slice;
use libc::{close, mmap, munmap};
use std::io;
use std::io::Error;
use std::marker::PhantomData;
use std::ops;
use std::ptr;

/// High performance, circular buffer.
pub struct IonaBuffer<
    T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable,
> {
    // Raw pointer to the buffer.
    addr: *mut u8,
    // Raw byte capacity of the buffer. Aligned to the system's page size.
    capacity: usize,
    // Byte mask to ensure pointer stays inbounds.
    mask: usize,
    // Number of elements that the buffer can contain.
    elem_capacity: usize,
    // Element mask to ensure the number of elements stays inbounds.
    elem_mask: usize,
    // IonaBuffer contains elements of type T.
    phantom: PhantomData<T>,
    // The write byte pointer, pointing to the current back of the circular buffer.
    ptr: usize,
    // The read byte pointer, pointing to the next initialized value.
    read_ptr: usize,
    // Number of T initialized in the buffer.
    len: usize,
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    IonaBuffer<T>
{
    /// Creates a page size aligned circular buffer.
    ///
    /// # Example
    ///
    /// ```
    /// use iona::IonaBuffer;
    ///
    /// let buffer: IonaBuffer<usize> = match IonaBuffer::with_capacity(512) {
    ///     Ok(buffer) => buffer,
    ///     Err(_) => panic!("Unable to allocate the buffer"),
    /// };
    ///
    /// assert_eq!(buffer.capacity(), 512);
    ///
    /// // On a 64 bit, 4kb page size computer requesting more than what can fit in a single page:
    /// let buffer: IonaBuffer<usize> = match IonaBuffer::with_capacity(513) {
    ///     Ok(buffer) => buffer,
    ///     Err(_) => panic!("Unable to allocate the buffer"),
    /// };
    ///
    /// assert_eq!(buffer.capacity(), 1024);
    /// ```
    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_os = "linux"))]
    pub fn with_capacity(capacity: usize) -> Result<Self, Error> {
        unsafe {
            // Get page size and align capacity
            let page_size = usize::try_from(libc::sysconf(libc::_SC_PAGESIZE))
                // TODO: make this error better
                .map_err(|_| std::io::ErrorKind::Other)?;
            let capacity = capacity * size_of::<T>();
            let capacity = (capacity + page_size - 1) & !(page_size - 1);
            let capacity = capacity.next_power_of_two();

            let fd = libc::memfd_create(c"circular_buffer".as_ptr(), 0);

            if fd < 0 {
                return Err(Error::last_os_error());
            }

            // Set the size of the memory region
            if libc::ftruncate(fd, capacity as i64) != 0 {
                close(fd);
                return Err(Error::last_os_error());
            }

            // Reserve 2x capacity of virtual address space
            let addr = mmap(
                ptr::null_mut(),
                2 * capacity,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
                -1,
                0,
            );

            if addr == libc::MAP_FAILED {
                close(fd);
                return Err(Error::last_os_error());
            }

            // Map first half to the memfd
            if mmap(
                addr,
                capacity,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_SHARED | libc::MAP_FIXED,
                fd,
                0,
            ) == libc::MAP_FAILED
            {
                libc::munmap(addr, 2 * capacity);
                close(fd);
                return Err(Error::last_os_error());
            }

            // Map second half to the same memfd (mirror mapping!)
            if mmap(
                addr.add(capacity),
                capacity,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_SHARED | libc::MAP_FIXED,
                fd,
                0,
            ) == libc::MAP_FAILED
            {
                munmap(addr, 2 * capacity);
                close(fd);
                return Err(Error::last_os_error());
            }

            // Can safely close the fd after the pages are allocated.
            close(fd);

            Ok(IonaBuffer::<T> {
                addr: addr.cast::<u8>(),
                capacity,
                elem_capacity: capacity / size_of::<T>(),
                mask: capacity - 1,
                elem_mask: (capacity / size_of::<T>()) - 1,
                phantom: PhantomData,
                ptr: 0,
                read_ptr: 0,
                len: 0,
            })
        }
    }

    /// Creates a new circular buffer.
    ///
    /// # Example
    ///
    /// ```
    /// use iona::IonaBuffer;
    ///
    /// let buffer: IonaBuffer<usize> = match IonaBuffer::new() {
    ///     Ok(buffer) => buffer,
    ///     Err(_) => panic!("Unable to allocate the buffer"),
    /// };
    ///
    /// assert_eq!(buffer.len(), 0);
    /// ```
    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), target_os = "linux"))]
    pub fn new() -> Result<Self, Error> {
        // Align to the least number of pages to fit a single T.
        Self::with_capacity(1)
    }

    /// Gets the number of items that have been added to the buffer. Will always be <= the capacity
    /// of the buffer. Does not count uninitialized spaces between values. For example, pushing an
    /// item and then push(ing)_back another item will only increase the len to two.
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new()?;
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&1);
    /// assert_eq!(buffer.len(), 1);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns whether the buffer is empty or not.
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new()?;
    /// assert!(buffer.is_empty());
    ///
    /// buffer.push_back(&1);
    /// assert!(!buffer.is_empty());
    /// #
    /// #   Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Shows how many elements of type T fit within the buffer.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new()?;
    /// assert_eq!(buffer.len(), 0);
    ///
    /// // On a 64 bit, 4kb page layout.
    /// assert_eq!(buffer.capacity(), 512);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[allow(
        clippy::misnamed_getters,
        reason = "this is getting the element capacity, rather than byte capacity"
    )]
    pub fn capacity(&self) -> usize {
        self.elem_capacity
    }

    /// Shows how much uninitialized memory remains in the buffer.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new()?;
    /// assert_eq!(buffer.len(), 0);
    /// assert_eq!(buffer.capacity(), 512);
    /// assert_eq!(buffer.capacity_available(), 512);
    ///
    /// buffer.push_back(&1);
    /// assert_eq!(buffer.len(), 1);
    /// assert_eq!(buffer.capacity(), 512);
    /// assert_eq!(buffer.capacity_available(), 511);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn capacity_available(&self) -> usize {
        self.elem_capacity - self.len()
    }

    ///// Gets the raw number byte capacity of the buffer.
    //pub(crate) fn byte_capacity(&self) -> usize {
    //    self.capacity
    //}

    /// Gets the nth value from the buffer. Masked to always be within the range.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new()?;
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&22);
    /// buffer.push_back(&23);
    ///
    /// assert_eq!(buffer.get(0), Some(&22));
    /// assert_eq!(buffer.get(1), Some(&23));
    ///
    /// assert_eq!(buffer.get(buffer.capacity()), Some(&22));
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get(&self, nth: usize) -> Option<&T> {
        let offset = (nth * size_of::<T>()) & self.mask;

        if self.is_in_range(offset) {
            return T::ref_from_bytes(self.read_from(offset, size_of::<T>())).ok();
        }
        None
    }

    fn is_in_range(&self, offset: usize) -> bool {
        // Buffer is full
        if self.ptr == self.read_ptr && self.len == self.elem_capacity {
            return true;
        }

        if self.ptr >= self.read_ptr {
            offset >= self.read_ptr && offset < self.ptr
        } else {
            offset >= self.read_ptr || offset < self.ptr
        }
    }

    /// Gets an exclusive reference to the nth value from the buffer.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new()?;
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&22);
    /// buffer.push_back(&23);
    ///
    /// assert_eq!(buffer.get_mut(0), Some(&mut 22));
    /// assert_eq!(buffer.get_mut(1), Some(&mut 23));
    ///
    /// assert_eq!(buffer.get_mut(buffer.capacity()), Some(&mut 22));
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get_mut(&mut self, nth: usize) -> Option<&mut T> {
        let offset = (nth * size_of::<T>()) & self.mask;

        if self.is_valid_offset(offset) {
            return T::mut_from_bytes(self.read_from_mut(offset, size_of::<T>())).ok();
        }
        None
    }

    /// Gets a slice from the buffer. Not a part of the public API. Expectation is for users to use
    /// the more idomatic range indexing, i.e. `buffer[0..22]`.
    pub(crate) fn get_slice(&self, rng: std::ops::Range<usize>) -> &[T] {
        zerocopy::FromBytes::ref_from_bytes(self.read_from(
            (rng.start * size_of::<T>()) & self.mask,
            (rng.end - rng.start) * size_of::<T>(),
        ))
        .expect("Failed here")
    }

    fn get_mut_slice_from_bytes(&mut self, rng: std::ops::Range<usize>) -> &mut [T] {
        let start = rng.start & self.mask;
        let mut len = rng.end & self.mask;
        if start > len {
            len = (start + self.capacity) - len;
        }
        assert!(len <= self.capacity);
        zerocopy::FromBytes::mut_from_bytes(self.read_from_mut(start, len))
            .expect("Failed in get_mut")
    }

    /// Gets a slice from the buffer with raw byte offsets.
    fn get_slice_from_bytes(&self, rng: std::ops::Range<usize>) -> &[T] {
        let start = rng.start & self.mask;
        let mut len = rng.end & self.mask;
        if start > len {
            len = (start + self.capacity) - len;
        }
        assert!(len <= self.capacity);
        zerocopy::FromBytes::ref_from_bytes(self.read_from(start, len)).expect("Failed here too")
    }

    /// Pushes a new item into the buffer. Overwrites the front of the buffer when it wraps around.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&22);
    ///
    /// assert_eq!(buffer.get(0), Some(&22));
    /// assert_eq!(buffer.len(), 1);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn push_back(&mut self, value: &T) {
        let offset = self.ptr & self.mask;
        self.write_at(offset, value.as_bytes());
        self.ptr = (self.ptr + size_of::<T>()) & self.mask;

        // If the buffer is full, advance the read pointer too.
        if self.is_full() {
            self.read_ptr = (self.read_ptr + size_of::<T>()) & self.mask;
        }

        self.update_len();
    }

    /// Pushes a new T to the front of the buffer.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&1);
    /// buffer.push_front(&0);
    /// buffer.push_front(&usize::MAX);
    ///
    /// assert_eq!(buffer.pop_front(), Some(usize::MAX));
    /// assert_eq!(buffer.pop_front(), Some(0));
    /// assert_eq!(buffer.pop_front(), Some(1));
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn push_front(&mut self, value: &T) {
        let offset = self.read_ptr.wrapping_sub(size_of::<T>()) & self.mask;
        self.write_at(offset, value.as_bytes());

        self.update_len();
        self.read_ptr = offset;
    }

    /// Pops the value at the read pointer. Will advance the read pointer and will return None
    /// when it reaches the write pointer. Equivalent to `next`.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&1);
    /// buffer.push_back(&2);
    /// assert_eq!(buffer.pop_front(), Some(1));
    /// assert_eq!(buffer.pop_front(), Some(2));
    /// buffer.push_back(&3);
    /// assert_eq!(buffer.pop_front(), Some(3));
    /// assert_eq!(buffer.len(), 0);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn pop_front(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        // Store the next element's position
        let next_idx = self.read_ptr;

        // Advance the read pointer
        self.read_ptr = (self.read_ptr + size_of::<T>()) & self.mask;
        self.decrease_len();

        // Return T
        let tmp = T::read_from_bytes(self.read_from(next_idx, size_of::<T>())).ok()?;

        // TODO: remove this allocation
        #[cfg(feature = "sensitive")]
        self.write_at(next_idx, &vec![0; size_of::<T>()]);

        Some(tmp)
    }

    /// Pops the value at the write pointer. Will move the write pointer back until it reaches the
    /// read pointer.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.push_back(&1);
    /// buffer.push_back(&2);
    /// assert_eq!(buffer.pop_back(), Some(2));
    /// assert_eq!(buffer.pop_back(), Some(1));
    /// assert_eq!(buffer.pop_back(), None);
    /// assert_eq!(buffer.len(), 0);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn pop_back(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        #[cfg(feature = "sensitive")]
        // Don't need to save the poiter if we're not going to zero out the value.
        let tmp_ptr = self.ptr;

        // Decrement the write pointer
        self.ptr = (self.ptr.wrapping_sub(size_of::<T>())) & self.mask;
        self.decrease_len();

        let tmp = T::read_from_bytes(self.read_from(self.ptr, size_of::<T>())).ok()?;

        // TODO: remove this allocation
        #[cfg(feature = "sensitive")]
        self.write_at(tmp_ptr, &vec![0; size_of::<T>()]);

        Some(tmp)
    }

    /// Returns whether the buffer is filled to capacity
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    /// assert!(!buffer.is_full());
    ///
    /// buffer.concat(&vec![1; buffer.capacity()]);
    /// assert!(buffer.is_full());
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_full(&self) -> bool {
        self.capacity() == self.len()
    }

    /// Fills the buffer with the same value
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.fill(1);
    /// assert!(buffer.is_full());
    /// assert_eq!(buffer.get(buffer.capacity() - 1), Some(&1));
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn fill(&mut self, value: T)
    where
        T: Clone,
    {
        // TODO: This can't allocate a vec here!
        self.concat(&vec![value; self.capacity()]);
    }

    /// Write a slice of bytes to an offset.
    #[inline]
    fn write_at(&mut self, offset: usize, bytes: &[u8]) {
        assert!(
            bytes.len() <= self.capacity,
            "Cannot write more than capacity"
        );
        let start = offset & self.mask;
        unsafe {
            ptr::copy_nonoverlapping(bytes.as_ptr(), self.addr.add(start), bytes.len());
        }
    }

    /// Concats a slice of T to the end of the circular buffer's value. Will overwrite the front
    /// of the buffer when wrapping.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// buffer.concat(&[1, 2, 3]);
    /// assert_eq!(&buffer[0..=2], &[1,2,3]);
    ///
    /// buffer.concat(&vec![22; buffer.capacity() - 1]);
    /// assert_eq!(&buffer[0..=2], &[22, 22, 3]);
    ///
    /// assert_eq!(buffer.len(), buffer.capacity());
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn concat(&mut self, slice: &[T]) {
        let bytes = zerocopy::IntoBytes::as_bytes(slice);
        self.write_at(self.ptr, bytes);

        if (self.ptr + bytes.len()) & self.mask >= self.read_ptr {
            self.read_ptr =
                ((self.ptr + bytes.len()) & self.mask).wrapping_sub(self.read_ptr) & self.mask;
        }

        // Move the write pointer forward
        self.ptr = (self.ptr + bytes.len()) & self.mask;
        // Update the len
        self.increase_len(slice.len());

        if self.is_full() {
            // Advance the read pointer to where the write pointer is pointing
            self.read_ptr = self.ptr;
        }
    }

    /// Increase the len of the buffer with
    #[inline]
    fn increase_len(&mut self, amount: usize) {
        let tmp_len = self.len() + amount;

        match tmp_len.cmp(&self.capacity()) {
            std::cmp::Ordering::Less => self.len = tmp_len,
            // The len can never exceed the capacity since it should always wrap.
            std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => self.len = self.capacity(),
        }
    }

    /// Decreases the len of the buffer with
    #[inline]
    fn decrease_len(&mut self) {
        if self.is_empty() {
            return;
        }

        self.len -= 1;
    }

    /// Increases the len of the buffer by one.
    #[inline]
    fn update_len(&mut self) {
        self.increase_len(1);
    }

    /// Overwrites a single value of T to a specific place in the buffer.
    ///
    /// # Example
    ///
    /// ```
    /// # use iona::IonaBuffer;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut buffer: IonaBuffer<usize> = IonaBuffer::new().unwrap();
    /// assert_eq!(buffer.len(), 0);
    ///
    /// // Subsequent pushes are wrapped around.
    /// buffer.push_back(&1);
    /// let previous_value = buffer.overwrite(0, &usize::MAX).unwrap();
    /// assert_eq!(buffer.get(0), Some(&usize::MAX));
    /// assert_eq!(previous_value, 1);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    /// TODO: improve the err type
    pub fn overwrite(&mut self, at: usize, value: &T) -> Result<T, io::Error> {
        // align the value
        let offset = at * size_of::<T>();

        if self.is_valid_offset(offset) {
            let tmp = T::read_from_bytes(self.read_from(offset, size_of::<T>()))
                .map_err(|_| std::io::ErrorKind::NotFound)?;
            self.write_at(offset, value.as_bytes());
            return Ok(tmp);
        }
        Err(io::ErrorKind::NotFound.into())
    }

    /// Takes a raw byte offset and determines whether the offset is between the read and write
    /// pointers.
    fn is_valid_offset(&self, offset: usize) -> bool {
        if self.ptr >= self.read_ptr {
            offset >= self.read_ptr && offset < self.ptr
        } else {
            offset >= self.read_ptr || offset < self.ptr
        }
    }

    #[inline]
    fn read_from(&self, offset: usize, len: usize) -> &[u8] {
        assert!(len <= self.capacity, "Cannot read more than capacity");
        let start = offset & self.mask;
        unsafe { std::slice::from_raw_parts(self.addr.add(start), len) }
    }

    #[inline]
    fn read_from_mut(&mut self, offset: usize, len: usize) -> &mut [u8] {
        assert!(len <= self.capacity, "Cannot read more than capacity");
        let start = offset & self.mask;
        unsafe { std::slice::from_raw_parts_mut(self.addr.add(start), len) }
    }

    pub fn iter(&self) -> slice::Iter<'_, T> {
        <&Self as IntoIterator>::into_iter(self)
    }

    pub fn iter_mut(&self) -> slice::Iter<'_, T> {
        <&Self as IntoIterator>::into_iter(self)
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    Drop for IonaBuffer<T>
{
    /// Free the memory
    fn drop(&mut self) {
        unsafe {
            libc::munmap(self.addr.cast::<libc::c_void>(), 2 * self.capacity);
        }
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    ops::Index<ops::Range<usize>> for IonaBuffer<T>
{
    type Output = [T];

    fn index(&self, index: ops::Range<usize>) -> &Self::Output {
        self.get_slice(index)
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    ops::Index<ops::RangeInclusive<usize>> for IonaBuffer<T>
{
    type Output = [T];

    fn index(&self, index: ops::RangeInclusive<usize>) -> &Self::Output {
        self.get_slice(*index.start()..*index.end() + 1)
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    ops::Index<ops::RangeTo<usize>> for IonaBuffer<T>
{
    type Output = [T];

    fn index(&self, index: ops::RangeTo<usize>) -> &Self::Output {
        self.get_slice(0..index.end)
    }
}

// TODO: Add bounds checking to these range impls
impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    ops::Index<ops::RangeToInclusive<usize>> for IonaBuffer<T>
{
    type Output = [T];

    fn index(&self, index: ops::RangeToInclusive<usize>) -> &Self::Output {
        self.get_slice(0..index.end + 1)
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    ops::Index<ops::RangeFrom<usize>> for IonaBuffer<T>
{
    type Output = [T];

    fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
        assert!(
            index.start > self.len,
            "index out of bounds: start {} >= len {}",
            index.start,
            self.len()
        );
        let start = (self.read_ptr / size_of::<T>() + index.start) & self.elem_mask;
        let count = self.len - index.start;
        self.get_slice(start..start + count)
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    ops::Index<ops::RangeFull> for IonaBuffer<T>
{
    type Output = [T];

    fn index(&self, _: ops::RangeFull) -> &Self::Output {
        self.get_slice_from_bytes(self.read_ptr..self.ptr)
    }
}

unsafe impl<
    T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable,
> Send for IonaBuffer<T>
{
}
unsafe impl<
    T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable,
> Sync for IonaBuffer<T>
{
}

impl<'a, T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    IntoIterator for &'a IonaBuffer<T>
{
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self[..].iter()
    }
}

impl<'a, T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    IntoIterator for &'a mut IonaBuffer<T>
{
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.get_mut_slice_from_bytes(self.read_ptr..self.ptr)
            .iter_mut()
    }
}

pub struct IntoIter<
    T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable,
>(IonaBuffer<T>);

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    Iterator for IntoIter<T>
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.pop_front()
    }
}

impl<T: zerocopy::FromBytes + zerocopy::IntoBytes + zerocopy::KnownLayout + zerocopy::Immutable>
    IntoIterator for IonaBuffer<T>
{
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter(self)
    }
}