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
use std::fmt; use std::vec; use std::iter; use std::marker; use std::ops; use std::slice; use std::mem; mod entry; use self::entry::Entry; use crate::index::Index; pub struct Extend<'a, I, Ix> where I: Iterator, I::Item: 'a, Ix: Index + 'a { iter: I, stash: &'a mut Stash<I::Item, Ix>, } impl<'a, I, Ix: Index> Drop for Extend<'a, I, Ix> where I: Iterator, I::Item: 'a { fn drop(&mut self) { for _ in self {} } } impl<'a, I, Ix: Index> Iterator for Extend<'a, I, Ix> where I: Iterator, I::Item: 'a { type Item = Ix; fn next(&mut self) -> Option<Ix> { self.iter.next().map(|v| self.stash.put(v)) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, I, Ix: Index> ExactSizeIterator for Extend<'a, I, Ix> where I: ExactSizeIterator, I::Item: 'a { } impl<'a, I, Ix: Index> DoubleEndedIterator for Extend<'a, I, Ix> where I: DoubleEndedIterator, I::Item: 'a { fn next_back(&mut self) -> Option<Ix> { self.iter.next_back().map(|v| self.stash.put(v)) } } /// Iterator over the `(index, &value)` pairs. pub struct Iter<'a, V: 'a, Ix: Index> { inner: iter::Enumerate<slice::Iter<'a, Entry<V>>>, len: usize, _marker: marker::PhantomData<fn() -> Ix>, } /// Iterator over the `(index, &mut value)` pairs. pub struct IterMut<'a, V: 'a, Ix: Index> { inner: iter::Enumerate<slice::IterMut<'a, Entry<V>>>, len: usize, _marker: marker::PhantomData<fn() -> Ix>, } /// Iterator over the `(index, value)` pairs. pub struct IntoIter<V, Ix: Index> { inner: iter::Enumerate<vec::IntoIter<Entry<V>>>, len: usize, _marker: marker::PhantomData<fn() -> Ix>, } /// Iterator over references to the values in the stash. pub struct Values<'a, V: 'a> { inner: slice::Iter<'a, Entry<V>>, len: usize, } /// Iterator over mutable references to the values in the stash. pub struct ValuesMut<'a, V: 'a> { inner: slice::IterMut<'a, Entry<V>>, len: usize, } /// Iterator over values in the stash. pub struct IntoValues<V> { inner: vec::IntoIter<Entry<V>>, len: usize, } impl_iter!(Values, (<'a, V>), &'a V, entry::value_ref, ()); impl_iter!(ValuesMut, (<'a, V>), &'a mut V, entry::value_mut, ()); impl_iter!(IntoValues, (<V>), V, entry::value, ()); impl_iter!(Iter, (<'a, V, Ix>), (Ix, &'a V), entry::value_index_ref, (where Ix: Index)); impl_iter!(IterMut, (<'a, V, Ix>), (Ix, &'a mut V), entry::value_index_mut, (where Ix: Index)); impl_iter!(IntoIter, (<V, Ix>), (Ix, V), entry::value_index, (where Ix: Index)); /// An `O(1)` amortized table that reuses keys. /// /// # Guarantees and non-guarantees: /// /// 1. `Stash` is deterministic and keys do not depend on the inserted values. /// This means you can update two stashes in tandem and get the same keys /// back. This could be useful for, e.g., primary/secondary replication. /// 2. Keys will always be less than the maximum number of items that have ever /// been present in the `Stash` at any single point in time. In other words, /// if you never store more than `n` items in a `Stash`, the stash will only /// assign keys less than `n`. You can take advantage of this guarantee to /// truncate the key from a `usize` to some smaller type. /// 3. Except the guarantees noted above, you can assume nothing about key /// assignment or iteration order. They can change at any time. /// /// An example use case is a file descriptor table. #[derive(Clone)] pub struct Stash<V, Ix = usize> { data: Vec<Entry<V>>, size: usize, next_free: usize, // add a phantom user of the Ix type to make sure an instance of Stash is bound to one // specific index type, separate calls to put and get can't use different index types. _marker: marker::PhantomData<fn(Ix) -> Ix>, } impl<V> Stash<V, usize> { /// Constructs a new, empty `Stash<V, usize>`. /// /// This is a convenience method. Use `Stash::default` for /// a constructor that is generic in the type of index used. /// /// The stash will not allocate until elements are put onto it. /// /// # Examples /// /// ``` /// use stash::Stash; /// /// let mut stash: Stash<i32> = Stash::new(); /// ``` #[inline] pub fn new() -> Self { Stash::with_capacity(0) } /// Constructs a new, empty `Stash<V, usize>` with the specified capacity. /// /// This is a convenience method. Use `Stash::default` for /// a constructor that is generic in the type of index used. In that case /// you can call `reserve` on the newly created stash to specify the /// capacity you need. /// /// The stash will be able to hold exactly `capacity` elements without /// reallocating. If `capacity` is 0, the stash will not allocate. /// /// It is important to note that this function does not specify the *length* /// of the returned stash , but only the *capacity*. (For an explanation of /// the difference between length and capacity, see the main `Vec<T>` docs /// in the `std::vec` module, 'Capacity and reallocation'.) /// /// # Examples /// /// ``` /// use stash::Stash; /// /// let mut stash = Stash::with_capacity(10); /// /// // The stash contains no items, even though it has capacity for more /// assert_eq!(stash.len(), 0); /// /// // These are all done without reallocating... /// for i in 0i32..10 { /// let _ = stash.put(i); /// } /// /// // ...but this may make the stash reallocate /// stash.put(11); /// ``` #[inline] pub fn with_capacity(capacity: usize) -> Self { Stash { data: Vec::with_capacity(capacity), next_free: 0, size: 0, _marker: marker::PhantomData, } } } impl<V, Ix> Stash<V, Ix> where Ix: Index { /// Returns the number of elements the stash can hold without reallocating. /// /// # Examples /// /// ``` /// use stash::Stash; /// /// let stash: Stash<i32> = Stash::with_capacity(10); /// assert_eq!(stash.capacity(), 10); /// ``` #[inline] pub fn capacity(&self) -> usize { self.data.capacity() } /// The number of items in the stash. /// /// # Examples /// /// ``` /// use stash::Stash; /// /// let mut stash = Stash::new(); /// assert_eq!(stash.len(), 0); /// stash.put("a"); /// assert_eq!(stash.len(), 1); /// ``` #[inline] pub fn len(&self) -> usize { self.size } /// Reserves capacity for at least `additional` more elements to be put into /// the given `Stash<T>`. The collection may reserve more space to avoid /// frequent reallocations. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// use stash::Stash; /// /// let mut stash: Stash<i32> = Stash::new(); /// let t1 = stash.put(1); /// stash.reserve(10); /// assert!(stash.capacity() >= 11); /// ``` pub fn reserve(&mut self, additional: usize) { let extra_space = self.data.len() - self.len(); if extra_space < additional { self.data.reserve(additional - extra_space) } } /// Reserves the minimum capacity for exactly `additional` more elements to /// be put into the given `Stash<T>`. Does nothing if the capacity is already /// sufficient. /// /// Note that the allocator may give the collection more space than it requests. Therefore /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future /// puts are expected. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// use stash::Stash; /// /// let mut stash: Stash<i32> = Stash::new(); /// let t1 = stash.put(1); /// stash.reserve_exact(10); /// assert!(stash.capacity() >= 11); /// ``` pub fn reserve_exact(&mut self, additional: usize) { let extra_space = self.data.len() - self.len(); if extra_space < additional { self.data.reserve_exact(additional - extra_space) } } /// Get the index that would be returned from next call to `put`. /// /// # Panics /// /// Panics if the size of the `Stash<V, Ix>` would overflow the `Ix` index type. pub fn next_index(&self) -> Ix { Ix::from_usize(self.next_free) } /// Put a value into the stash. /// /// Returns the index at which this value was stored. /// /// # Panics /// /// Panics if the size of the `Stash<V, Ix>` would overflow the `Ix` index type. #[inline] pub fn put(&mut self, value: V) -> Ix { // create index first so the potential panic would happen before any modification let idx = Ix::from_usize(self.next_free); let loc = self.next_free; debug_assert!(loc <= self.data.len()); self.next_free = if self.next_free == self.data.len() { self.data.push(Entry::Full(value)); self.next_free.checked_add(1).unwrap() } else { // Safe because we've recorded that it is safe. unsafe { match mem::replace(self.data.get_unchecked_mut(loc), Entry::Full(value)) { Entry::Empty(next_free) => next_free, _ => ::unreachable::unreachable(), } } }; self.size += 1; idx } /// Put all items in the iterator into the stash. /// /// Returns an iterator over the indices where the items were inserted. The /// items are actually inserted as the Iterator is read. If the returned /// Iterator is dropped, the rest of the items will be inserted all at once. #[inline] pub fn extend<I>(&mut self, iter: I) -> Extend<I, Ix> where I: Iterator<Item = V> { let (lower, _) = iter.size_hint(); self.reserve(lower); Extend { iter: iter, stash: self, } } /// Iterate over the items in this `Stash<V>`. /// /// Returns an iterator that yields `(index, &value)` pairs. #[inline] pub fn iter(&self) -> Iter<V, Ix> { Iter { len: self.len(), inner: self.data.iter().enumerate(), _marker: marker::PhantomData, } } /// Mutably iterate over the items in this `Stash<V>`. /// /// Returns an iterator that yields `(index, &mut value)` pairs. #[inline] pub fn iter_mut(&mut self) -> IterMut<V, Ix> { IterMut { len: self.len(), inner: self.data.iter_mut().enumerate(), _marker: marker::PhantomData, } } /// Iterate over the values in this `Stash<V>` by reference. #[inline] pub fn values(&self) -> Values<V> { Values { len: self.len(), inner: self.data.iter(), } } /// Mutably iterate over the values in this `Stash<V>` by reference. #[inline] pub fn values_mut(&mut self) -> ValuesMut<V> { ValuesMut { len: self.len(), inner: self.data.iter_mut(), } } /// Iterate over the values in this `Stash<V>` by value. #[inline] pub fn into_values(self) -> IntoValues<V> { IntoValues { len: self.len(), inner: self.data.into_iter(), } } /// Check if this `Stash<V>` is empty. /// /// Returns `true` if this `Stash<V>` is empty. #[inline] pub fn is_empty(&self) -> bool { self.size == 0 } /// Take an item from a slot (if non empty). pub fn take(&mut self, index: Ix) -> Option<V> { let take_index = index.into_usize(); match self.data.get_mut(take_index) { None => None, Some(entry) => match mem::replace(entry, Entry::Empty(self.next_free)) { Entry::Empty(free_slot) => { *entry = Entry::Empty(free_slot); None }, Entry::Full(value) => { self.next_free = take_index; self.size -= 1; Some(value) } } } } /// Take an item from a slot (if non empty) without bounds or empty checking. /// So use it very carefully! /// /// This can be safely used as long as the user does not mutate /// `indices` from `put` and is sure not to have taken the value /// associated with the given `index`. #[inline] pub unsafe fn take_unchecked(&mut self, index: Ix) -> V { let take_index = index.into_usize(); match mem::replace(self.data.get_unchecked_mut(take_index), Entry::Empty(self.next_free)) { Entry::Empty(_) => ::unreachable::unreachable(), Entry::Full(value) => { self.next_free = take_index; self.size -= 1; value } } } /// Get a reference to the value at `index`. #[inline] pub fn get(&self, index: Ix) -> Option<&V> { match self.data.get(index.into_usize()) { Some(&Entry::Full(ref v)) => Some(v), _ => None, } } /// Get a reference to the value at `index` without bounds or empty checking. /// So use it very carefully! /// /// This can be safely used as long as the user does not mutate /// `indices` from `put` and is sure not to have taken the value /// associated with the given `index`. #[inline] pub unsafe fn get_unchecked(&self, index: Ix) -> &V { match self.data.get_unchecked(index.into_usize()) { &Entry::Full(ref v) => v, _ => ::unreachable::unreachable() } } /// Get a mutable reference to the value at `index`. #[inline] pub fn get_mut(&mut self, index: Ix) -> Option<&mut V> { match self.data.get_mut(index.into_usize()) { Some(&mut Entry::Full(ref mut v)) => Some(v), _ => None, } } /// Get a mutable reference to the value at `index` without bounds or empty checking. /// So use it very carefully! /// /// This can be safely used as long as the user does not mutate /// `indices` from `put` and is sure not to have taken the value /// associated with the given `index`. #[inline] pub unsafe fn get_unchecked_mut(&mut self, index: Ix) -> &mut V { match self.data.get_unchecked_mut(index.into_usize()) { &mut Entry::Full(ref mut v) => v, _ => ::unreachable::unreachable() } } /// Clear the stash. Cleared stash will give the same keys as a /// new stash for subsequent puts. pub fn clear(&mut self) { // Do it this way so that nothing bad happens if a destructor panics. for (i, entry) in self.data.iter_mut().enumerate() { // Skip if empty. if let Entry::Empty(_) = *entry { continue; } self.next_free = i; self.size -= 1; // Do this last, that way a panic just stops this half way through. *entry = Entry::Empty(self.next_free); } // We've already replaced every element with `Empty` so all destructors // are no-ops. Use `set_len` to avoid traversing the list twice. unsafe { self.data.set_len(0); self.next_free = 0; } } } impl<V, Ix: Index> IntoIterator for Stash<V, Ix> { type Item = (Ix, V); type IntoIter = IntoIter<V, Ix>; #[inline] fn into_iter(self) -> Self::IntoIter { IntoIter { len: self.len(), inner: self.data.into_iter().enumerate(), _marker: marker::PhantomData, } } } impl<'a, V, Ix: Index> IntoIterator for &'a Stash<V, Ix> { type Item = (Ix, &'a V); type IntoIter = Iter<'a, V, Ix>; #[inline] fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, V, Ix: Index> IntoIterator for &'a mut Stash<V, Ix> { type Item = (Ix, &'a mut V); type IntoIter = IterMut<'a, V, Ix>; #[inline] fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } impl<V, Ix> fmt::Debug for Stash<V, Ix> where V: fmt::Debug, Ix: fmt::Debug + Index { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self).finish() } } impl<'a, V, Ix: Index> ops::Index<Ix> for Stash<V, Ix> { type Output = V; #[inline] fn index(&self, index: Ix) -> &V { self.get(index).expect("index out of bounds") } } impl<'a, V, Ix: Index> ops::IndexMut<Ix> for Stash<V, Ix> { #[inline] fn index_mut(&mut self, index: Ix) -> &mut V { self.get_mut(index).expect("index out of bounds") } } impl<V, Ix: Index> Default for Stash<V, Ix> { #[inline] fn default() -> Self { Stash { data: Vec::new(), next_free: 0, size: 0, _marker: marker::PhantomData, } } } #[cfg(feature = "serialization")] mod serialization { use super::*; use serde::de::{ SeqAccess, Visitor, Deserialize, Deserializer }; use serde::ser::{ SerializeSeq, Serialize, Serializer }; impl<V, Ix> Serialize for Stash<V, Ix> where V: Serialize, Ix: Index, { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut seq = serializer.serialize_seq(Some(self.data.len()))?; for e in &self.data { let option = match e { Entry::Full(v) => Some(v), Entry::Empty(_) => None, }; seq.serialize_element(&option)?; } seq.end() } } impl<'de, V, Ix> Deserialize<'de> for Stash<V, Ix> where V: Deserialize<'de>, Ix: Index, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(StashVisitor::new()) } } struct StashVisitor<V, Ix> { _marker: marker::PhantomData<fn(V) -> Ix>, } impl<V, Ix> StashVisitor<V, Ix> { fn new() -> StashVisitor<V, Ix> { StashVisitor { _marker: marker::PhantomData, } } } impl<'de, V, Ix> Visitor<'de> for StashVisitor<V, Ix> where V: Deserialize<'de>, Ix: Index, { type Value = Stash<V, Ix>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a sequence of optional values") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let initial_size = seq.size_hint().unwrap_or(8); let mut data = Vec::with_capacity(initial_size); let mut i = 0; let mut next_free = 0; let mut size = 0; let mut first_free = None; while let Some(option) = seq.next_element()? { match option { Some(v) => { data.push(Entry::Full(v)); size += 1; } None => { if first_free.is_none() { first_free = Some(i); } data.push(Entry::Empty(next_free)); next_free = i; } } i += 1; } // fix the last entry in linked list now that we know total length. if let Some(Entry::Empty(ref mut next)) = first_free.and_then(|e|data.get_mut(e)) { *next = i; } else { next_free = i; } Ok(Stash { data, next_free, size, _marker: marker::PhantomData, }) } } }