Skip to main content

anda_db_utils/
lib.rs

1//! Shared utility types used by the AndaDB workspace.
2//!
3//! The crate intentionally stays small and dependency-light. It currently
4//! provides:
5//!
6//! - [`UniqueVec`], an insertion-ordered vector that rejects duplicates.
7//! - [`CountingWriter`], a writer that counts serialized bytes without storing
8//!   the payload.
9//! - [`Pipe`], a small functional-style chaining trait.
10
11use core::ops::Deref;
12use rustc_hash::{FxBuildHasher, FxHashSet};
13use serde::{
14    de::{Deserialize, Deserializer},
15    ser::{Serialize, Serializer},
16};
17use std::{borrow::Borrow, hash::Hash};
18
19/// A trait for functional-style method chaining.
20///
21/// Allows any value to be passed through a function, enabling
22/// fluent interfaces and functional programming patterns.
23pub trait Pipe<T> {
24    /// Passes the value through a function.
25    ///
26    /// # Arguments
27    ///
28    /// * `f` - Function to apply to the value
29    ///
30    /// # Returns
31    ///
32    /// The result of applying the function to the value
33    fn pipe<F, R>(self, f: F) -> R
34    where
35        F: FnOnce(Self) -> R,
36        Self: Sized;
37}
38
39impl<T> Pipe<T> for T {
40    fn pipe<F, R>(self, f: F) -> R
41    where
42        F: FnOnce(Self) -> R,
43    {
44        f(self)
45    }
46}
47
48/// A helper utility to efficiently push or extend a `Vec` with unique items.
49///
50/// This struct maintains an internal `HashSet` to keep track of existing items,
51/// providing an optimized way to perform multiple non-existent insertions.
52/// It is designed to be used with a `Vec` that it helps manage.
53///
54/// # Examples
55///
56/// ```rust
57/// use anda_db_utils::UniqueVec;
58///
59/// let vec = vec![1, 2, 3];
60/// let mut extender = UniqueVec::from(vec);
61///
62/// // Push an item that already exists (no change)
63/// extender.push(2);
64/// assert_eq!(extender.as_ref(), &[1, 2, 3]);
65///
66/// // Push a new item
67/// extender.push(4);
68/// assert_eq!(extender.as_ref(), &[1, 2, 3, 4]);
69///
70/// // Extend with a list of items
71/// extender.extend(vec![3, 5, 6]);
72/// assert_eq!(extender.as_ref(), &[1, 2, 3, 4, 5, 6]);
73/// ```
74#[derive(Clone, Debug)]
75pub struct UniqueVec<T> {
76    set: FxHashSet<T>,
77    vec: Vec<T>,
78}
79
80struct UniqueVecSetRebuildGuard<'a, T>
81where
82    T: Eq + Hash + Clone,
83{
84    set: &'a mut FxHashSet<T>,
85    vec: &'a mut Vec<T>,
86}
87
88impl<T> Drop for UniqueVecSetRebuildGuard<'_, T>
89where
90    T: Eq + Hash + Clone,
91{
92    fn drop(&mut self) {
93        // Retain-style edits can only delete elements, never duplicate them, so
94        // equal lengths imply the set still mirrors the vec exactly. Rebuild only
95        // on divergence (e.g. a panicking predicate or an inconsistent Hash/Eq
96        // implementation interrupted the incremental set maintenance).
97        if self.set.len() != self.vec.len() {
98            self.set.clear();
99            self.set.extend(self.vec.iter().cloned());
100        }
101    }
102}
103
104impl<T> Default for UniqueVec<T> {
105    /// Creates an empty `UniqueVec`.
106    fn default() -> Self {
107        Self {
108            set: FxHashSet::default(),
109            vec: Vec::new(),
110        }
111    }
112}
113
114impl<T> From<Vec<T>> for UniqueVec<T>
115where
116    T: Eq + Hash + Clone,
117{
118    /// Creates a `UniqueVec` from a `Vec`.
119    ///
120    /// The extender is initialized with all the unique items from the vector.
121    fn from(mut vec: Vec<T>) -> Self {
122        let mut set = FxHashSet::with_capacity_and_hasher(vec.len(), FxBuildHasher);
123        vec.retain(|item| set.insert(item.clone()));
124        Self { set, vec }
125    }
126}
127
128impl<T> FromIterator<T> for UniqueVec<T>
129where
130    T: Eq + Hash + Clone,
131{
132    /// Creates a `UniqueVec` from an iterator.
133    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
134        let vec: Vec<T> = iter.into_iter().collect();
135        vec.into()
136    }
137}
138
139impl<T> From<UniqueVec<T>> for Vec<T> {
140    /// Converts a `UniqueVec` into a `Vec`.
141    fn from(extender: UniqueVec<T>) -> Self {
142        extender.vec
143    }
144}
145
146impl<T> AsRef<[T]> for UniqueVec<T> {
147    /// Returns a slice containing the entire vector.
148    fn as_ref(&self) -> &[T] {
149        &self.vec
150    }
151}
152
153impl<T> Deref for UniqueVec<T> {
154    type Target = Vec<T>;
155
156    /// Dereferences the `UniqueVec` to a `Vec`.
157    fn deref(&self) -> &Self::Target {
158        &self.vec
159    }
160}
161
162impl<T> UniqueVec<T>
163where
164    T: Eq + Hash + Clone,
165{
166    /// Creates a new, empty `UniqueVec`.
167    pub fn new() -> Self {
168        UniqueVec::default()
169    }
170
171    /// Creates a new, empty `UniqueVec` with a specified capacity.
172    pub fn with_capacity(capacity: usize) -> Self {
173        UniqueVec {
174            set: FxHashSet::with_capacity_and_hasher(capacity, FxBuildHasher),
175            vec: Vec::with_capacity(capacity),
176        }
177    }
178
179    /// Returns `true` if the `UniqueVec` contains the specified item.
180    pub fn contains<Q>(&self, item: &Q) -> bool
181    where
182        T: Borrow<Q>,
183        Q: Eq + Hash + ?Sized,
184    {
185        self.set.contains(item)
186    }
187
188    /// Pushes an item to the vector if it does not already exist.
189    ///
190    /// # Arguments
191    ///
192    /// * `item` - The item to add.
193    ///
194    /// # Returns
195    ///
196    /// `true` if the item was added, `false` otherwise.
197    pub fn push(&mut self, item: T) -> bool {
198        if self.set.insert(item.clone()) {
199            self.vec.push(item);
200            true
201        } else {
202            false
203        }
204    }
205
206    /// Extends the vector with items from an iterator that do not already exist.
207    ///
208    /// # Arguments
209    ///
210    /// * `items` - An iterator providing the items to add.
211    pub fn extend(&mut self, items: impl IntoIterator<Item = T>) {
212        Extend::extend(self, items);
213    }
214
215    /// Retains only the elements specified by the predicate.
216    pub fn retain<F>(&mut self, mut f: F)
217    where
218        F: FnMut(&T) -> bool,
219    {
220        let guard = UniqueVecSetRebuildGuard {
221            set: &mut self.set,
222            vec: &mut self.vec,
223        };
224        let set = &mut *guard.set;
225        guard.vec.retain(|item| {
226            if f(item) {
227                true
228            } else {
229                set.remove(item);
230                false
231            }
232        });
233    }
234
235    /// Removes and returns the element at `index`.
236    pub fn remove(&mut self, index: usize) -> T {
237        let item = self.vec.remove(index);
238        self.set.remove(&item);
239        item
240    }
241
242    /// Removes **an element** from the vector and returns it.
243    /// The first element that satisfies the predicate will be removed.
244    pub fn remove_if<P>(&mut self, mut predicate: P) -> Option<T>
245    where
246        P: FnMut(&T) -> bool,
247    {
248        if let Some(index) = self.vec.iter().position(&mut predicate) {
249            let item = self.vec.remove(index);
250            self.set.remove(&item);
251            Some(item)
252        } else {
253            None
254        }
255    }
256
257    /// Removes **an element** from the vector and returns it.
258    /// The last element is swapped into its place.
259    pub fn swap_remove_if<P>(&mut self, mut predicate: P) -> Option<T>
260    where
261        P: FnMut(&T) -> bool,
262    {
263        if let Some(index) = self.vec.iter().position(&mut predicate) {
264            let item = self.vec.swap_remove(index);
265            self.set.remove(&item);
266            Some(item)
267        } else {
268            None
269        }
270    }
271
272    /// Intersects the `UniqueVec` with another `UniqueVec`.
273    pub fn intersect_with(&mut self, other: &UniqueVec<T>) {
274        let guard = UniqueVecSetRebuildGuard {
275            set: &mut self.set,
276            vec: &mut self.vec,
277        };
278        let set = &mut *guard.set;
279        guard.vec.retain(|item| {
280            if other.set.contains(item) {
281                true
282            } else {
283                set.remove(item);
284                false
285            }
286        });
287    }
288
289    /// Returns the inner `Vec` of the `UniqueVec`.
290    pub fn into_vec(self) -> Vec<T> {
291        self.vec
292    }
293
294    /// Returns the inner `FxHashSet` of the `UniqueVec`.
295    pub fn into_set(self) -> FxHashSet<T> {
296        self.set
297    }
298
299    /// Converts the `UniqueVec` to a `Vec`.
300    pub fn to_vec(&self) -> Vec<T> {
301        self.vec.clone()
302    }
303
304    /// Converts the `UniqueVec` to a `FxHashSet`.
305    pub fn to_set(&self) -> FxHashSet<T> {
306        self.set.clone()
307    }
308}
309
310impl<T> Extend<T> for UniqueVec<T>
311where
312    T: Eq + Hash + Clone,
313{
314    /// Extends the vector with items from an iterator that do not already exist.
315    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
316        self.vec.extend(
317            iter.into_iter()
318                .filter(|item| self.set.insert(item.clone())),
319        );
320    }
321}
322
323impl<T> Serialize for UniqueVec<T>
324where
325    T: Serialize,
326{
327    /// Serializes the `UniqueVec` as a sequence.
328    #[inline]
329    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
330        serializer.collect_seq(self.vec.iter())
331    }
332}
333
334impl<'de, T> Deserialize<'de> for UniqueVec<T>
335where
336    T: Eq + Hash + Clone + Deserialize<'de>,
337{
338    /// Deserializes a sequence into a `UniqueVec`.
339    #[inline]
340    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
341        let vec: Vec<T> = Deserialize::deserialize(deserializer)?;
342        Ok(UniqueVec::from(vec))
343    }
344}
345
346/// Utility for counting the size of serialized CBOR data.
347#[derive(Clone, Debug, Eq, PartialEq)]
348pub struct CountingWriter {
349    count: usize,
350}
351
352impl Default for CountingWriter {
353    /// Creates a new `CountingWriter` with a count of 0.
354    fn default() -> Self {
355        Self::new()
356    }
357}
358
359impl CountingWriter {
360    /// Creates a new `CountingWriter`.
361    pub const fn new() -> Self {
362        CountingWriter { count: 0 }
363    }
364
365    /// Returns the current count of bytes written.
366    pub const fn size(&self) -> usize {
367        self.count
368    }
369}
370
371impl std::io::Write for CountingWriter {
372    /// Implements the write method for the Write trait.
373    /// This simply counts the bytes without actually writing them.
374    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
375        let len = buf.len();
376        self.count = self
377            .count
378            .checked_add(len)
379            .ok_or_else(|| std::io::Error::other("byte count overflow"))?;
380        Ok(len)
381    }
382
383    /// Implements the flush method for the Write trait.
384    /// This is a no-op since we're not actually writing data.
385    fn flush(&mut self) -> std::io::Result<()> {
386        Ok(())
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use std::{borrow::Cow, io::Write};
394
395    #[test]
396    fn test_pipe_trait() {
397        // Test basic pipe functionality
398        let result = 5.pipe(|x| x * 2).pipe(|x| x + 1);
399        assert_eq!(result, 11);
400
401        // Test pipe with different types
402        let string_result = "hello"
403            .pipe(|s| s.to_uppercase())
404            .pipe(|s| format!("{} world", s));
405        assert_eq!(string_result, "HELLO world");
406
407        // Test pipe with closure that changes type
408        let vec_result = vec![1, 2, 3].pipe(|v| v.len()).pipe(|len| len as f64);
409        assert_eq!(vec_result, 3.0);
410    }
411
412    #[test]
413    fn test_unique_vec_new() {
414        let uv: UniqueVec<i32> = UniqueVec::new();
415        assert_eq!(uv.len(), 0);
416        assert!(uv.is_empty());
417    }
418
419    #[test]
420    fn test_unique_vec_with_capacity() {
421        let uv: UniqueVec<i32> = UniqueVec::with_capacity(10);
422        assert_eq!(uv.len(), 0);
423        assert_eq!(uv.capacity(), 10);
424    }
425
426    #[test]
427    fn test_unique_vec_from_vec() {
428        let vec = vec![1, 2, 2, 3, 2, 1];
429        let uv = UniqueVec::from(vec);
430        assert_eq!(uv.len(), 3);
431        assert!(uv.contains(&1));
432        assert!(uv.contains(&2));
433        assert!(uv.contains(&3));
434    }
435
436    #[test]
437    fn test_unique_vec_from_iterator() {
438        let uv: UniqueVec<i32> = [2, 2, 1, 3, 2, 1].iter().cloned().collect();
439        assert_eq!(uv.len(), 3);
440        assert!(uv.contains(&2));
441        assert!(uv.contains(&1));
442        assert!(uv.contains(&3));
443    }
444
445    #[test]
446    fn test_unique_vec_push() {
447        let mut uv = UniqueVec::new();
448
449        // Push new items
450        assert!(uv.push(1));
451        assert!(uv.push(2));
452        assert!(uv.push(3));
453        assert_eq!(uv.len(), 3);
454
455        // Push duplicate items
456        assert!(!uv.push(1));
457        assert!(!uv.push(2));
458        assert_eq!(uv.len(), 3);
459
460        // Verify order is maintained
461        assert_eq!(uv.as_ref(), &[1, 2, 3]);
462    }
463
464    #[test]
465    fn test_unique_vec_extend() {
466        let mut uv = UniqueVec::from(vec![1, 2, 3]);
467
468        // Extend with mix of new and existing items
469        uv.extend(vec![3, 4, 5, 2, 6]);
470
471        assert_eq!(uv.len(), 6);
472        assert_eq!(uv.as_ref(), &[1, 2, 3, 4, 5, 6]);
473    }
474
475    #[test]
476    fn test_unique_vec_retain() {
477        let mut uv = UniqueVec::from(vec![1, 2, 3, 4, 5]);
478
479        // Retain only even numbers
480        uv.retain(|&x| x % 2 == 0);
481
482        assert_eq!(uv.len(), 2);
483        assert_eq!(uv.as_ref(), &[2, 4]);
484        assert!(uv.contains(&2));
485        assert!(uv.contains(&4));
486        assert!(!uv.contains(&1));
487        assert!(!uv.contains(&3));
488        assert!(!uv.contains(&5));
489    }
490
491    #[test]
492    fn test_unique_vec_retain_keeps_set_consistent_after_panic() {
493        let mut uv = UniqueVec::from(vec![1, 2, 3, 4, 5]);
494
495        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
496            uv.retain(|&x| {
497                if x == 3 {
498                    panic!("intentional retain panic");
499                }
500
501                x % 2 == 0
502            });
503        }));
504
505        assert!(result.is_err());
506        for value in 1..=5 {
507            assert_eq!(uv.contains(&value), uv.as_ref().contains(&value));
508        }
509    }
510
511    #[test]
512    fn test_unique_vec_retain_without_removal_keeps_set_consistent() {
513        let mut uv = UniqueVec::from(vec![1, 2, 3]);
514
515        uv.retain(|_| true);
516
517        assert_eq!(uv.as_ref(), &[1, 2, 3]);
518        // The set must still reject duplicates and accept new items.
519        assert!(!uv.push(2));
520        assert!(uv.push(4));
521        assert_eq!(uv.as_ref(), &[1, 2, 3, 4]);
522    }
523
524    #[test]
525    fn test_unique_vec_intersect_with_superset_and_disjoint() {
526        let mut uv = UniqueVec::from(vec![1, 2, 3]);
527        let superset = UniqueVec::from(vec![1, 2, 3, 4, 5]);
528
529        // Intersecting with a superset removes nothing.
530        uv.intersect_with(&superset);
531        assert_eq!(uv.as_ref(), &[1, 2, 3]);
532        assert!(!uv.push(3));
533
534        // Intersecting with a disjoint set removes everything; removed items
535        // must be insertable again afterwards.
536        let disjoint = UniqueVec::from(vec![7, 8]);
537        uv.intersect_with(&disjoint);
538        assert!(uv.is_empty());
539        assert!(!uv.contains(&1));
540        assert!(uv.push(1));
541    }
542
543    #[test]
544    fn test_unique_vec_remove() {
545        let mut uv = UniqueVec::from(vec![1, 2, 3, 4, 5]);
546
547        let removed = uv.remove(2); // Remove element at index 2 (value 3)
548        assert_eq!(removed, 3);
549        assert_eq!(uv.len(), 4);
550        assert_eq!(uv.as_ref(), &[1, 2, 4, 5]);
551        assert!(!uv.contains(&3));
552    }
553
554    #[test]
555    #[should_panic]
556    fn test_unique_vec_remove_out_of_bounds() {
557        let mut uv = UniqueVec::from(vec![1, 2, 3]);
558        uv.remove(5); // Should panic
559    }
560
561    #[test]
562    fn test_unique_vec_remove_if() {
563        let mut uv = UniqueVec::from(vec![1, 2, 3, 4, 5]);
564
565        // Remove first even number
566        let removed = uv.remove_if(|&x| x % 2 == 0);
567        assert_eq!(removed, Some(2));
568        assert_eq!(uv.len(), 4);
569        assert_eq!(uv.as_ref(), &[1, 3, 4, 5]);
570        assert!(!uv.contains(&2));
571
572        // Try to remove non-existent condition
573        let removed = uv.remove_if(|&x| x > 10);
574        assert_eq!(removed, None);
575        assert_eq!(uv.len(), 4);
576    }
577
578    #[test]
579    fn test_unique_vec_swap_remove_if() {
580        let mut uv = UniqueVec::from(vec![1, 2, 3, 4, 5]);
581
582        // Remove first even number (swap with last)
583        let removed = uv.swap_remove_if(|&x| x % 2 == 0);
584        assert_eq!(removed, Some(2));
585        assert_eq!(uv.len(), 4);
586        // After swap_remove, the last element (5) should be in position of removed element
587        assert_eq!(uv.as_ref(), &[1, 5, 3, 4]);
588        assert!(!uv.contains(&2));
589    }
590
591    #[test]
592    fn test_unique_vec_contains() {
593        let uv = UniqueVec::from(vec![1, 2, 3]);
594
595        assert!(uv.contains(&1));
596        assert!(uv.contains(&2));
597        assert!(uv.contains(&3));
598        assert!(!uv.contains(&4));
599    }
600
601    #[test]
602    fn test_unique_vec_intersect_with() {
603        let mut uv1 = UniqueVec::from(vec![1, 2, 3, 4, 5]);
604        let uv2 = UniqueVec::from(vec![3, 4, 5, 6, 7]);
605
606        uv1.intersect_with(&uv2);
607
608        assert_eq!(uv1.len(), 3);
609        assert!(uv1.contains(&3));
610        assert!(uv1.contains(&4));
611        assert!(uv1.contains(&5));
612        assert!(!uv1.contains(&1));
613        assert!(!uv1.contains(&2));
614    }
615
616    #[test]
617    fn test_unique_vec_to_vec() {
618        let uv = UniqueVec::from(vec![1, 2, 2, 3]);
619        let vec = uv.to_vec();
620        assert_eq!(vec, vec![1, 2, 3]);
621    }
622
623    #[test]
624    fn test_unique_vec_to_set() {
625        let uv = UniqueVec::from(vec![1, 2, 3]);
626        let set = uv.to_set();
627        assert_eq!(set.len(), 3);
628        assert!(set.contains(&1));
629        assert!(set.contains(&2));
630        assert!(set.contains(&3));
631    }
632
633    #[test]
634    fn test_unique_vec_as_ref() {
635        let uv = UniqueVec::from(vec![1, 2, 3]);
636        let slice: &[i32] = uv.as_ref();
637        assert_eq!(slice, &[1, 2, 3]);
638    }
639
640    #[test]
641    fn test_unique_vec_deref() {
642        let uv = UniqueVec::from(vec![1, 2, 3]);
643        // Test deref by calling Vec methods directly
644        assert_eq!(uv.len(), 3);
645        assert_eq!(uv[0], 1);
646        assert_eq!(uv[1], 2);
647        assert_eq!(uv[2], 3);
648    }
649
650    #[test]
651    fn test_unique_vec_into_vec() {
652        let uv = UniqueVec::from(vec![1, 2, 3]);
653        let vec: Vec<i32> = uv.into();
654        assert_eq!(vec, vec![1, 2, 3]);
655    }
656
657    #[test]
658    fn test_unique_vec_serialize_deserialize() {
659        let uv = UniqueVec::from(vec![1, 2, 2, 3, 2, 1]); // Duplicates should be removed
660
661        // Serialize
662        let json = serde_json::to_string(&uv).unwrap();
663        assert_eq!(json, "[1,2,3]");
664
665        // Deserialize
666        let deserialized: UniqueVec<i32> = serde_json::from_str("[1,3,2,3,3,2,1]").unwrap();
667        assert_eq!(deserialized.len(), 3);
668        assert_eq!(deserialized.as_ref(), &[1, 3, 2]);
669    }
670
671    #[test]
672    fn test_unique_vec_deserialize_borrowed_values() {
673        fn deserialize_unique_vec_cow<'a>(json: &'a str) -> UniqueVec<Cow<'a, str>> {
674            serde_json::from_str(json).unwrap()
675        }
676
677        let json = String::from(r#"["alpha","beta","alpha"]"#);
678        let deserialized = deserialize_unique_vec_cow(&json);
679
680        assert_eq!(
681            deserialized.as_ref(),
682            &[Cow::Borrowed("alpha"), Cow::Borrowed("beta")]
683        );
684    }
685
686    #[test]
687    fn test_unique_vec_clone() {
688        let uv1 = UniqueVec::from(vec![1, 2, 3]);
689        let uv2 = uv1.clone();
690
691        assert_eq!(uv1.len(), uv2.len());
692        assert_eq!(uv1.as_ref(), uv2.as_ref());
693    }
694
695    #[test]
696    fn test_counting_writer_new() {
697        let writer = CountingWriter::new();
698        assert_eq!(writer.size(), 0);
699    }
700
701    #[test]
702    fn test_counting_writer_default() {
703        let writer = CountingWriter::default();
704        assert_eq!(writer.size(), 0);
705    }
706
707    #[test]
708    fn test_counting_writer_write() {
709        let mut writer = CountingWriter::new();
710
711        let result = writer.write(b"hello");
712        assert!(result.is_ok());
713        assert_eq!(result.unwrap(), 5);
714        assert_eq!(writer.size(), 5);
715
716        let result = writer.write(b" world");
717        assert!(result.is_ok());
718        assert_eq!(result.unwrap(), 6);
719        assert_eq!(writer.size(), 11);
720    }
721
722    #[test]
723    fn test_counting_writer_flush() {
724        let mut writer = CountingWriter::new();
725        let result = writer.flush();
726        assert!(result.is_ok());
727        assert_eq!(writer.size(), 0); // Flush doesn't change size
728    }
729
730    #[test]
731    fn test_counting_writer_multiple_writes() {
732        let mut writer = CountingWriter::new();
733
734        // Multiple writes should accumulate
735        writer.write_all(b"a").unwrap();
736        assert_eq!(writer.size(), 1);
737
738        writer.write_all(b"bc").unwrap();
739        assert_eq!(writer.size(), 3);
740
741        writer.write_all(b"defg").unwrap();
742        assert_eq!(writer.size(), 7);
743    }
744
745    #[test]
746    fn test_counting_writer_empty_write() {
747        let mut writer = CountingWriter::new();
748
749        let result = writer.write(b"");
750        assert!(result.is_ok());
751        assert_eq!(result.unwrap(), 0);
752        assert_eq!(writer.size(), 0);
753    }
754
755    #[test]
756    fn test_unique_vec_edge_cases() {
757        // Test with empty vector
758        let uv = UniqueVec::from(vec![] as Vec<i32>);
759        assert_eq!(uv.len(), 0);
760        assert!(uv.is_empty());
761
762        // Test with single element
763        let mut uv = UniqueVec::from(vec![42]);
764        assert_eq!(uv.len(), 1);
765        assert!(uv.contains(&42));
766
767        // Test removing the only element
768        let removed = uv.remove(0);
769        assert_eq!(removed, 42);
770        assert_eq!(uv.len(), 0);
771        assert!(!uv.contains(&42));
772    }
773
774    #[test]
775    fn test_unique_vec_string_type() {
776        let mut uv = UniqueVec::new();
777
778        uv.push("hello".to_string());
779        uv.push("world".to_string());
780        uv.push("hello".to_string()); // Duplicate
781
782        assert_eq!(uv.len(), 2);
783        assert!(uv.contains("hello"));
784        assert!(uv.contains("world"));
785    }
786
787    #[test]
788    fn test_counting_writer_overflow() {
789        let mut writer = CountingWriter { count: usize::MAX };
790        let err = writer.write(b"x").unwrap_err();
791
792        assert_eq!(err.kind(), std::io::ErrorKind::Other);
793        assert_eq!(writer.size(), usize::MAX);
794    }
795}