vec_cell/lib.rs
1//! `VecCell` is a `Vec` with interior mutability and dynamically checked borrow rules.
2//! `VecCell` allows to take disjoint mutable borrows to its elements.
3//!
4//! # Example
5//!
6//! ```
7//! use vec_cell::VecCell;
8//!
9//! let mut vec_cell: VecCell<i32> = VecCell::new();
10//!
11//! vec_cell.push(0);
12//! vec_cell.push(1);
13//! vec_cell.push(2);
14//!
15//! {
16//! assert_eq!(*vec_cell.borrow(0), 0);
17//! assert_eq!(*vec_cell.borrow(1), 1);
18//! assert_eq!(*vec_cell.borrow(2), 2);
19//! }
20//!
21//! {
22//! let borrow_mut1 = &mut *vec_cell.borrow_mut(1);
23//! let borrow_mut2 = &mut *vec_cell.borrow_mut(2);
24//!
25//! *borrow_mut1 = 10;
26//! *borrow_mut2 = 15;
27//! }
28//!
29//! assert_eq!(vec_cell.pop(), Some(15));
30//! assert_eq!(vec_cell.pop(), Some(10));
31//! assert_eq!(vec_cell.pop(), Some(0));
32//! ```
33
34mod flatten;
35
36pub use flatten::Flatten;
37
38use std::cell::{Cell, UnsafeCell};
39use std::convert::From;
40use std::default::Default;
41use std::fmt::{self, Debug};
42use std::marker::PhantomData;
43use std::mem;
44use std::ops::{Deref, DerefMut, Drop};
45use std::ptr::NonNull;
46
47use thiserror::Error;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
50enum BorrowFlag {
51 NotBorrowed,
52 Reading(usize),
53 Writing,
54}
55
56#[derive(Debug)]
57struct BorrowRef<'borrow> {
58 borrow_flag: &'borrow Cell<BorrowFlag>,
59}
60
61impl<'borrow> BorrowRef<'borrow> {
62 fn new(borrow_flag: &'borrow Cell<BorrowFlag>) -> Option<Self> {
63 let b = match borrow_flag.get() {
64 BorrowFlag::NotBorrowed => BorrowFlag::Reading(1),
65 BorrowFlag::Reading(n) => BorrowFlag::Reading(n + 1),
66 BorrowFlag::Writing => return None,
67 };
68 borrow_flag.set(b);
69 Some(Self { borrow_flag })
70 }
71}
72
73impl Clone for BorrowRef<'_> {
74 fn clone(&self) -> Self {
75 match self.borrow_flag.get() {
76 BorrowFlag::Reading(n) => self.borrow_flag.set(BorrowFlag::Reading(n + 1)),
77 _ => unreachable!(),
78 }
79
80 Self {
81 borrow_flag: self.borrow_flag,
82 }
83 }
84}
85
86impl Drop for BorrowRef<'_> {
87 fn drop(&mut self) {
88 let b = match self.borrow_flag.get() {
89 BorrowFlag::Reading(n) if n > 1 => BorrowFlag::Reading(n - 1),
90 _ => BorrowFlag::NotBorrowed,
91 };
92
93 self.borrow_flag.set(b);
94 }
95}
96
97#[derive(Debug)]
98struct BorrowRefMut<'borrow> {
99 borrow_flag: &'borrow Cell<BorrowFlag>,
100}
101
102impl<'borrow> BorrowRefMut<'borrow> {
103 fn new(borrow_flag: &'borrow Cell<BorrowFlag>) -> Option<Self> {
104 match borrow_flag.get() {
105 BorrowFlag::NotBorrowed => {
106 borrow_flag.set(BorrowFlag::Writing);
107 Some(Self { borrow_flag })
108 }
109 _ => None,
110 }
111 }
112}
113
114impl Drop for BorrowRefMut<'_> {
115 fn drop(&mut self) {
116 self.borrow_flag.set(BorrowFlag::NotBorrowed);
117 }
118}
119
120/// A wrapper type for a immutably borrowed element from a `VecCell<T>`.
121pub struct ElementRef<'borrow, T: 'borrow> {
122 value: NonNull<T>,
123 borrow_ref: BorrowRef<'borrow>,
124}
125
126impl<'borrow, T: 'borrow> ElementRef<'borrow, T> {
127 /// Clones [`ElementRef`].
128 pub fn clone(orig: &ElementRef<'borrow, T>) -> ElementRef<'borrow, T> {
129 unsafe { ElementRef::new(orig.value.as_ptr(), orig.borrow_ref.clone()) }
130 }
131
132 /// Makes a new [`ElementRef`] for a compomnent of the borrowed data.
133 pub fn map<U, F>(orig: ElementRef<'borrow, T>, f: F) -> ElementRef<'borrow, U>
134 where F: FnOnce(&T) -> &U
135 {
136 // SAFETY: the pointer to the new value is nonnull
137 // because it is created from the reference.
138 unsafe { ElementRef::new(f(&*orig), orig.borrow_ref) }
139 }
140
141 // Creates new `ElementRef`.
142 //
143 // SAFETY: The caller needs to ensure that `value` is a nonnull pointer.
144 pub(crate) unsafe fn new(value: *const T, borrow_ref: BorrowRef<'borrow>) -> Self {
145 Self {
146 value: NonNull::new_unchecked(value as *mut T),
147 borrow_ref,
148 }
149 }
150}
151
152impl<T: Debug> Debug for ElementRef<'_, T> {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 f.write_fmt(format_args!("{:?}", **self))
155 }
156}
157
158impl<T> Deref for ElementRef<'_, T> {
159 type Target = T;
160
161 #[inline]
162 fn deref(&self) -> &Self::Target {
163 // SAFETY: Until `ElementRef` is dropped, `BorrowRef` ensures that there won't be
164 // any unique references which are aliasing with obtained shared references.
165 unsafe { self.value.as_ref() }
166 }
167}
168
169/// A wrapper type for a mutably borrowed element from a `VecCell<T>`.
170pub struct ElementRefMut<'borrow, T: 'borrow> {
171 value: NonNull<T>,
172 borrow_ref_mut: BorrowRefMut<'borrow>,
173
174 _p: PhantomData<&'borrow mut T>,
175}
176
177impl<'borrow, T: 'borrow> ElementRefMut<'borrow, T> {
178 /// Makes a new [`ElementRefMut`] for a compomnent of the borrowed data.
179 pub fn map<U, F>(mut orig: ElementRefMut<'borrow, T>, f: F) -> ElementRefMut<'borrow, U>
180 where F: FnOnce(&mut T) -> &mut U
181 {
182 // SAFETY: the pointer to the new value is nonnull
183 // because it is created from the reference.
184 unsafe { ElementRefMut::new(f(&mut *orig), orig.borrow_ref_mut) }
185 }
186
187 // Creates new `ElementRefMut`.
188 //
189 // SAFETY: The caller needs to ensure that `value` is a nonnull pointer.
190 pub(crate) unsafe fn new(value: *mut T, borrow_ref_mut: BorrowRefMut<'borrow>) -> Self {
191 Self {
192 value: NonNull::new_unchecked(value),
193 borrow_ref_mut,
194
195 _p: PhantomData,
196 }
197 }
198}
199
200impl<T: Debug> Debug for ElementRefMut<'_, T> {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 f.write_fmt(format_args!("{:?}", **self))
203 }
204}
205
206impl<T> Deref for ElementRefMut<'_, T> {
207 type Target = T;
208
209 #[inline]
210 fn deref(&self) -> &Self::Target {
211 // SAFETY: Until `ElementRefMut` is dropped, `BorrowRefMut` ensures that
212 // there won't be any references which are aliasing with obtained
213 // shared references except shared references to VecCell.
214 unsafe { self.value.as_ref() }
215 }
216}
217
218impl<T> DerefMut for ElementRefMut<'_, T> {
219 #[inline]
220 fn deref_mut(&mut self) -> &mut Self::Target {
221 // SAFETY: Until `ElementRefMut` is dropped, `BorrowRefMut` ensures that
222 // there won't be any references which are aliasing with obtained
223 // unique reference except shared references to VecCell.
224 unsafe { self.value.as_mut() }
225 }
226}
227
228/// An error which may occure after calling `VecCell::try_borrow` or `VecCell::try_borrow_mut`.
229#[derive(Error, Debug)]
230pub enum BorrowError {
231 #[error("element is out of bounds")]
232 ElementOutOfBounds,
233 #[error("element is already borrowed mutably")]
234 ElementAlreadyBorrowedMutably,
235 #[error("element is already borrowed")]
236 ElementAlreadyBorrowed,
237 #[error("{0}")]
238 Other(String),
239}
240
241impl From<String> for BorrowError {
242 fn from(value: String) -> Self {
243 BorrowError::Other(value)
244 }
245}
246
247/// A `Vec` with interior mutability and dynamically checked borrow rules
248/// when interacting with its elements.
249pub struct VecCell<T> {
250 data: UnsafeCell<Vec<T>>,
251 borrow_flags: Vec<Cell<BorrowFlag>>,
252
253 len: usize,
254}
255
256impl<T> VecCell<T> {
257 /// Creates a new empty `VecCell`.
258 ///
259 /// # Examples
260 ///
261 /// ```
262 /// use vec_cell::VecCell;
263 ///
264 /// let vec_cell: VecCell<i32> = VecCell::new();
265 /// ```
266 #[inline]
267 #[must_use]
268 pub fn new() -> Self {
269 Self {
270 data: UnsafeCell::new(vec![]),
271 borrow_flags: vec![],
272
273 len: 0,
274 }
275 }
276
277 /// Immutably borrows element with specified index.
278 ///
279 /// The borrow lasts until the returned `ElementRef` exits the scope.
280 /// During this period any number of immutable borrows can be obtained but no mutable ones.
281 ///
282 /// # Panics
283 /// Panics if the element is already borrowed mutably or `index` is out of bounds.
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// use vec_cell::VecCell;
289 ///
290 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
291 ///
292 /// assert_eq!(*vec_cell.borrow(0), 0);
293 /// assert_eq!(*vec_cell.borrow(1), 1);
294 /// assert_eq!(*vec_cell.borrow(2), 2);
295 /// ```
296 #[inline]
297 pub fn borrow(&self, index: usize) -> ElementRef<'_, T> {
298 self.try_borrow(index)
299 .unwrap_or_else(|err| panic!("Borrow error: {err}"))
300 }
301
302 /// Immutably borrows an element with specified index, returns an error if the element
303 /// is already borrowed mutably or its index is out of bounds.
304 ///
305 /// The borrow lasts until the returned `ElementRef` exits the scope.
306 /// During this period any number of immutable borrows can be obtained but no mutable ones.
307 ///
308 /// # Examples
309 ///
310 /// ```
311 /// use vec_cell::VecCell;
312 ///
313 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0]);
314 ///
315 /// {
316 /// let borrow = vec_cell.try_borrow(0);
317 /// assert!(vec_cell.try_borrow(0).is_ok());
318 /// }
319 ///
320 /// {
321 /// assert!(vec_cell.try_borrow(10).is_err());
322 /// }
323 ///
324 /// {
325 /// let borrow_mut = vec_cell.try_borrow_mut(0);
326 /// assert!(vec_cell.try_borrow(0).is_err())
327 /// }
328 /// ```
329 pub fn try_borrow(&self, index: usize) -> Result<ElementRef<'_, T>, BorrowError> {
330 self.borrow_flags
331 .get(index)
332 .ok_or(BorrowError::ElementOutOfBounds)
333 .and_then(|borrow_flag| {
334 BorrowRef::new(borrow_flag).ok_or(BorrowError::ElementAlreadyBorrowedMutably)
335 })
336 .and_then(|borrow_ref| {
337 (index < self.len)
338 .then(|| {
339 // SAFETY: Until `ElementRef` is dropped, `BorrowRef` ensures that we can't
340 // get any unique references which are aliasing with this pointer.
341 let element = unsafe { (*self.data.get()).as_ptr().add(index) };
342
343 // SAFETY: The pointer to the element is valid because:
344 // 1. The pointer to `Vec` which is obtained
345 // from `UnsafeCell` is always valid;
346 // 2. The element is inside the bounds of `Vec` because `index < len`.
347 unsafe { ElementRef::new(element, borrow_ref) }
348 })
349 .ok_or(BorrowError::ElementOutOfBounds)
350 })
351 }
352
353 /// Returns a reference to an element, without doing bounds and aliasing checking.
354 ///
355 /// # Safety
356 ///
357 /// Calling this method with an out-of-bounds index or if the element is already boroowed mutably
358 /// is undefined behavior.
359 ///
360 /// # Examples
361 ///
362 /// ```
363 /// use vec_cell::VecCell;
364 ///
365 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
366 ///
367 /// // let borrow_mut_unchecked = vec_cell.borrow_mut_unchecked(1); <--- UB
368 /// let borrow_unchecked = unsafe { vec_cell.borrow_unchecked(1) };
369 /// assert_eq!(borrow_unchecked, &1);
370 ///
371 /// ```
372 #[inline]
373 pub unsafe fn borrow_unchecked(&self, index: usize) -> &T {
374 (*self.data.get()).get_unchecked(index)
375 }
376
377 /// Mutably borrows element with specified index.
378 ///
379 /// The borrow lasts until the returned `ElementRefMut` exits the scope.
380 /// During this period no borrows can be obtained.
381 ///
382 /// # Panics
383 /// Panics if the element is already borrowed or `index` is out of bounds.
384 ///
385 /// # Examples
386 ///
387 /// ```
388 /// use vec_cell::VecCell;
389 ///
390 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0]);
391 ///
392 /// let mut borrow_mut = vec_cell.borrow_mut(0);
393 /// *borrow_mut = 42;
394 ///
395 /// assert_eq!(*borrow_mut, 42);
396 /// ```
397 #[inline]
398 pub fn borrow_mut(&self, index: usize) -> ElementRefMut<'_, T> {
399 self.try_borrow_mut(index)
400 .unwrap_or_else(|err| panic!("Mutable borrow error: {err}"))
401 }
402
403 /// Mutably borrows an element with specified index, returns an error if the element
404 /// is already borrowed or its index is out of bounds.
405 ///
406 /// The borrow lasts until the returned `ElementRefMut` exits the scope.
407 /// During this period no borrows can be obtained.
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// use vec_cell::VecCell;
413 ///
414 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0]);
415 ///
416 /// {
417 /// assert!(vec_cell.try_borrow_mut(0).is_ok());
418 /// assert!(vec_cell.try_borrow_mut(10).is_err())
419 /// }
420 ///
421 /// {
422 /// let borrow = vec_cell.try_borrow(0);
423 /// assert!(vec_cell.try_borrow_mut(0).is_err())
424 /// }
425 /// ```
426 pub fn try_borrow_mut(&self, index: usize) -> Result<ElementRefMut<'_, T>, BorrowError> {
427 self.borrow_flags
428 .get(index)
429 .ok_or(BorrowError::ElementOutOfBounds)
430 .and_then(|borrow_flag| {
431 BorrowRefMut::new(borrow_flag).ok_or(BorrowError::ElementAlreadyBorrowed)
432 })
433 .and_then(|borrow_ref_mut| {
434 (index < self.len)
435 .then(|| {
436 // SAFETY: Until `ElementRefMut` is dropped, `BorrowRefMut` ensures
437 // that we can't get any references which are aliasing with this
438 // pointer except shared references to VecCell.
439 let element = unsafe { (*self.data.get()).as_mut_ptr().add(index) };
440
441 // SAFETY: The pointer to the element is valid because:
442 // 1. The pointer to `Vec` which is obtained
443 // from `UnsafeCell` is always valid;
444 // 2. The element is inside the bounds of `Vec` because `index < len`.
445 unsafe { ElementRefMut::new(element, borrow_ref_mut) }
446 })
447 .ok_or(BorrowError::ElementOutOfBounds)
448 })
449 }
450
451 /// Returns a mutable reference to an element, without doing bounds and aliasing checking.
452 ///
453 /// # Safety
454 ///
455 /// Calling this method with an out-of-bounds index or if the element is already boroowed
456 /// is undefined behavior.
457 ///
458 /// # Examples
459 ///
460 /// ```
461 /// use vec_cell::VecCell;
462 ///
463 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
464 ///
465 /// // let borrow_unchecked = vec_cell.borrow_unchecked(1); <--- UB
466 ///
467 /// let borrow_mut_unchecked = unsafe { vec_cell.borrow_mut_unchecked(1) };
468 /// assert_eq!(borrow_mut_unchecked, &mut 1);
469 ///
470 /// *borrow_mut_unchecked = 2;
471 /// assert_eq!(borrow_mut_unchecked, &mut 2);
472 ///
473 /// ```
474 #[inline]
475 pub unsafe fn borrow_mut_unchecked(&self, index: usize) -> &mut T {
476 (*self.data.get()).get_unchecked_mut(index)
477 }
478
479 /// Returns the number of elements in `VecCell`.
480 ///
481 /// # Examples
482 ///
483 /// ```
484 /// use vec_cell::VecCell;
485 ///
486 /// let vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
487 /// assert_eq!(vec_cell.len(), 3);
488 /// ```
489 #[inline]
490 pub fn len(&self) -> usize {
491 self.len
492 }
493
494 /// Returns `true` if `VecCell` contains no elements.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use vec_cell::VecCell;
500 ///
501 /// let mut vec_cell: VecCell<i32> = VecCell::new();
502 /// assert!(vec_cell.is_empty());
503 ///
504 /// vec_cell.push(0);
505 /// assert!(!vec_cell.is_empty());
506 /// ```
507 #[inline]
508 pub fn is_empty(&self) -> bool {
509 self.len() == 0
510 }
511
512 /// Appends an element to the back of a `VecCell`.
513 ///
514 /// # Examples
515 ///
516 /// ```
517 /// use vec_cell::VecCell;
518 ///
519 /// let mut vec_cell: VecCell<i32> = VecCell::new();
520 /// vec_cell.push(0);
521 /// assert_eq!(*vec_cell.borrow(0), 0);
522 /// ```
523 #[inline]
524 pub fn push(&mut self, value: T) {
525 self.data.get_mut().push(value);
526 self.borrow_flags.push(Cell::new(BorrowFlag::NotBorrowed));
527
528 self.len += 1;
529 }
530
531 /// Removes the last element from a `VecCell` and returns it, or `None` if it is empty.
532 ///
533 /// # Examples
534 ///
535 /// ```
536 /// use vec_cell::VecCell;
537 ///
538 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
539 ///
540 /// assert_eq!(vec_cell.pop(), Some(2));
541 /// assert_eq!(vec_cell.pop(), Some(1));
542 /// assert_eq!(vec_cell.pop(), Some(0));
543 /// assert_eq!(vec_cell.pop(), None);
544 /// ```
545 #[inline]
546 pub fn pop(&mut self) -> Option<T> {
547 self.borrow_flags.pop();
548 self.data.get_mut().pop().map(|element| {
549 self.len -= 1;
550
551 element
552 })
553 }
554
555 /// Move all elements from `other` to `self`.
556 ///
557 /// # Examples
558 ///
559 /// ```
560 /// use vec_cell::VecCell;
561 ///
562 /// let mut vec_cell1: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
563 /// let mut vec_cell2: VecCell<i32> = VecCell::from(vec![3, 4, 5]);
564 ///
565 /// vec_cell1.append(&mut vec_cell2);
566 ///
567 /// for i in 0..6 {
568 /// assert_eq!(*vec_cell1.borrow(i), i as i32);
569 /// }
570 /// ```
571 #[inline]
572 pub fn append(&mut self, other: &mut VecCell<T>) {
573 self.len += other.len();
574
575 self.data.get_mut().append(other.data.get_mut());
576 self.borrow_flags.append(&mut other.borrow_flags);
577 }
578
579 /// Move all elements from `vec` to `self`.
580 ///
581 /// # Examples
582 ///
583 /// ```
584 /// use vec_cell::VecCell;
585 ///
586 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
587 /// let mut vec: Vec<i32> = vec![3, 4, 5];
588 ///
589 /// vec_cell.append_vec(&mut vec);
590 ///
591 /// for i in 0..6 {
592 /// assert_eq!(*vec_cell.borrow(i), i as i32);
593 /// }
594 /// ```
595 #[inline]
596 pub fn append_vec(&mut self, vec: &mut Vec<T>) {
597 self.len += vec.len();
598
599 self.borrow_flags
600 .append(&mut vec![Cell::new(BorrowFlag::NotBorrowed); vec.len()]);
601 self.data.get_mut().append(vec);
602 }
603
604 /// Insert an element at posiion `index`.
605 ///
606 /// # Panics
607 ///
608 /// Panics if `index` is out of bounds.
609 ///
610 /// # Examples
611 ///
612 /// ```
613 /// use vec_cell::VecCell;
614 ///
615 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
616 ///
617 /// vec_cell.insert(1, 3);
618 /// assert_eq!(*vec_cell.borrow(1), 3);
619 /// ```
620 #[inline]
621 pub fn insert(&mut self, index: usize, element: T) {
622 self.data.get_mut().insert(index, element);
623 self.borrow_flags
624 .insert(index, Cell::new(BorrowFlag::NotBorrowed));
625
626 self.len += 1;
627 }
628
629 /// Removes and returns the element at position `index`.
630 ///
631 /// # Panics
632 ///
633 /// Panics if `index` is out of bounds.
634 ///
635 /// # Examples
636 ///
637 /// ```
638 /// use vec_cell::VecCell;
639 ///
640 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
641 ///
642 /// let removed_element = vec_cell.remove(1);
643 /// assert_eq!(removed_element, 1);
644 /// ```
645 #[inline]
646 pub fn remove(&mut self, index: usize) -> T {
647 self.len -= 1;
648
649 self.borrow_flags.remove(index);
650 self.data.get_mut().remove(index)
651 }
652
653 /// Removes and returns the element at position `index`.
654 ///
655 /// The removed element is replaced by the last element.
656 ///
657 /// # Panics
658 ///
659 /// Panics if `index` is out of bounds.
660 ///
661 /// # Examples
662 ///
663 /// ```
664 /// use vec_cell::VecCell;
665 ///
666 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2, 3, 4, 5]);
667 ///
668 /// let removed_element = vec_cell.swap_remove(1);
669 /// assert_eq!(removed_element, 1);
670 /// assert_eq!(*vec_cell.borrow(1), 5);
671 /// ```
672 #[inline]
673 pub fn swap_remove(&mut self, index: usize) -> T {
674 self.len -= 1;
675
676 self.borrow_flags.swap_remove(index);
677 self.data.get_mut().swap_remove(index)
678 }
679
680 /// Replaces and returns the element at position `index` with `value`.
681 ///
682 /// # Panics
683 ///
684 /// Panics if `index` is out of bounds or element at position `index` is already borrowed.
685 ///
686 /// # Examples
687 ///
688 /// ```
689 /// use vec_cell::VecCell;
690 ///
691 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2, 3, 4, 5]);
692 ///
693 /// let replaced_element = vec_cell.replace(1, 10);
694 /// assert_eq!(replaced_element, 1);
695 /// assert_eq!(*vec_cell.borrow(1), 10);
696 /// ```
697 #[inline]
698 pub fn replace(&self, index: usize, value: T) -> T {
699 mem::replace(&mut *self.borrow_mut(index), value)
700 }
701}
702
703impl<T: Default> VecCell<T> {
704 /// Takes the element at position `index` and replaces it with `Default` value.
705 ///
706 /// # Panics
707 ///
708 /// Panics if `index` is out of bounds or element at position `index` is already borrowed.
709 ///
710 /// # Examples
711 ///
712 /// ```
713 /// use vec_cell::VecCell;
714 ///
715 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2, 3, 4, 5]);
716 ///
717 /// let taken_element = vec_cell.take(1);
718 /// assert_eq!(taken_element, 1);
719 /// assert_eq!(*vec_cell.borrow(1), 0);
720 /// ```
721 #[inline]
722 pub fn take(&self, index: usize) -> T {
723 self.try_take(index)
724 .unwrap_or_else(|err| panic!("Take error: {err}"))
725 }
726
727 /// Takes the element at position `index` and replaces it with `Default` value.
728 ///
729 /// If `index` is out of bounds or element at position `index`
730 /// is already borrowed, returns an error.
731 ///
732 /// # Examples
733 ///
734 /// ```
735 /// use vec_cell::VecCell;
736 ///
737 /// let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2, 3, 4, 5]);
738 ///
739 /// {
740 /// let taken_element = vec_cell.try_take(1);
741 /// assert_eq!(taken_element.unwrap(), 1);
742 /// assert_eq!(*vec_cell.borrow(1), 0);
743 /// }
744 ///
745 /// {
746 /// let taken_element = vec_cell.try_take(10);
747 /// assert!(taken_element.is_err());
748 /// }
749 ///
750 /// {
751 /// let borrow_mut = vec_cell.borrow_mut(2);
752 /// let taken_element = vec_cell.try_take(2);
753 /// assert!(taken_element.is_err());
754 /// }
755 /// ```
756 #[inline]
757 pub fn try_take(&self, index: usize) -> Result<T, BorrowError> {
758 self.try_borrow_mut(index)
759 .map(|mut element| mem::take(&mut *element))
760 }
761}
762
763impl<T: Debug> Debug for VecCell<T> {
764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765 enum ElementDebug<'borrow, T> {
766 Value(ElementRef<'borrow, T>),
767 Borrowed,
768 }
769
770 impl<T: Debug> Debug for ElementDebug<'_, T> {
771 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 match self {
773 Self::Value(element_ref) => f.write_fmt(format_args!("{:?}", element_ref)),
774 Self::Borrowed => f.write_str("<borrowed>"),
775 }
776 }
777 }
778
779 f.debug_list()
780 .entries(
781 (0..self.len())
782 .into_iter()
783 .map(|i| match self.try_borrow(i) {
784 Ok(element_ref) => ElementDebug::Value(element_ref),
785 Err(_) => ElementDebug::Borrowed,
786 }),
787 )
788 .finish()
789 }
790}
791
792impl<T> Default for VecCell<T> {
793 #[inline]
794 fn default() -> Self {
795 Self::new()
796 }
797}
798
799impl<T> From<Vec<T>> for VecCell<T> {
800 #[inline]
801 fn from(data: Vec<T>) -> Self {
802 let len = data.len();
803
804 Self {
805 data: UnsafeCell::new(data),
806 borrow_flags: vec![Cell::new(BorrowFlag::NotBorrowed); len],
807
808 len,
809 }
810 }
811}
812
813impl<T: Clone> From<&Vec<T>> for VecCell<T> {
814 #[inline]
815 fn from(data: &Vec<T>) -> Self {
816 Self::from(data.clone())
817 }
818}
819
820impl<T: Clone> From<&mut Vec<T>> for VecCell<T> {
821 #[inline]
822 fn from(data: &mut Vec<T>) -> Self {
823 Self::from(data.clone())
824 }
825}
826
827impl<T: Clone> From<&[T]> for VecCell<T> {
828 #[inline]
829 fn from(data: &[T]) -> Self {
830 Self::from(data.to_vec())
831 }
832}
833
834impl<T: Clone> From<&mut [T]> for VecCell<T> {
835 #[inline]
836 fn from(data: &mut [T]) -> Self {
837 Self::from(data.to_vec())
838 }
839}
840
841#[cfg(test)]
842mod test {
843 use super::*;
844
845 #[test]
846 fn test_borrow() {
847 let vec_cell: VecCell<i32> = VecCell::from(vec![0, 1]);
848
849 let element0_borrow1 = &*vec_cell.borrow(0);
850 let element0_borrow2 = &*vec_cell.borrow(0);
851
852 assert_eq!(*element0_borrow1, 0);
853 assert_eq!(*element0_borrow2, 0);
854 assert_eq!(*element0_borrow1, *element0_borrow2);
855
856 let element1_borrow1 = &*vec_cell.borrow(1);
857 let element1_borrow2 = &*vec_cell.borrow(1);
858
859 assert_eq!(*element1_borrow1, 1);
860 assert_eq!(*element1_borrow2, 1);
861 assert_eq!(*element1_borrow1, *element1_borrow2);
862 }
863
864 #[test]
865 fn test_borrow_mut() {
866 let vec_cell: VecCell<i32> = VecCell::from(vec![0, 1]);
867
868 let element0_borrow_mut1 = &mut *vec_cell.borrow_mut(0);
869 let element0_borrow_mut2 = vec_cell.try_borrow_mut(0);
870
871 assert_eq!(*element0_borrow_mut1, 0);
872 assert!(element0_borrow_mut2.is_err());
873
874 let element1_borrow_mut1 = &mut *vec_cell.borrow_mut(1);
875 let element1_borrow_mut2 = vec_cell.try_borrow_mut(1);
876
877 assert_eq!(*element1_borrow_mut1, 1);
878 assert!(element1_borrow_mut2.is_err());
879
880 *element0_borrow_mut1 = 3;
881 assert_eq!(*element0_borrow_mut1, 3);
882
883 *element1_borrow_mut1 = 4;
884 assert_eq!(*element1_borrow_mut1, 4);
885 }
886
887 #[test]
888 fn test_borrow_and_borrow_mut() {
889 let vec_cell: VecCell<i32> = VecCell::from(vec![0]);
890
891 let borrow = &*vec_cell.borrow(0);
892 assert_eq!(*borrow, 0);
893
894 let borrow_mut = vec_cell.try_borrow_mut(0);
895 assert!(borrow_mut.is_err());
896 }
897
898 #[test]
899 fn test_borrow_mut_and_borrow() {
900 let vec_cell: VecCell<i32> = VecCell::from(vec![0]);
901
902 let mut element_ref_mut = vec_cell.borrow_mut(0);
903 let borrow_mut = &mut *element_ref_mut;
904 assert_eq!(*borrow_mut, 0);
905
906 *borrow_mut = 1;
907 assert_eq!(*borrow_mut, 1);
908
909 let borrow = vec_cell.try_borrow(0);
910 assert!(borrow.is_err());
911
912 std::mem::drop(element_ref_mut);
913
914 let borrow = &*vec_cell.borrow(0);
915 assert_eq!(*borrow, 1);
916 }
917
918 #[test]
919 fn test_len() {
920 let mut vec_cell: VecCell<i32> = VecCell::new();
921 assert!(vec_cell.is_empty());
922
923 vec_cell.push(0);
924 assert_eq!(vec_cell.len(), 1);
925
926 {
927 let borrow_mut = &mut *vec_cell.borrow_mut(0);
928 let shared_ref = &vec_cell;
929
930 *borrow_mut = 10;
931 assert_eq!(shared_ref.len(), 1);
932 }
933
934 vec_cell.push(1);
935 assert_eq!(vec_cell.len(), 2);
936 }
937
938 #[test]
939 fn test_push() {
940 let mut vec_cell: VecCell<i32> = VecCell::new();
941
942 assert!(vec_cell.try_borrow(0).is_err());
943 assert!(vec_cell.is_empty());
944
945 vec_cell.push(0);
946 vec_cell.push(1);
947 vec_cell.push(2);
948
949 assert_eq!(*vec_cell.borrow(0), 0);
950 assert_eq!(*vec_cell.borrow(1), 1);
951 assert_eq!(*vec_cell.borrow(2), 2);
952 assert!(!vec_cell.is_empty());
953 }
954
955 #[test]
956 fn test_pop() {
957 let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
958
959 assert_eq!(*vec_cell.borrow(0), 0);
960 assert_eq!(*vec_cell.borrow(1), 1);
961 assert_eq!(*vec_cell.borrow(2), 2);
962 assert!(!vec_cell.is_empty());
963
964 assert_eq!(vec_cell.pop(), Some(2));
965 assert_eq!(vec_cell.pop(), Some(1));
966 assert_eq!(vec_cell.pop(), Some(0));
967
968 assert!(vec_cell.is_empty());
969 }
970
971 #[test]
972 fn test_append() {
973 let mut vec_cell1: VecCell<usize> = VecCell::from(vec![0, 1, 2]);
974 let mut vec_cell2: VecCell<usize> = VecCell::from(vec![3, 4, 5]);
975
976 vec_cell1.append(&mut vec_cell2);
977
978 assert_eq!(vec_cell1.len(), 6);
979
980 for i in 0..6 {
981 assert_eq!(*vec_cell1.borrow(i), i);
982 }
983 }
984
985 #[test]
986 fn test_append_vec() {
987 let mut vec_cell: VecCell<usize> = VecCell::from(vec![0, 1, 2]);
988 let mut vec: Vec<usize> = vec![3, 4, 5];
989
990 vec_cell.append_vec(&mut vec);
991
992 assert_eq!(vec_cell.len(), 6);
993
994 for i in 0..6 {
995 assert_eq!(*vec_cell.borrow(i), i);
996 }
997 }
998
999 #[test]
1000 fn test_insert() {
1001 let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2, 3, 4, 5]);
1002
1003 assert_eq!(vec_cell.len(), 6);
1004 assert_eq!(*vec_cell.borrow(1), 1);
1005
1006 vec_cell.insert(1, 6);
1007 assert_eq!(vec_cell.len(), 7);
1008 assert_eq!(*vec_cell.borrow(1), 6);
1009
1010 assert_eq!(*vec_cell.borrow(4), 3);
1011
1012 vec_cell.insert(4, 7);
1013 assert_eq!(vec_cell.len(), 8);
1014 assert_eq!(*vec_cell.borrow(4), 7);
1015 }
1016
1017 #[test]
1018 fn test_remove() {
1019 let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
1020
1021 assert_eq!(vec_cell.len(), 3);
1022
1023 assert_eq!(vec_cell.remove(0), 0);
1024 assert_eq!(vec_cell.len(), 2);
1025
1026 assert_eq!(vec_cell.remove(1), 2);
1027 assert_eq!(vec_cell.len(), 1);
1028
1029 assert_eq!(vec_cell.remove(0), 1);
1030 assert!(vec_cell.is_empty());
1031 }
1032
1033 #[test]
1034 fn test_swap_remove() {
1035 let mut vec_cell: VecCell<i32> = VecCell::from(vec![0, 1, 2]);
1036
1037 assert_eq!(vec_cell.len(), 3);
1038
1039 assert_eq!(vec_cell.swap_remove(0), 0);
1040 assert_eq!(*vec_cell.borrow(0), 2);
1041 assert_eq!(vec_cell.len(), 2);
1042
1043 assert_eq!(vec_cell.swap_remove(0), 2);
1044 assert_eq!(*vec_cell.borrow(0), 1);
1045 assert_eq!(vec_cell.len(), 1);
1046
1047 assert_eq!(vec_cell.swap_remove(0), 1);
1048 assert!(vec_cell.is_empty());
1049 }
1050
1051 #[test]
1052 fn test_element_ref_map() {
1053 struct Test {
1054 a: i32,
1055 b: i32,
1056 }
1057
1058 let vec_cell: VecCell<Test> = VecCell::from(vec![Test { a: 0, b: 1 }]);
1059 let element_borrow = vec_cell.borrow(0);
1060
1061 let a_borrow = ElementRef::map(ElementRef::clone(&element_borrow), |eb| &eb.a);
1062 assert_eq!(*a_borrow, 0);
1063
1064 let b_borrow = ElementRef::map(element_borrow, |eb| &eb.b);
1065 assert_eq!(*b_borrow, 1);
1066 }
1067
1068 #[test]
1069 fn test_element_ref_mut_map() {
1070 struct Test {
1071 a: i32,
1072 b: i32,
1073 }
1074
1075 let vec_cell: VecCell<Test> = VecCell::from(vec![Test { a: 0, b: 1 }]);
1076
1077 {
1078 let element_borrow_mut = vec_cell.borrow_mut(0);
1079
1080 let mut a_borrow = ElementRefMut::map(element_borrow_mut, |eb| &mut eb.a);
1081 assert_eq!(*a_borrow, 0);
1082
1083 *a_borrow = 2;
1084 assert_eq!(*a_borrow, 2);
1085 }
1086
1087 {
1088 let element_borrow_mut = vec_cell.borrow_mut(0);
1089
1090 let mut b_borrow = ElementRefMut::map(element_borrow_mut, |eb| &mut eb.b);
1091 assert_eq!(*b_borrow, 1);
1092
1093 *b_borrow = 3;
1094 assert_eq!(*b_borrow, 3);
1095 }
1096 }
1097}