|
| 1 | +#![cfg(feature = "alloc")] |
| 2 | + |
| 3 | +use crate::prelude::*; |
| 4 | +use core::cell::UnsafeCell; |
| 5 | + |
| 6 | +/// Helps overcome limitations of the lifetime system when constructing MIDI events and files. |
| 7 | +/// |
| 8 | +/// Because many events contain references to data that outlives them, it can be hard to build a |
| 9 | +/// MIDI file on-the-fly. |
| 10 | +/// |
| 11 | +/// Consider the following code: |
| 12 | +/// |
| 13 | +/// ```rust,compile_fail |
| 14 | +/// use midly::{TrackEvent, TrackEventKind, MetaMessage}; |
| 15 | +/// |
| 16 | +/// let mut track = Vec::new(); |
| 17 | +/// for i in 0..64 { |
| 18 | +/// let marker_name = format!("Marker {}", i); |
| 19 | +/// let marker_ref = marker_name.as_bytes(); |
| 20 | +/// track.push(TrackEvent { |
| 21 | +/// delta: 0.into(), |
| 22 | +/// kind: TrackEventKind::Meta(MetaMessage::Marker(marker_ref)), |
| 23 | +/// }); |
| 24 | +/// } |
| 25 | +/// ``` |
| 26 | +/// |
| 27 | +/// Looks pretty good, but it fails to compile with |
| 28 | +/// `error[E0597]: "marker_name" does not live long enough`, with a rightful reason: `marker_name` |
| 29 | +/// is dropped before the next iteration of the loop. |
| 30 | +/// |
| 31 | +/// Instead, use `Arena` like the following code: |
| 32 | +/// |
| 33 | +/// ```rust |
| 34 | +/// use midly::{TrackEvent, TrackEventKind, MetaMessage}; |
| 35 | +/// |
| 36 | +/// let arena = midly::Arena::new(); |
| 37 | +/// let mut track = Vec::new(); |
| 38 | +/// for i in 0..64 { |
| 39 | +/// let marker_name = format!("Marker {}", i); |
| 40 | +/// let marker_ref = arena.add(marker_name.as_bytes()); |
| 41 | +/// track.push(TrackEvent { |
| 42 | +/// delta: 0.into(), |
| 43 | +/// kind: TrackEventKind::Meta(MetaMessage::Marker(marker_ref)), |
| 44 | +/// }); |
| 45 | +/// } |
| 46 | +/// ``` |
| 47 | +#[derive(Default)] |
| 48 | +pub struct Arena { |
| 49 | + allocations: UnsafeCell<Vec<*mut [u8]>>, |
| 50 | +} |
| 51 | +impl Arena { |
| 52 | + /// Create a new empty arena. |
| 53 | + pub fn new() -> Arena { |
| 54 | + Self::default() |
| 55 | + } |
| 56 | + |
| 57 | + /// Empty this arena, deallocating all added bytes. |
| 58 | + /// |
| 59 | + /// This method is safe to call because it requires a mutable reference. |
| 60 | + pub fn clear(&mut self) { |
| 61 | + // SAFETY: |
| 62 | + // Accessing the `UnsafeCell` is safe because we have a mutable reference to it. |
| 63 | + // Since we have a mutable reference to `Arena`, there are no more references into |
| 64 | + // the boxed bytes. Therefore, it is safe to drop the boxed bytes themselves. |
| 65 | + unsafe { |
| 66 | + for bytes in (*self.allocations.get()).drain(..) { |
| 67 | + drop(Box::from_raw(bytes)); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + /// Get the amount of allocations in the arena. |
| 73 | + pub fn len(&self) -> usize { |
| 74 | + // SAFETY: |
| 75 | + // Accessing `self.allocations` is safe as long as there are no concurrent reads or writes. |
| 76 | + // The _contents_ of `self.allocations` might have outstanding references, but reading the |
| 77 | + // length does not require derefencing the contents. |
| 78 | + unsafe { (*self.allocations.get()).len() } |
| 79 | + } |
| 80 | + |
| 81 | + /// Add a set of bytes to the arena, returning a longer-lived mutable reference to a copy of |
| 82 | + /// these same bytes. |
| 83 | + pub fn add<'a, 'b>(&'a self, bytes: &'b [u8]) -> &'a mut [u8] { |
| 84 | + self.add_boxed(Box::from(bytes)) |
| 85 | + } |
| 86 | + |
| 87 | + /// Add a `Vec<u8>` to the arena, returning a long-lived mutable reference to its contents. |
| 88 | + /// |
| 89 | + /// This method is very similar to `add`, but avoids an allocation and a copy. |
| 90 | + pub fn add_vec<'a>(&'a self, bytes: Vec<u8>) -> &'a mut [u8] { |
| 91 | + self.add_boxed(bytes.into_boxed_slice()) |
| 92 | + } |
| 93 | + |
| 94 | + /// Add a set of databytes to the arena, returning a longer-lived mutable reference to a copy |
| 95 | + /// of these same databytes. |
| 96 | + pub fn add_u7<'a, 'b>(&'a self, databytes: &'b [u7]) -> &'a mut [u7] { |
| 97 | + // SAFETY: |
| 98 | + // The returned `&mut [u8]` is transformed into a `&mut [u7]` without checking its |
| 99 | + // contents, which is safe because it was originally a `&[u7]`. |
| 100 | + unsafe { u7::slice_from_int_unchecked_mut(self.add(u7::slice_as_int(databytes))) } |
| 101 | + } |
| 102 | + |
| 103 | + /// Add a `Vec<u7>` to the arena, returning a long-lived mutable reference to its contents. |
| 104 | + /// |
| 105 | + /// This method is very similar to `add_u7`, but avoids an allocation and a copy. |
| 106 | + pub fn add_u7_vec<'a>(&'a self, databytes: Vec<u7>) -> &'a mut [u7] { |
| 107 | + // SAFETY: |
| 108 | + // Two unsafe actions are done: |
| 109 | + // First, a `Vec<u7>` is transmuted into a `Vec<u8>`. This is valid because `u7` has the |
| 110 | + // same representation as `u8` (guaranteed by `repr(transparent)`), and every `u7` bit |
| 111 | + // pattern is a valid `u8` bit pattern. |
| 112 | + // Second, the returned `&mut [u8]` is transformed into a `&mut [u7]` without checking its |
| 113 | + // contents, which is safe because it was originally a `Vec<u7>`. |
| 114 | + unsafe { |
| 115 | + u7::slice_from_int_unchecked_mut( |
| 116 | + self.add_boxed(mem::transmute::<Vec<u7>, Vec<u8>>(databytes).into_boxed_slice()), |
| 117 | + ) |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + fn add_boxed<'a>(&'a self, boxed_bytes: Box<[u8]>) -> &'a mut [u8] { |
| 122 | + // SAFETY: |
| 123 | + // This block moves `boxed_bytes` into `self` and returns a mutable reference to its |
| 124 | + // contents. |
| 125 | + // Further pushes to `self.allocations` may move the _pointers_ to the boxes, but not the |
| 126 | + // box contents themselves, therefore it's safe to hand out mutable references and modify |
| 127 | + // `self.allocations` at the same time. |
| 128 | + unsafe { |
| 129 | + let pointer = Box::into_raw(boxed_bytes); |
| 130 | + (*self.allocations.get()).push(pointer); |
| 131 | + &mut *pointer |
| 132 | + } |
| 133 | + } |
| 134 | +} |
| 135 | +impl Drop for Arena { |
| 136 | + fn drop(&mut self) { |
| 137 | + self.clear(); |
| 138 | + } |
| 139 | +} |
| 140 | +impl fmt::Debug for Arena { |
| 141 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 142 | + //TODO: Once the `len()` method for raw pointers to slices is stabilized, add better |
| 143 | + //debug print, showing the size of each allocation. |
| 144 | + write!(f, "Arena({})", self.len())?; |
| 145 | + Ok(()) |
| 146 | + } |
| 147 | +} |
0 commit comments