rpds/vector/
mod.rs

1use alloc::borrow::Borrow;
2use alloc::fmt::Display;
3use alloc::vec::Vec;
4use archery::*;
5use core::cmp::Ordering;
6use core::hash::{Hash, Hasher};
7use core::iter::FromIterator;
8use core::ops::Index;
9use core::ops::IndexMut;
10
11// TODO Use impl trait instead of this when available.
12pub type Iter<'a, T, P> = core::iter::Map<IterPtr<'a, T, P>, fn(&SharedPointer<T, P>) -> &T>;
13
14const DEFAULT_BITS: u8 = 5;
15
16/// Creates a [`Vector`](crate::Vector) containing the given arguments:
17///
18/// ```
19/// # use rpds::*;
20/// #
21/// let v = Vector::new()
22///     .push_back(1)
23///     .push_back(2)
24///     .push_back(3);
25///
26/// assert_eq!(vector![1, 2, 3], v);
27/// ```
28#[macro_export]
29macro_rules! vector {
30    ($($e:expr),*) => {
31        {
32            #[allow(unused_mut)]
33            let mut v = $crate::Vector::new();
34            $(
35                v.push_back_mut($e);
36            )*
37            v
38        }
39    };
40}
41
42/// Creates a [`Vector`](crate::Vector) that implements `Sync`, containing the given arguments:
43///
44/// ```
45/// # use rpds::*;
46/// #
47/// let v = Vector::new_sync()
48///     .push_back(1)
49///     .push_back(2)
50///     .push_back(3);
51///
52/// assert_eq!(vector_sync![1, 2, 3], v);
53/// ```
54#[macro_export]
55macro_rules! vector_sync {
56    ($($e:expr),*) => {
57        {
58            #[allow(unused_mut)]
59            let mut v = $crate::Vector::new_sync();
60            $(
61                v.push_back_mut($e);
62            )*
63            v
64        }
65    };
66}
67
68/// A persistent vector with structural sharing.
69///
70/// # Complexity
71///
72/// Let *n* be the number of elements in the vector.
73///
74/// ## Temporal complexity
75///
76/// | Operation                  | Average   | Worst case  |
77/// |:-------------------------- | ---------:| -----------:|
78/// | `new()`                    |      Θ(1) |        Θ(1) |
79/// | `set()`                    | Θ(log(n)) |   Θ(log(n)) |
80/// | `push_back()`              | Θ(log(n)) |   Θ(log(n)) |
81/// | `drop_last()`              | Θ(log(n)) |   Θ(log(n)) |
82/// | `first()`/`last()`/`get()` | Θ(log(n)) |   Θ(log(n)) |
83/// | `len()`                    |      Θ(1) |        Θ(1) |
84/// | `clone()`                  |      Θ(1) |        Θ(1) |
85/// | iterator creation          |      Θ(1) |        Θ(1) |
86/// | iterator step              |      Θ(1) |   Θ(log(n)) |
87/// | iterator full              |      Θ(n) |        Θ(n) |
88///
89/// # Implementation details
90///
91/// This implementation uses a bitmapped vector trie as described in
92/// [Understanding Persistent Vector Part 1](http://hypirion.com/musings/understanding-persistent-vector-pt-1)
93/// and [Understanding Persistent Vector Part 2](http://hypirion.com/musings/understanding-persistent-vector-pt-2).
94#[derive(Debug)]
95pub struct Vector<T, P = RcK>
96where
97    P: SharedPointerKind,
98{
99    root: SharedPointer<Node<T, P>, P>,
100    bits: u8,
101    length: usize,
102}
103
104pub type VectorSync<T> = Vector<T, ArcTK>;
105
106#[derive(Debug)]
107enum Node<T, P = RcK>
108where
109    P: SharedPointerKind,
110{
111    Branch(Vec<SharedPointer<Node<T, P>, P>>),
112    Leaf(Vec<SharedPointer<T, P>>),
113}
114
115impl<T, P> Node<T, P>
116where
117    P: SharedPointerKind,
118{
119    fn new_empty_branch() -> Node<T, P> {
120        Node::Branch(Vec::new())
121    }
122
123    fn new_empty_leaf() -> Node<T, P> {
124        Node::Leaf(Vec::new())
125    }
126
127    fn get<F: Fn(usize, usize) -> usize>(&self, index: usize, height: usize, bucket: F) -> &T {
128        let b = bucket(index, height);
129
130        match self {
131            Node::Branch(a) => a[b].get(index, height - 1, bucket),
132            Node::Leaf(a) => {
133                debug_assert_eq!(height, 0);
134                a[b].as_ref()
135            }
136        }
137    }
138
139    fn assoc<F: Fn(usize) -> usize>(&mut self, value: T, height: usize, bucket: F) {
140        let b = bucket(height);
141
142        match self {
143            Node::Leaf(a) => {
144                debug_assert_eq!(height, 0, "cannot have a leaf at this height");
145
146                if a.len() == b {
147                    a.push(SharedPointer::new(value));
148                } else {
149                    a[b] = SharedPointer::new(value);
150                }
151            }
152
153            Node::Branch(a) => {
154                debug_assert!(height > 0, "cannot have a branch at this height");
155
156                match a.get_mut(b) {
157                    Some(subtree) => {
158                        SharedPointer::make_mut(subtree).assoc(value, height - 1, bucket);
159                    }
160                    None => {
161                        let mut subtree = if height > 1 {
162                            Node::new_empty_branch()
163                        } else {
164                            Node::new_empty_leaf()
165                        };
166
167                        subtree.assoc(value, height - 1, bucket);
168                        a.push(SharedPointer::new(subtree));
169                    }
170                }
171            }
172        }
173    }
174
175    #[inline]
176    fn is_empty(&self) -> bool {
177        self.used() == 0
178    }
179
180    #[inline]
181    fn is_singleton(&self) -> bool {
182        self.used() == 1
183    }
184
185    fn used(&self) -> usize {
186        match self {
187            Node::Leaf(a) => a.len(),
188            Node::Branch(a) => a.len(),
189        }
190    }
191
192    /// Drops the last element.
193    ///
194    /// This will return `true` if the subtree after drop becomes empty (or it already was empty).
195    /// Note that this will prune irrelevant branches, i.e. there will be no branches without
196    /// elements under it.
197    fn drop_last(&mut self) -> bool {
198        if self.is_empty() {
199            return true;
200        }
201
202        match self {
203            Node::Leaf(a) => {
204                a.pop();
205            }
206
207            Node::Branch(a) => {
208                if SharedPointer::make_mut(a.last_mut().unwrap()).drop_last() {
209                    a.pop();
210                }
211            }
212        }
213
214        self.is_empty()
215    }
216}
217
218impl<T: Clone, P> Node<T, P>
219where
220    P: SharedPointerKind,
221{
222    fn get_mut<F: Fn(usize, usize) -> usize>(
223        &mut self,
224        index: usize,
225        height: usize,
226        bucket: F,
227    ) -> &mut T {
228        let b = bucket(index, height);
229
230        match *self {
231            Node::Branch(ref mut a) => {
232                SharedPointer::make_mut(&mut a[b]).get_mut(index, height - 1, bucket)
233            }
234            Node::Leaf(ref mut a) => {
235                debug_assert_eq!(height, 0);
236                SharedPointer::make_mut(&mut a[b])
237            }
238        }
239    }
240}
241
242impl<T, P> Clone for Node<T, P>
243where
244    P: SharedPointerKind,
245{
246    fn clone(&self) -> Node<T, P> {
247        match self {
248            Node::Branch(a) => Node::Branch(Vec::clone(a)),
249            Node::Leaf(a) => Node::Leaf(Vec::clone(a)),
250        }
251    }
252}
253
254mod vector_utils {
255    #[inline]
256    pub fn degree(bits: u8) -> usize {
257        1 << bits
258    }
259
260    #[inline]
261    pub fn mask(bits: u8) -> usize {
262        degree(bits) - 1
263    }
264
265    #[inline]
266    pub fn bucket(bits: u8, index: usize, height: usize) -> usize {
267        (index >> (height * bits as usize)) & mask(bits)
268    }
269}
270
271impl<T> VectorSync<T> {
272    #[must_use]
273    pub fn new_sync() -> VectorSync<T> {
274        Vector::new_with_ptr_kind()
275    }
276}
277
278impl<T> Vector<T> {
279    #[must_use]
280    pub fn new() -> Vector<T> {
281        Vector::new_with_ptr_kind()
282    }
283}
284
285impl<T, P> Vector<T, P>
286where
287    P: SharedPointerKind,
288{
289    #[must_use]
290    pub fn new_with_ptr_kind() -> Vector<T, P> {
291        Vector::new_with_bits(DEFAULT_BITS)
292    }
293
294    #[must_use]
295    pub fn new_with_bits(bits: u8) -> Vector<T, P> {
296        assert!(bits > 0, "number of bits for the vector must be positive");
297
298        Vector { root: SharedPointer::new(Node::new_empty_leaf()), bits, length: 0 }
299    }
300
301    #[must_use]
302    #[inline]
303    pub fn first(&self) -> Option<&T> {
304        self.get(0)
305    }
306
307    #[must_use]
308    pub fn last(&self) -> Option<&T> {
309        match self.length {
310            0 => None,
311            n => self.get(n - 1),
312        }
313    }
314
315    #[inline]
316    fn height(&self) -> usize {
317        if self.length > 1 {
318            let u: usize = self.length - 1;
319            let c: usize = usize::BITS as usize - u.leading_zeros() as usize;
320            let b: usize = self.bits as usize;
321
322            c / b + usize::from(c % b > 0) - 1
323        } else {
324            0
325        }
326    }
327
328    #[must_use]
329    pub fn get(&self, index: usize) -> Option<&T> {
330        if index >= self.length {
331            None
332        } else {
333            Some(self.root.get(index, self.height(), |index, height| {
334                vector_utils::bucket(self.bits, index, height)
335            }))
336        }
337    }
338
339    #[must_use]
340    pub fn set(&self, index: usize, v: T) -> Option<Vector<T, P>> {
341        let mut new_vector = self.clone();
342
343        if new_vector.set_mut(index, v) { Some(new_vector) } else { None }
344    }
345
346    /// Returns `true` if the operation was successful.
347    pub fn set_mut(&mut self, index: usize, v: T) -> bool {
348        if index >= self.length {
349            false
350        } else {
351            self.assoc(index, v);
352            true
353        }
354    }
355
356    /// Sets the given index to v.
357    ///
358    /// # Panics
359    ///
360    /// This method will panic if the trie's root doesn't have capacity for the given index.
361    fn assoc(&mut self, index: usize, v: T) {
362        debug_assert!(
363            index < self.root_max_capacity(),
364            "This trie's root cannot support this index"
365        );
366
367        let height = self.height();
368        let bits = self.bits;
369        SharedPointer::make_mut(&mut self.root)
370            .assoc(v, height, |height| vector_utils::bucket(bits, index, height));
371        let adds_item: bool = index >= self.length;
372
373        if adds_item {
374            self.length += 1;
375        }
376    }
377
378    #[inline]
379    fn root_max_capacity(&self) -> usize {
380        /* A Trie's root max capacity is
381         *
382         *     degree ** (height + 1)
383         *   = (2 ** bits) ** (height + 1)        (by def. of degree)
384         *   = 2 ** (bits * (height + 1))
385         *   = 1 << (bits * (height + 1))
386         */
387        1 << (self.bits as usize * (self.height() + 1))
388    }
389
390    #[inline]
391    fn is_root_full(&self) -> bool {
392        self.length == self.root_max_capacity()
393    }
394
395    #[must_use]
396    pub fn push_back(&self, v: T) -> Vector<T, P> {
397        let mut new_vector = self.clone();
398
399        new_vector.push_back_mut(v);
400
401        new_vector
402    }
403
404    pub fn push_back_mut(&mut self, v: T) {
405        if self.is_root_full() {
406            let mut new_root: Node<T, P> = Node::new_empty_branch();
407
408            match new_root {
409                Node::Branch(ref mut values) => values.push(SharedPointer::clone(&self.root)),
410                Node::Leaf(_) => unreachable!("expected a branch"),
411            }
412
413            let length = self.length;
414            self.root = SharedPointer::new(new_root);
415            self.length += 1;
416
417            self.assoc(length, v);
418        } else {
419            let length = self.length;
420            self.assoc(length, v);
421        }
422    }
423
424    /// Compresses a root.  A root is compressed if, whenever there is a branch, it has more than
425    /// one child.
426    ///
427    /// The trie must always have a compressed root.
428    fn compress_root(root: &mut Node<T, P>) -> Option<SharedPointer<Node<T, P>, P>> {
429        let singleton = root.is_singleton();
430
431        match root {
432            Node::Leaf(_) => None,
433            Node::Branch(a) if singleton => a.pop(),
434            Node::Branch(_) => None,
435        }
436    }
437
438    #[must_use]
439    pub fn drop_last(&self) -> Option<Vector<T, P>> {
440        let mut new_vector = self.clone();
441
442        if new_vector.drop_last_mut() { Some(new_vector) } else { None }
443    }
444
445    pub fn drop_last_mut(&mut self) -> bool {
446        if self.length > 0 {
447            let new_root = {
448                let root = SharedPointer::make_mut(&mut self.root);
449
450                root.drop_last();
451                self.length -= 1;
452
453                Vector::compress_root(root)
454            };
455
456            if let Some(new_root) = new_root {
457                self.root = new_root;
458            }
459
460            true
461        } else {
462            false
463        }
464    }
465
466    #[must_use]
467    #[inline]
468    pub fn len(&self) -> usize {
469        self.length
470    }
471
472    #[must_use]
473    #[inline]
474    pub fn is_empty(&self) -> bool {
475        self.len() == 0
476    }
477
478    pub fn iter(&self) -> Iter<'_, T, P> {
479        self.iter_ptr().map(|v| v.borrow())
480    }
481
482    #[must_use]
483    fn iter_ptr(&self) -> IterPtr<'_, T, P> {
484        IterPtr::new(self)
485    }
486}
487
488impl<T: Clone, P> Vector<T, P>
489where
490    P: SharedPointerKind,
491{
492    /// Gets a mutable reference to an element. If the element is shared, it will be cloned.
493    /// Returns `None` if and only if the given `index` is out of range.
494    #[must_use]
495    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
496        if index >= self.length {
497            None
498        } else {
499            let height = self.height();
500            let bits = self.bits;
501            Some(
502                SharedPointer::make_mut(&mut self.root).get_mut(index, height, |index, height| {
503                    vector_utils::bucket(bits, index, height)
504                }),
505            )
506        }
507    }
508}
509
510impl<T, P> Index<usize> for Vector<T, P>
511where
512    P: SharedPointerKind,
513{
514    type Output = T;
515
516    fn index(&self, index: usize) -> &T {
517        self.get(index).unwrap_or_else(|| panic!("index out of bounds {index}"))
518    }
519}
520
521impl<T: Clone, P> IndexMut<usize> for Vector<T, P>
522where
523    P: SharedPointerKind,
524{
525    fn index_mut(&mut self, index: usize) -> &mut T {
526        self.get_mut(index).unwrap_or_else(|| panic!("index out of bounds {index}"))
527    }
528}
529
530impl<T, P> Default for Vector<T, P>
531where
532    P: SharedPointerKind,
533{
534    fn default() -> Vector<T, P> {
535        Vector::new_with_ptr_kind()
536    }
537}
538
539impl<T: PartialEq<U>, U, P, PO> PartialEq<Vector<U, PO>> for Vector<T, P>
540where
541    P: SharedPointerKind,
542    PO: SharedPointerKind,
543{
544    fn eq(&self, other: &Vector<U, PO>) -> bool {
545        self.length == other.length && self.iter().eq(other.iter())
546    }
547}
548
549impl<T: Eq, P> Eq for Vector<T, P> where P: SharedPointerKind {}
550
551impl<T: PartialOrd<U>, U, P, PO> PartialOrd<Vector<U, PO>> for Vector<T, P>
552where
553    P: SharedPointerKind,
554    PO: SharedPointerKind,
555{
556    fn partial_cmp(&self, other: &Vector<U, PO>) -> Option<Ordering> {
557        self.iter().partial_cmp(other.iter())
558    }
559}
560
561impl<T: Ord, P> Ord for Vector<T, P>
562where
563    P: SharedPointerKind,
564{
565    fn cmp(&self, other: &Vector<T, P>) -> Ordering {
566        self.iter().cmp(other.iter())
567    }
568}
569
570impl<T: Hash, P> Hash for Vector<T, P>
571where
572    P: SharedPointerKind,
573{
574    fn hash<H: Hasher>(&self, state: &mut H) {
575        // Add the hash of length so that if two collections are added one after the other it doesn't
576        // hash to the same thing as a single collection with the same elements in the same order.
577        self.len().hash(state);
578
579        for e in self {
580            e.hash(state);
581        }
582    }
583}
584
585impl<T, P> Clone for Vector<T, P>
586where
587    P: SharedPointerKind,
588{
589    fn clone(&self) -> Vector<T, P> {
590        Vector { root: SharedPointer::clone(&self.root), bits: self.bits, length: self.length }
591    }
592}
593
594impl<T: Display, P> Display for Vector<T, P>
595where
596    P: SharedPointerKind,
597{
598    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
599        let mut first = true;
600
601        fmt.write_str("[")?;
602
603        for v in self {
604            if !first {
605                fmt.write_str(", ")?;
606            }
607            v.fmt(fmt)?;
608            first = false;
609        }
610
611        fmt.write_str("]")
612    }
613}
614
615impl<'a, T, P> IntoIterator for &'a Vector<T, P>
616where
617    P: SharedPointerKind,
618{
619    type Item = &'a T;
620    type IntoIter = Iter<'a, T, P>;
621
622    fn into_iter(self) -> Iter<'a, T, P> {
623        self.iter()
624    }
625}
626
627impl<T, P> FromIterator<T> for Vector<T, P>
628where
629    P: SharedPointerKind,
630{
631    fn from_iter<I: IntoIterator<Item = T>>(into_iter: I) -> Vector<T, P> {
632        let mut vector = Vector::new_with_ptr_kind();
633        vector.extend(into_iter);
634        vector
635    }
636}
637
638impl<T, P> Extend<T> for Vector<T, P>
639where
640    P: SharedPointerKind,
641{
642    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
643        for elem in iter {
644            self.push_back_mut(elem);
645        }
646    }
647}
648
649pub struct IterPtr<'a, T, P>
650where
651    P: SharedPointerKind,
652{
653    vector: &'a Vector<T, P>,
654
655    stack_forward: Option<Vec<IterStackElement<'a, T, P>>>,
656    stack_backward: Option<Vec<IterStackElement<'a, T, P>>>,
657
658    left_index: usize,  // inclusive
659    right_index: usize, // exclusive
660}
661
662struct IterStackElement<'a, T, P>
663where
664    P: SharedPointerKind,
665{
666    node: &'a Node<T, P>,
667    index: isize,
668}
669
670impl<'a, T, P> IterStackElement<'a, T, P>
671where
672    P: SharedPointerKind,
673{
674    fn new(node: &Node<T, P>, backwards: bool) -> IterStackElement<'_, T, P> {
675        #[allow(clippy::cast_possible_wrap)]
676        IterStackElement { node, index: if backwards { node.used() as isize - 1 } else { 0 } }
677    }
678
679    #[inline]
680    fn current_node(&self) -> &'a Node<T, P> {
681        #[allow(clippy::cast_sign_loss)]
682        match self.node {
683            Node::Branch(a) => a[self.index as usize].as_ref(),
684            Node::Leaf(_) => panic!("called current node of a branch"),
685        }
686    }
687
688    #[inline]
689    fn current_elem(&self) -> &'a SharedPointer<T, P> {
690        #[allow(clippy::cast_sign_loss)]
691        match self.node {
692            Node::Leaf(a) => &a[self.index as usize],
693            Node::Branch(_) => panic!("called current element of a branch"),
694        }
695    }
696
697    /// Advance and returns `true` if finished.
698    #[inline]
699    fn advance(&mut self, backwards: bool) -> bool {
700        #[allow(clippy::cast_sign_loss)]
701        if backwards {
702            self.index -= 1;
703            self.index < 0
704        } else {
705            self.index += 1;
706            self.index as usize >= self.node.used()
707        }
708    }
709}
710
711impl<'a, T, P> IterPtr<'a, T, P>
712where
713    P: SharedPointerKind,
714{
715    fn new(vector: &Vector<T, P>) -> IterPtr<'_, T, P> {
716        IterPtr {
717            vector,
718
719            stack_forward: None,
720            stack_backward: None,
721
722            left_index: 0,
723            right_index: vector.len(),
724        }
725    }
726
727    fn dig(stack: &mut Vec<IterStackElement<'_, T, P>>, backwards: bool) {
728        let next_node: &Node<T, P> = {
729            let stack_top = stack.last().unwrap();
730
731            if let Node::Leaf(_) = *stack_top.node {
732                return;
733            }
734
735            stack_top.current_node()
736        };
737
738        stack.push(IterStackElement::new(next_node, backwards));
739
740        IterPtr::dig(stack, backwards);
741    }
742
743    fn init_if_needed(&mut self, backwards: bool) {
744        let stack_field =
745            if backwards { &mut self.stack_backward } else { &mut self.stack_forward };
746
747        if stack_field.is_none() {
748            let mut stack: Vec<IterStackElement<'_, T, P>> =
749                Vec::with_capacity(self.vector.height() + 1);
750
751            stack.push(IterStackElement::new(self.vector.root.borrow(), backwards));
752
753            IterPtr::dig(&mut stack, backwards);
754
755            *stack_field = Some(stack);
756        }
757    }
758
759    fn advance(stack: &mut Vec<IterStackElement<'_, T, P>>, backwards: bool) {
760        if let Some(mut stack_element) = stack.pop() {
761            let finished = stack_element.advance(backwards);
762
763            if finished {
764                IterPtr::advance(stack, backwards);
765            } else {
766                stack.push(stack_element);
767
768                IterPtr::dig(stack, backwards);
769            }
770        }
771    }
772
773    #[inline]
774    fn current(stack: &[IterStackElement<'a, T, P>]) -> Option<&'a SharedPointer<T, P>> {
775        stack.last().map(IterStackElement::current_elem)
776    }
777
778    #[inline]
779    fn non_empty(&self) -> bool {
780        self.left_index < self.right_index
781    }
782
783    fn advance_forward(&mut self) {
784        if self.non_empty() {
785            IterPtr::advance(self.stack_forward.as_mut().unwrap(), false);
786
787            self.left_index += 1;
788        }
789    }
790
791    fn current_forward(&self) -> Option<&'a SharedPointer<T, P>> {
792        if self.non_empty() { IterPtr::current(self.stack_forward.as_ref().unwrap()) } else { None }
793    }
794
795    fn advance_backward(&mut self) {
796        if self.non_empty() {
797            IterPtr::advance(self.stack_backward.as_mut().unwrap(), true);
798
799            self.right_index -= 1;
800        }
801    }
802
803    fn current_backward(&self) -> Option<&'a SharedPointer<T, P>> {
804        if self.non_empty() {
805            IterPtr::current(self.stack_backward.as_ref().unwrap())
806        } else {
807            None
808        }
809    }
810}
811
812impl<'a, T, P> Iterator for IterPtr<'a, T, P>
813where
814    P: SharedPointerKind,
815{
816    type Item = &'a SharedPointer<T, P>;
817
818    fn next(&mut self) -> Option<&'a SharedPointer<T, P>> {
819        self.init_if_needed(false);
820
821        let current = self.current_forward();
822
823        self.advance_forward();
824
825        current
826    }
827
828    fn size_hint(&self) -> (usize, Option<usize>) {
829        let len = self.right_index - self.left_index;
830
831        (len, Some(len))
832    }
833}
834
835impl<'a, T, P> DoubleEndedIterator for IterPtr<'a, T, P>
836where
837    P: SharedPointerKind,
838{
839    fn next_back(&mut self) -> Option<&'a SharedPointer<T, P>> {
840        self.init_if_needed(true);
841
842        let current = self.current_backward();
843
844        self.advance_backward();
845
846        current
847    }
848}
849
850impl<T, P> ExactSizeIterator for IterPtr<'_, T, P> where P: SharedPointerKind {}
851
852#[cfg(feature = "serde")]
853pub mod serde {
854    use super::*;
855    use ::serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
856    use ::serde::ser::{Serialize, Serializer};
857    use core::fmt;
858    use core::marker::PhantomData;
859
860    impl<T, P> Serialize for Vector<T, P>
861    where
862        T: Serialize,
863        P: SharedPointerKind,
864    {
865        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
866            serializer.collect_seq(self)
867        }
868    }
869
870    impl<'de, T, P> Deserialize<'de> for Vector<T, P>
871    where
872        T: Deserialize<'de>,
873        P: SharedPointerKind,
874    {
875        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Vector<T, P>, D::Error> {
876            deserializer
877                .deserialize_seq(VectorVisitor { _phantom_t: PhantomData, _phantom_p: PhantomData })
878        }
879    }
880
881    struct VectorVisitor<T, P> {
882        _phantom_t: PhantomData<T>,
883        _phantom_p: PhantomData<P>,
884    }
885
886    impl<'de, T, P> Visitor<'de> for VectorVisitor<T, P>
887    where
888        T: Deserialize<'de>,
889        P: SharedPointerKind,
890    {
891        type Value = Vector<T, P>;
892
893        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
894            formatter.write_str("a sequence")
895        }
896
897        fn visit_seq<A>(self, mut seq: A) -> Result<Vector<T, P>, A::Error>
898        where
899            A: SeqAccess<'de>,
900        {
901            let mut vector = Vector::new_with_ptr_kind();
902
903            while let Some(value) = seq.next_element()? {
904                vector.push_back_mut(value);
905            }
906
907            Ok(vector)
908        }
909    }
910}
911
912#[cfg(test)]
913mod test;