project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | use std::{fmt::Debug, mem::MaybeUninit}; |
| 2 | |
| 3 | pub(crate) struct TinyVec<T, const N: usize> { |
| 4 | len: u8, |
| 5 | data: [MaybeUninit<T>; N], |
| 6 | } |
| 7 | |
| 8 | impl<T: Debug, const N: usize> Debug for TinyVec<T, N> { |
| 9 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 10 | f.debug_list().entries(self.iter()).finish() |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | impl<T: Clone, const N: usize> Clone for TinyVec<T, N> { |
| 15 | fn clone(&self) -> Self { |
| 16 | let mut result = Self::new(); |
| 17 | for item in self.iter() { |
| 18 | result |
| 19 | .push(item.clone()) |
| 20 | .ok() |
| 21 | .expect("TinyVec clone should fit in the same capacity"); |
| 22 | } |
| 23 | result |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl<T, const N: usize> std::ops::Index<usize> for TinyVec<T, N> { |
| 28 | type Output = T; |
| 29 | |
| 30 | fn index(&self, index: usize) -> &Self::Output { |
| 31 | assert!(index < self.len as usize); |
| 32 | // SAFETY: This is safe because we know that the data is initialized |
| 33 | unsafe { self.data[index].assume_init_ref() } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl<T, const N: usize> TinyVec<T, N> { |
| 38 | #[inline] |
| 39 | pub fn new() -> Self { |
| 40 | if N > u8::MAX as usize { |
| 41 | panic!("TinyVec size too large"); |
| 42 | } |
| 43 | |
| 44 | Self { |
| 45 | len: 0, |
| 46 | // SAFETY: This initialization is copied from std |
| 47 | // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid. |
| 48 | data: unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }, |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub fn push(&mut self, value: T) -> Result<(), T> { |
| 53 | if self.len == N as u8 { |
| 54 | return Err(value); |
| 55 | } |
| 56 | |
| 57 | self.data[self.len as usize] = MaybeUninit::new(value); |
| 58 | self.len += 1; |
| 59 | Ok(()) |
| 60 | } |
| 61 | |
| 62 | #[inline(always)] |
| 63 | pub fn get(&self, index: usize) -> &T { |
| 64 | &self[index] |
| 65 | } |
| 66 | |
| 67 | pub fn pop(&mut self) -> Option<T> { |
| 68 | if self.len == 0 { |
| 69 | None |
| 70 | } else { |
| 71 | self.len -= 1; |
| 72 | // SAFETY: This is safe because we know that the last element is initialized |
| 73 | Some(unsafe { self.data[self.len as usize].assume_init_read() }) |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | #[inline(always)] |
| 78 | pub fn len(&self) -> usize { |
| 79 | self.len as usize |
| 80 | } |
| 81 | |
| 82 | #[inline(always)] |
| 83 | pub fn is_empty(&self) -> bool { |
| 84 | self.len == 0 |
| 85 | } |
| 86 | |
| 87 | pub fn iter(&self) -> impl Iterator<Item = &T> { |
| 88 | let mut index = 0; |
| 89 | std::iter::from_fn(move || { |
| 90 | if index < self.len as usize { |
| 91 | let result = &self[index]; |
| 92 | index += 1; |
| 93 | Some(result) |
| 94 | } else { |
| 95 | None |
| 96 | } |
| 97 | }) |
| 98 | } |
| 99 | |
| 100 | pub fn can_merge(&self, other: &Self) -> bool { |
| 101 | if self.len() + other.len() > N { |
| 102 | return false; |
| 103 | } |
| 104 | |
| 105 | self.len() + other.len() <= self.data.len() |
| 106 | } |
| 107 | |
| 108 | pub fn merge(&mut self, other: &Self) |
| 109 | where |
| 110 | T: Clone, |
| 111 | { |
| 112 | if !self.can_merge(other) { |
| 113 | panic!("TinyVec cannot merge"); |
| 114 | } |
| 115 | |
| 116 | for item in other.iter() { |
| 117 | self.push(item.clone()) |
| 118 | .ok() |
| 119 | .expect("TinyVec merge should fit after can_merge"); |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | pub fn merge_left(&mut self, left: &Self) |
| 124 | where |
| 125 | T: Clone, |
| 126 | { |
| 127 | if !self.can_merge(left) { |
| 128 | panic!("TinyVec cannot merge"); |
| 129 | } |
| 130 | |
| 131 | let mut result = Self::new(); |
| 132 | for item in left.iter().chain(self.iter()) { |
| 133 | result |
| 134 | .push(item.clone()) |
| 135 | .ok() |
| 136 | .expect("TinyVec merge_left should fit after can_merge"); |
| 137 | } |
| 138 | *self = result; |
| 139 | } |
| 140 | |
| 141 | pub fn slice(&self, start: usize, end: usize) -> Self |
| 142 | where |
| 143 | T: Clone, |
| 144 | { |
| 145 | assert!(start <= end && end <= self.len as usize); |
| 146 | let mut result = Self::new(); |
| 147 | for item in self.iter().skip(start).take(end - start) { |
| 148 | result |
| 149 | .push(item.clone()) |
| 150 | .ok() |
| 151 | .expect("TinyVec slice should fit in the same capacity"); |
| 152 | } |
| 153 | result |
| 154 | } |
| 155 | |
| 156 | #[inline] |
| 157 | pub fn split(&mut self, pos: usize) -> Self { |
| 158 | assert!(pos <= self.len()); |
| 159 | let old_len = self.len(); |
| 160 | let mut result = Self::new(); |
| 161 | for i in pos..old_len { |
| 162 | // SAFETY: indexes below old_len are initialized. The value is moved |
| 163 | // into result and self.len is truncated below before self is dropped. |
| 164 | let value = unsafe { self.data[i].assume_init_read() }; |
| 165 | result |
| 166 | .push(value) |
| 167 | .ok() |
| 168 | .expect("TinyVec split should fit in the same capacity"); |
| 169 | } |
| 170 | self.len = pos as u8; |
| 171 | result |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | impl<T: Clone, const N: usize> TinyVec<T, N> { |
| 176 | pub fn to_vec(&self) -> Vec<T> { |
| 177 | let mut result = Vec::with_capacity(self.len as usize); |
| 178 | for i in 0..self.len as usize { |
| 179 | result.push(self[i].clone()); |
| 180 | } |
| 181 | result |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | impl<T: PartialEq, const N: usize> PartialEq for TinyVec<T, N> { |
| 186 | fn eq(&self, other: &Self) -> bool { |
| 187 | if self.len != other.len { |
| 188 | return false; |
| 189 | } |
| 190 | |
| 191 | for i in 0..self.len as usize { |
| 192 | if self[i] != other[i] { |
| 193 | return false; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | true |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | impl<T: Eq, const N: usize> Eq for TinyVec<T, N> {} |
| 202 | |
| 203 | impl<T, const N: usize> Drop for TinyVec<T, N> { |
| 204 | fn drop(&mut self) { |
| 205 | for i in 0..self.len as usize { |
| 206 | // SAFETY: This is safe because we know that the element is initialized |
| 207 | unsafe { std::ptr::drop_in_place(self.data[i].as_mut_ptr()) }; |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | #[cfg(test)] |
| 213 | mod test { |
| 214 | use std::sync::Arc; |
| 215 | |
| 216 | use super::TinyVec; |
| 217 | |
| 218 | #[test] |
| 219 | fn pop_should_drop() { |
| 220 | let mut arr: TinyVec<_, 2> = TinyVec::new(); |
| 221 | let elem = Arc::new(10); |
| 222 | assert_eq!(Arc::strong_count(&elem), 1); |
| 223 | arr.push(elem.clone()).unwrap(); |
| 224 | assert_eq!(Arc::strong_count(&elem), 2); |
| 225 | arr.pop(); |
| 226 | assert_eq!(Arc::strong_count(&elem), 1); |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn dropping_should_drop_all_elem() { |
| 231 | let mut arr: TinyVec<_, 2> = TinyVec::new(); |
| 232 | let elem = Arc::new(10); |
| 233 | assert_eq!(Arc::strong_count(&elem), 1); |
| 234 | arr.push(elem.clone()).unwrap(); |
| 235 | assert_eq!(Arc::strong_count(&elem), 2); |
| 236 | drop(arr); |
| 237 | assert_eq!(Arc::strong_count(&elem), 1); |
| 238 | } |
| 239 | |
| 240 | #[test] |
| 241 | fn split() { |
| 242 | let mut arr: TinyVec<u8, 8> = TinyVec::new(); |
| 243 | arr.push(1).unwrap(); |
| 244 | arr.push(2).unwrap(); |
| 245 | arr.push(3).unwrap(); |
| 246 | arr.push(4).unwrap(); |
| 247 | let new = arr.split(2); |
| 248 | assert_eq!(arr.to_vec(), vec![1, 2]); |
| 249 | assert_eq!(new.to_vec(), vec![3, 4]); |
| 250 | } |
| 251 | |
| 252 | #[test] |
| 253 | fn slice() { |
| 254 | let mut arr: TinyVec<u8, 8> = TinyVec::new(); |
| 255 | arr.push(1).unwrap(); |
| 256 | arr.push(2).unwrap(); |
| 257 | arr.push(3).unwrap(); |
| 258 | arr.push(4).unwrap(); |
| 259 | arr.push(5).unwrap(); |
| 260 | let arr = arr; |
| 261 | let new = arr.slice(2, 4); |
| 262 | assert_eq!(new.to_vec(), vec![3, 4]); |
| 263 | } |
| 264 | |
| 265 | #[test] |
| 266 | fn clone() { |
| 267 | let mut arr: TinyVec<u8, 8> = TinyVec::new(); |
| 268 | arr.push(1).unwrap(); |
| 269 | arr.push(2).unwrap(); |
| 270 | arr.push(3).unwrap(); |
| 271 | arr.push(4).unwrap(); |
| 272 | arr.push(5).unwrap(); |
| 273 | let arr = arr; |
| 274 | let new = arr.clone(); |
| 275 | assert_eq!(arr, new); |
| 276 | assert_eq!(new.to_vec(), [1, 2, 3, 4, 5]); |
| 277 | } |
| 278 | |
| 279 | #[cfg(miri)] |
| 280 | #[test] |
| 281 | fn clone_of_owned_values_does_not_duplicate_ownership_with_raw_copy() { |
| 282 | let mut arr: TinyVec<Box<i32>, 2> = TinyVec::new(); |
| 283 | arr.push(Box::new(1)).unwrap(); |
| 284 | |
| 285 | let cloned = arr.clone(); |
| 286 | drop(arr); |
| 287 | drop(cloned); |
| 288 | } |
| 289 | } |