signvec/
signvec.rs

1use crate::{Sign, Signable};
2use fastset::Set;
3use nanorand::WyRand;
4use serde::{Deserialize, Serialize};
5use std::borrow::Borrow;
6use std::cmp::Ordering;
7use std::hash::{Hash, Hasher};
8use std::marker::PhantomData;
9use std::mem::MaybeUninit;
10use std::ops::{Bound, Deref, Index, RangeBounds};
11
12const DEFAULT_SET_SIZE: usize = 1000;
13
14/// A vector-like data structure with additional information about the sign of its elements.
15///
16/// This data structure holds a vector of elements of type `T`, along with sets `pos` and `neg`
17/// containing the indices of positive and negative elements respectively. The `SignVec` is used
18/// to efficiently store and manipulate elements based on their sign.
19///
20/// Compared to standard vectors, `SignVec` provides additional functionality for handling
21/// elements based on their sign and maintaining sets of positive and negative indices.
22///
23/// # Type Parameters
24///
25/// * `T`: The type of elements stored in the `SignVec`, which must implement the `Signable` trait
26///        and also be cloneable.
27///
28/// # Fields
29///
30/// * `vals`: A vector holding elements of type `T`.
31/// * `pos`: A set containing the indices of positive elements in `vals`.
32/// * `neg`: A set containing the indices of negative elements in `vals`.
33/// * `_marker`: Phantom data field to maintain covariance with the type parameter `T`.
34///
35#[derive(Debug, Serialize, Deserialize, Clone)]
36pub struct SignVec<T>
37where
38    T: Signable + Clone,
39{
40    pub vals: Vec<T>,
41    pub pos: Set,
42    pub neg: Set,
43    _marker: PhantomData<T>,
44}
45
46impl<T> SignVec<T>
47where
48    T: Signable + Clone,
49{
50    /// Appends elements from another vector to the end of this `SignVec`.
51    ///
52    /// This method appends each element from the provided vector `other` to the end of the `vals`
53    /// vector of this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the
54    /// sign of each appended element.
55    ///
56    /// # Arguments
57    ///
58    /// * `other`: A mutable reference to a vector of elements to be appended.
59    ///
60    /// # Examples
61    ///
62    /// ```
63    /// use signvec::{SignVec, svec, Sign};
64    ///
65    /// let mut sv = svec![5, -10, 15];
66    /// let mut other_vec = vec![25, -30];
67    /// let mut other_sv = svec![20, -35];
68    ///
69    /// sv.append(&mut other_vec);
70    /// sv.append(&mut other_sv);
71    ///
72    /// assert_eq!(sv.len(), 7);
73    /// assert_eq!(sv.count(Sign::Plus), 4);
74    /// assert_eq!(sv.count(Sign::Minus), 3);
75    /// ```
76    #[inline(always)]
77    pub fn append(&mut self, other: &[T])
78    where
79        T: Signable + Clone,
80    {
81        let start_len = self.vals.len();
82        other.iter().enumerate().for_each(|(index, e)| {
83            let vals_index = start_len + index;
84            match e.sign() {
85                Sign::Plus => self.pos.insert(vals_index),
86                Sign::Minus => self.neg.insert(vals_index),
87            };
88            self.vals.push(e.clone());
89        });
90    }
91    /// Returns a raw pointer to the underlying data of this `SignVec`.
92    ///
93    /// This method returns a raw pointer to the first element in the `vals` vector of this `SignVec`.
94    ///
95    /// # Safety
96    ///
97    /// The returned pointer is valid for as long as this `SignVec` is not modified or deallocated.
98    /// Modifying the `SignVec` or deallocating it invalidates the pointer. It's unsafe to dereference the pointer directly.
99    /// However, it can be safely passed to other functions that expect a raw pointer.
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// use signvec::{SignVec, svec};
105    ///
106    /// let sv = svec![5, -10, 15];
107    /// let ptr = sv.as_ptr();
108    ///
109    /// ```
110    #[inline(always)]
111    pub fn as_ptr(&self) -> *const T {
112        self.vals.as_ptr()
113    }
114    /// Returns a slice containing all elements in this `SignVec`.
115    ///
116    /// This method returns a slice containing all elements in the `vals` vector of this `SignVec`.
117    ///
118    /// # Examples
119    ///
120    /// ```
121    /// use signvec::{SignVec, svec};
122    ///
123    /// let sv = svec![5, -10, 15];
124    /// let slice = sv.as_slice();
125    ///
126    /// assert_eq!(slice, &[5, -10, 15]);
127    /// ```
128    #[inline(always)]
129    pub fn as_slice(&self) -> &[T] {
130        self.vals.as_slice()
131    }
132
133    /// Returns the capacity of the `vals` vector of this `SignVec`.
134    ///
135    /// This method returns the capacity of the `vals` vector, which is the maximum number of elements
136    /// that the vector can hold without reallocating.
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// use signvec::{SignVec, svec};
142    ///
143    /// let sv = svec![5, -10, 15];
144    /// assert_eq!(sv.capacity(), 4);
145    /// ```
146    #[inline(always)]
147    pub fn capacity(&self) -> usize {
148        self.vals.capacity()
149    }
150
151    /// Clears all elements from this `SignVec`.
152    ///
153    /// This method removes all elements from the `vals` vector of this `SignVec`, and clears the
154    /// `pos` and `neg` sets. The capacity of none of the fields are affected.
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// use signvec::{SignVec, svec};
160    ///
161    /// let mut sv = svec![5, -10, 15];
162    /// sv.clear();
163    ///
164    /// assert!(sv.is_empty());
165    /// ```
166    #[inline(always)]
167    pub fn clear(&mut self) {
168        self.vals.clear();
169        self.pos.clear();
170        self.neg.clear();
171    }
172
173    /// Returns the number of elements with the specified sign in this `SignVec`.
174    ///
175    /// This method returns the number of elements in the `pos` set if `sign` is `Sign::Plus`, or
176    /// the number of elements in the `neg` set if `sign` is `Sign::Minus`.
177    ///
178    /// # Arguments
179    ///
180    /// * `sign`: The sign of the elements to count.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use signvec::{SignVec, Sign, svec};
186    ///
187    /// let sv = svec![5, -10, 15];
188    ///
189    /// assert_eq!(sv.count(Sign::Plus), 2);
190    /// assert_eq!(sv.count(Sign::Minus), 1);
191    /// ```
192    #[inline(always)]
193    pub fn count(&self, sign: Sign) -> usize {
194        match sign {
195            Sign::Plus => self.pos.len(),
196            Sign::Minus => self.neg.len(),
197        }
198    }
199
200    /// Returns the number of elements with a positive sign in this `SignVec`.
201    ///
202    /// This method directly returns the number of elements in the `pos` set,
203    /// providing a more straightforward and slightly faster alternative to calling `count(Sign::Plus)`.
204    ///
205    /// # Examples
206    ///
207    /// ```
208    /// use signvec::{SignVec, svec};
209    ///
210    /// let sv = svec![5, -10, 15];
211    ///
212    /// assert_eq!(sv.count_pos(), 2);
213    /// ```
214    #[inline(always)]
215    pub fn count_pos(&self) -> usize {
216        self.pos.len()
217    }
218
219    /// Returns the number of elements with a negative sign in this `SignVec`.
220    ///
221    /// This method directly returns the number of elements in the `neg` set,
222    /// providing a more straightforward and slightly faster alternative to calling `count(Sign::Minus)`.
223    ///
224    /// # Examples
225    ///
226    /// ```
227    /// use signvec::{SignVec, svec};
228    ///
229    /// let sv = svec![5, -10, 15];
230    ///
231    /// assert_eq!(sv.count_neg(), 1);
232    /// ```
233    #[inline(always)]
234    pub fn count_neg(&self) -> usize {
235        self.neg.len()
236    }
237
238    /// Removes consecutive duplicate elements from this `SignVec`.
239    ///
240    /// This method removes consecutive duplicate elements from the `vals` vector of this `SignVec`.
241    /// Elements are considered duplicates if they are equal according to the `PartialEq` trait.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use signvec::{SignVec, svec};
247    ///
248    /// let mut sv = svec![5, 5, -10, 15, 15];
249    /// sv.dedup();
250    ///
251    /// assert_eq!(sv, svec![5, -10, 15]);
252    /// ```
253    #[inline(always)]
254    pub fn dedup(&mut self)
255    where
256        T: PartialEq + Signable,
257    {
258        if self.vals.is_empty() {
259            return;
260        }
261
262        let mut write = 1; // Index to write to.
263        for read in 1..self.vals.len() {
264            if self.vals[read] != self.vals[read - 1] {
265                // Move non-duplicate to the 'write' position if necessary.
266                if read != write {
267                    self.vals[write] = self.vals[read].clone();
268
269                    if self.vals[read].sign() == Sign::Plus {
270                        self.pos.remove(&read);
271                        self.pos.insert(write);
272                    } else {
273                        self.neg.remove(&read);
274                        self.neg.insert(write);
275                    }
276                }
277                write += 1;
278            } else {
279                // For duplicates, just remove them from pos and neg sets.
280                self.pos.remove(&read);
281                self.neg.remove(&read);
282            }
283        }
284        // Truncate the vector to remove excess elements.
285        self.vals.truncate(write);
286    }
287
288    /// Removes elements from this `SignVec` based on a predicate.
289    ///
290    /// This method removes elements from the `vals` vector of this `SignVec` based on the provided
291    /// predicate `same_bucket`. Elements `x` and `y` are considered duplicates if `same_bucket(&x, &y)`
292    /// returns `true`.
293    ///
294    /// # Arguments
295    ///
296    /// * `same_bucket`: A predicate used to determine whether two elements are duplicates.
297    ///
298    /// # Examples
299    ///
300    /// ```
301    /// use signvec::{SignVec, svec};
302    ///
303    /// let mut sign_vec = svec![5, 5, -10, 15, 15];
304    /// sign_vec.dedup_by(|x, y| x == y);
305    ///
306    /// assert_eq!(sign_vec, svec![5, -10, 15]);
307    /// ```
308    #[inline(always)]
309    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
310    where
311        F: FnMut(&T, &T) -> bool,
312    {
313        unsafe {
314            let mut len = self.vals.len();
315            let mut i = 0;
316            let vals_ptr = self.vals.as_mut_ptr();
317            while i < len {
318                let curr = vals_ptr.add(i);
319                let mut j = i + 1;
320                while j < len {
321                    let next = vals_ptr.add(j);
322                    if same_bucket(&*curr, &*next) {
323                        self.vals.remove(j);
324                        self.pos.remove(&j);
325                        self.neg.remove(&j);
326                        len -= 1;
327                    } else {
328                        j += 1;
329                    }
330                }
331                i += 1;
332            }
333        }
334    }
335    /// Removes elements from this `SignVec` based on a key function.
336    ///
337    /// This method removes elements from the `vals` vector of this `SignVec` based on the key
338    /// returned by the provided key function `key`. If the key of two consecutive elements is equal,
339    /// the second element is removed.
340    ///
341    /// # Arguments
342    ///
343    /// * `key`: A function used to determine the key for each element.
344    ///
345    /// # Examples
346    ///
347    /// ```
348    /// use signvec::{SignVec, svec};
349    ///
350    /// let mut sign_vec: SignVec<i32> = svec![5, 6, 10, -10];
351    /// sign_vec.dedup_by_key(|x| x.abs());
352    ///
353    /// assert_eq!(sign_vec, svec![5, 6, 10]);
354    /// ```
355    #[inline(always)]
356    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
357    where
358        F: FnMut(&T) -> K,
359        K: PartialEq,
360    {
361        unsafe {
362            let mut i = 1;
363            let vals_ptr = self.vals.as_mut_ptr();
364            while i < self.vals.len() {
365                // Use while loop to manually control the iteration process, allowing us to adjust 'i' as needed.
366                let prev = vals_ptr.add(i - 1);
367                let now = vals_ptr.add(i);
368                if i > 0 && key(&*prev) == key(&*now) {
369                    self.vals.remove(i); // Remove the current item if its key matches the previous item's key.
370                                         // Do not increment 'i' so that the next element,
371                                         // which shifts into the current index, is compared next.
372                    self.pos.remove(&(i));
373                    self.neg.remove(&(i));
374                } else {
375                    i += 1; // Only increment 'i' if no removal was made.
376                }
377            }
378        }
379    }
380
381    /// Drains elements from this `SignVec` based on a range.
382    ///
383    /// This method removes elements from the `vals` vector of this `SignVec` based on the provided
384    /// range `range`. It returns a `SignVecDrain` iterator over the removed elements.
385    ///
386    /// # Arguments
387    ///
388    /// * `range`: The range of indices to drain elements from.
389    ///
390    /// # Panics
391    ///
392    /// Panics if the range is out of bounds.
393    ///
394    /// # Examples
395    ///
396    /// ```
397    /// use signvec::{SignVec, svec};
398    /// use std::ops::Bound;
399    ///
400    /// let mut sign_vec = svec![5, -10, 15, 20];
401    /// let drained: Vec<_> = sign_vec.drain(1..3).collect();
402    ///
403    /// assert_eq!(drained, vec![-10, 15]);
404    /// assert_eq!(sign_vec, svec![5, 20]);
405    /// ```
406    #[inline(always)]
407    pub fn drain<R>(&mut self, range: R) -> SignVecDrain<'_, T>
408    where
409        R: RangeBounds<usize>,
410    {
411        let start = match range.start_bound() {
412            Bound::Included(&s) => s,
413            Bound::Excluded(&s) => s + 1,
414            Bound::Unbounded => 0,
415        };
416        let end = match range.end_bound() {
417            Bound::Included(&e) => e + 1,
418            Bound::Excluded(&e) => e,
419            Bound::Unbounded => self.vals.len(),
420        };
421
422        // Initial validation.
423        if start > end || end > self.vals.len() {
424            panic!("Drain range out of bounds");
425        }
426
427        SignVecDrain {
428            sign_vec: self,
429            current_index: start,
430            drain_end: end,
431        }
432    }
433
434    /// Extends this `SignVec` with elements from a slice.
435    ///
436    /// This method appends each element from the provided slice `other` to the end of the `vals`
437    /// vector of this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the
438    /// sign of each appended element.
439    ///
440    /// # Arguments
441    ///
442    /// * `other`: A slice of elements to be appended.
443    ///
444    /// # Examples
445    ///
446    /// ```
447    /// use signvec::{SignVec, svec};
448    ///
449    /// let mut sign_vec = svec![5, -10];
450    /// sign_vec.extend_from_slice(&[15, -20]);
451    ///
452    /// assert_eq!(sign_vec, svec![5, -10, 15, -20]);
453    /// ```
454    #[inline(always)]
455    pub fn extend_from_slice(&mut self, other: &[T]) {
456        let offset = self.vals.len();
457        self.vals.extend_from_slice(other);
458        for (i, e) in other.iter().enumerate() {
459            match e.sign() {
460                Sign::Plus => self.pos.insert(offset + i),
461                Sign::Minus => self.neg.insert(offset + i),
462            };
463        }
464    }
465
466    /// Extends this `SignVec` with elements from within a range.
467    ///
468    /// This method appends elements from the range `src` within the `vals` vector of this `SignVec`
469    /// to the end of the `vals` vector. It updates the `pos` and `neg` sets accordingly based on the
470    /// sign of each appended element.
471    ///
472    /// # Arguments
473    ///
474    /// * `src`: The range of indices to extend elements from.
475    ///
476    /// # Panics
477    ///
478    /// Panics if the range is out of bounds.
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// use signvec::{SignVec, svec};
484    /// use std::ops::Bound;
485    ///
486    /// let mut sign_vec = svec![5, -10, 15, 20];
487    /// sign_vec.extend_from_within(..=2);
488    ///
489    /// assert_eq!(sign_vec, svec![5, -10, 15, 20, 5, -10, 15]);
490    /// ```
491    #[inline(always)]
492    pub fn extend_from_within<R>(&mut self, src: R)
493    where
494        R: RangeBounds<usize>,
495    {
496        let start = match src.start_bound() {
497            Bound::Included(&s) => s,
498            Bound::Excluded(&s) => s + 1,
499            Bound::Unbounded => 0,
500        };
501        let end = match src.end_bound() {
502            Bound::Included(&e) => e + 1,
503            Bound::Excluded(&e) => e,
504            Bound::Unbounded => self.vals.len(),
505        };
506        if start > end || end > self.vals.len() {
507            panic!("Invalid range for extend_from_within");
508        }
509
510        let offset = self.vals.len();
511        self.vals.extend_from_within(start..end);
512        for i in start..end {
513            match self.vals[i].sign() {
514                Sign::Plus => self.pos.insert(offset + i - start),
515                Sign::Minus => self.neg.insert(offset + i - start),
516            };
517        }
518    }
519    /// Inserts an element at a specified index into this `SignVec`.
520    ///
521    /// This method inserts the specified `element` at the given `index` into the `vals` vector of
522    /// this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the sign of the
523    /// inserted element.
524    ///
525    /// # Arguments
526    ///
527    /// * `index`: The index at which to insert the element.
528    /// * `element`: The element to insert.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// use signvec::{SignVec, svec};
534    ///
535    /// let mut sign_vec = svec![5, -10];
536    /// sign_vec.insert(1, 15);
537    ///
538    /// assert_eq!(sign_vec, svec![5, 15, -10]);
539    /// ```
540    #[inline(always)]
541    pub fn insert(&mut self, index: usize, element: T) {
542        self.pos = self
543            .pos
544            .iter()
545            .map(|&idx| if idx >= index { idx + 1 } else { idx })
546            .collect();
547        self.neg = self
548            .neg
549            .iter()
550            .map(|&idx| if idx >= index { idx + 1 } else { idx })
551            .collect();
552        match element.sign() {
553            Sign::Plus => {
554                self.pos.insert(index);
555            }
556            Sign::Minus => {
557                self.neg.insert(index);
558            }
559        };
560        self.vals.insert(index, element);
561    }
562
563    /// Returns a reference to the set of indices with the specified sign.
564    ///
565    /// This method returns a reference to the `Set` containing the indices of elements with the
566    /// specified `sign` in this `SignVec`.
567    ///
568    /// # Arguments
569    ///
570    /// * `sign`: The sign of the elements whose indices are requested.
571    ///
572    /// # Examples
573    ///
574    /// ```
575    /// use signvec::{SignVec, svec, Sign};
576    /// use fastset::Set;
577    ///
578    /// let sign_vec = svec![5, -10, 15, -20];
579    ///
580    /// assert_eq!(sign_vec.indices(Sign::Plus), &Set::from(&[0, 2]));
581    /// assert_eq!(sign_vec.indices(Sign::Minus), &Set::from(&[1, 3]));
582    /// ```
583    #[inline(always)]
584    pub fn indices(&self, sign: Sign) -> &Set {
585        match sign {
586            Sign::Plus => &self.pos,
587            Sign::Minus => &self.neg,
588        }
589    }
590
591    /// Returns a reference to the set of indices with positive signs.
592    ///
593    /// This method provides direct access to the `Set` containing the indices of elements
594    /// with a positive sign in this `SignVec`, bypassing the need to specify the sign.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use signvec::{SignVec, svec};
600    /// use fastset::Set;
601    ///
602    /// let sign_vec = svec![5, -10, 15, -20];
603    ///
604    /// assert_eq!(sign_vec.indices_pos(), &Set::from(&[0, 2]));
605    /// ```
606    #[inline(always)]
607    pub fn indices_pos(&self) -> &Set {
608        &self.pos
609    }
610
611    /// Returns a reference to the set of indices with negative signs.
612    ///
613    /// This method provides direct access to the `Set` containing the indices of elements
614    /// with a negative sign in this `SignVec`, bypassing the need to specify the sign.
615    ///
616    /// # Examples
617    ///
618    /// ```
619    /// use signvec::{SignVec, svec};
620    /// use fastset::Set;
621    ///
622    /// let sign_vec = svec![5, -10, 15, -20];
623    ///
624    /// assert_eq!(sign_vec.indices_neg(), &Set::from(&[1, 3]));
625    /// ```
626    #[inline(always)]
627    pub fn indices_neg(&self) -> &Set {
628        &self.neg
629    }
630
631    /// Consumes this `SignVec`, returning a boxed slice of its elements.
632    ///
633    /// This method consumes the `SignVec`, transforming it into a boxed slice of its elements.
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// use signvec::{SignVec, svec};
639    ///
640    /// let sign_vec = svec![5, -10];
641    /// let boxed_slice = sign_vec.into_boxed_slice();
642    ///
643    /// assert_eq!(&*boxed_slice, &[5, -10]);
644    /// ```
645    #[inline(always)]
646    pub fn into_boxed_slice(self) -> Box<[T]> {
647        self.vals.into_boxed_slice()
648    }
649
650    /// Returns `true` if this `SignVec` is empty.
651    ///
652    /// This method returns `true` if the `vals` vector of this `SignVec` is empty, otherwise `false`.
653    ///
654    /// # Examples
655    ///
656    /// ```
657    /// use signvec::{SignVec, svec};
658    ///
659    /// let sign_vec: SignVec<i32> = svec![];
660    ///
661    /// assert!(sign_vec.is_empty());
662    /// ```
663    #[inline(always)]
664    pub fn is_empty(&self) -> bool {
665        self.vals.is_empty()
666    }
667
668    /// Converts this `SignVec` into a mutable slice without deallocating memory.
669    ///
670    /// This method consumes the `SignVec` and returns a mutable reference to its elements without
671    /// deallocating memory. It is the caller's responsibility to ensure that the memory is properly
672    /// deallocated once the reference is no longer needed.
673    ///
674    /// # Examples
675    ///
676    /// ```
677    /// use signvec::{SignVec, svec};
678    ///
679    /// let mut sign_vec = svec![5, -10];
680    /// let slice = sign_vec.leak();
681    ///
682    /// assert_eq!(slice, &mut [5, -10]);
683    /// ```
684    #[inline(always)]
685    pub fn leak<'a>(self) -> &'a mut [T] {
686        let pointer = self.vals.as_ptr();
687        let len = self.vals.len();
688        std::mem::forget(self);
689        unsafe { std::slice::from_raw_parts_mut(pointer as *mut T, len) }
690    }
691
692    /// Returns the number of elements in this `SignVec`.
693    ///
694    /// This method returns the number of elements stored in the `vals` vector of this `SignVec`.
695    ///
696    /// # Examples
697    ///
698    /// ```
699    /// use signvec::{SignVec, svec};
700    ///
701    /// let sign_vec = svec![5, -10, 15];
702    ///
703    /// assert_eq!(sign_vec.len(), 3);
704    /// ```
705    #[inline(always)]
706    pub fn len(&self) -> usize {
707        self.vals.len()
708    }
709    /// Creates a new `SignVec` from a slice of elements.
710    ///
711    /// This method constructs a new `SignVec` by iterating over the elements in the input slice `input`.
712    /// It initializes the `vals` vector with the elements from the slice and populates the `pos` and
713    /// `neg` sets based on the sign of each element. The maximum index value is used to initialize the sets.
714    ///
715    /// # Arguments
716    ///
717    /// * `input`: A slice containing elements to be stored in the `SignVec`.
718    ///
719    /// # Examples
720    ///
721    /// ```
722    /// use signvec::{SignVec, svec, Sign};
723    ///
724    /// let mut sign_vec = SignVec::new();
725    /// assert_eq!(sign_vec.len(), 0);
726    /// assert_eq!(sign_vec.count(Sign::Plus), 0);
727    /// assert_eq!(sign_vec.count(Sign::Minus), 0);
728    ///
729    /// let input_slice = &[5, -10, 15];
730    /// sign_vec.extend(input_slice);
731    ///
732    /// assert_eq!(sign_vec.len(), 3);
733    /// assert_eq!(sign_vec.count(Sign::Plus), 2);
734    /// assert_eq!(sign_vec.count(Sign::Minus), 1);
735    /// ```
736    #[inline(always)]
737    pub fn new() -> Self {
738        Self::default()
739    }
740    /// Removes and returns the last element from this `SignVec`, or `None` if it is empty.
741    ///
742    /// This method removes and returns the last element from the `vals` vector of this `SignVec`, if
743    /// it exists. It updates the `pos` and `neg` sets accordingly based on the sign of the removed
744    /// element.
745    ///
746    /// # Returns
747    ///
748    /// * `Some(T)`: The last element from the `vals` vector, if it exists.
749    /// * `None`: If the `vals` vector is empty.
750    ///
751    /// # Examples
752    ///
753    /// ```
754    /// use signvec::{SignVec, svec};
755    ///
756    /// let mut sign_vec = svec![5, -10];
757    ///
758    /// assert_eq!(sign_vec.pop(), Some(-10));
759    /// assert_eq!(sign_vec.pop(), Some(5));
760    /// assert_eq!(sign_vec.pop(), None);
761    /// ```
762    #[inline(always)]
763    pub fn pop(&mut self) -> Option<T> {
764        if let Some(topop) = self.vals.pop() {
765            let idx = self.vals.len(); // Get the new length after popping.
766            match topop.sign() {
767                Sign::Plus => {
768                    self.pos.remove(&idx);
769                }
770                Sign::Minus => {
771                    self.neg.remove(&idx);
772                }
773            };
774            Some(topop)
775        } else {
776            None
777        }
778    }
779
780    /// Appends an element to the end of this `SignVec`.
781    ///
782    /// This method appends the specified `element` to the end of the `vals` vector of this `SignVec`.
783    /// It updates the `pos` and `neg` sets accordingly based on the sign of the appended element.
784    ///
785    /// # Arguments
786    ///
787    /// * `element`: The element to append.
788    ///
789    /// # Examples
790    ///
791    /// ```
792    /// use signvec::{SignVec, svec};
793    ///
794    /// let mut sign_vec = svec![5, -10];
795    /// sign_vec.push(15);
796    ///
797    /// assert_eq!(sign_vec, svec![5, -10, 15]);
798    /// ```
799    #[inline(always)]
800    pub fn push(&mut self, element: T) {
801        let index = self.vals.len();
802        match element.sign() {
803            Sign::Plus => self.pos.insert(index),
804            Sign::Minus => self.neg.insert(index),
805        };
806        self.vals.push(element);
807    }
808
809    /// Removes and returns the element at the specified index from this `SignVec`.
810    ///
811    /// This method removes and returns the element at the specified `index` from the `vals` vector of
812    /// this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the sign of the
813    /// removed element.
814    ///
815    /// # Arguments
816    ///
817    /// * `index`: The index of the element to remove.
818    ///
819    /// # Returns
820    ///
821    /// * `T`: The element removed from the `vals` vector.
822    ///
823    /// # Panics
824    ///
825    /// Panics if `index` is out of bounds.
826    ///
827    /// # Examples
828    ///
829    /// ```
830    /// use signvec::{SignVec, svec};
831    ///
832    /// let mut sign_vec = svec![5, -10, 15];
833    /// let removed = sign_vec.remove(1);
834    ///
835    /// assert_eq!(removed, -10);
836    /// assert_eq!(sign_vec, svec![5, 15]);
837    /// ```
838    #[inline(always)]
839    pub fn remove(&mut self, index: usize) -> T {
840        self.pos = self
841            .pos
842            .iter()
843            .map(|&idx| if idx > index { idx - 1 } else { idx })
844            .collect();
845        self.neg = self
846            .neg
847            .iter()
848            .map(|&idx| if idx > index { idx - 1 } else { idx })
849            .collect();
850        let removed = self.vals.remove(index);
851        match removed.sign() {
852            Sign::Plus => self.pos.remove(&index),
853            Sign::Minus => self.neg.remove(&index),
854        };
855        removed
856    }
857    /// Reserves capacity for at least `additional` more elements in `vals`.
858    ///
859    /// This method reserves capacity for at least `additional` more elements in the `vals` vector of
860    /// this `SignVec`. It also reserves capacity in the `pos` and `neg` sets accordingly based on the
861    /// new capacity of the `vals` vector.
862    ///
863    /// # Arguments
864    ///
865    /// * `additional`: The number of additional elements to reserve capacity for.
866    ///
867    /// # Examples
868    ///
869    /// ```
870    /// use signvec::{SignVec, svec};
871    ///
872    /// let mut sign_vec = svec![5, -10];
873    /// sign_vec.reserve(3);
874    ///
875    /// assert!(sign_vec.capacity() >= 5);
876    /// ```
877    #[inline(always)]
878    pub fn reserve(&mut self, additional: usize) {
879        let new_capacity = self.vals.len() + additional;
880        self.vals.reserve(additional);
881        self.pos.reserve(new_capacity);
882        self.neg.reserve(new_capacity);
883    }
884
885    /// Reserves the exact capacity for `additional` more elements in `vals`.
886    ///
887    /// This method reserves the exact capacity for `additional` more elements in the `vals` vector of
888    /// this `SignVec`. It also reserves capacity in the `pos` and `neg` sets accordingly based on the
889    /// new capacity of the `vals` vector.
890    ///
891    /// # Arguments
892    ///
893    /// * `additional`: The exact number of additional elements to reserve capacity for.
894    ///
895    /// # Examples
896    ///
897    /// ```
898    /// use signvec::{SignVec, svec};
899    ///
900    /// let mut sign_vec = svec![5, -10];
901    /// sign_vec.reserve_exact(3);
902    ///
903    /// assert_eq!(sign_vec.capacity(), 5);
904    /// ```
905    #[inline(always)]
906    pub fn reserve_exact(&mut self, additional: usize) {
907        let new_capacity = self.vals.len() + additional;
908        self.vals.reserve_exact(additional);
909        self.pos.reserve(new_capacity);
910        self.neg.reserve(new_capacity);
911    }
912
913    /// Resizes the `SignVec` in place to a new length.
914    ///
915    /// This method changes the `len` field of the `vals` vector of this `SignVec`, and adjusts the
916    /// elements, `pos`, and `neg` sets accordingly based on the new length and the specified `value`.
917    ///
918    /// # Arguments
919    ///
920    /// * `new_len`: The new length of the `SignVec`.
921    /// * `value`: The value to initialize new elements with, if `new_len` is greater than the current
922    ///            length.
923    ///
924    /// # Examples
925    ///
926    /// ```
927    /// use signvec::{SignVec, svec};
928    ///
929    /// let mut sign_vec = svec![5, -10];
930    /// sign_vec.resize(5, 0);
931    ///
932    /// assert_eq!(sign_vec, svec![5, -10, 0, 0, 0]);
933    /// ```
934    #[inline(always)]
935    pub fn resize(&mut self, new_len: usize, value: T) {
936        let old_len = self.vals.len();
937        match new_len > old_len {
938            true => {
939                self.vals.resize(new_len, value.clone());
940                match value.sign() {
941                    Sign::Plus => (old_len..new_len).for_each(|i| {
942                        self.pos.insert(i);
943                    }),
944                    Sign::Minus => (old_len..new_len).for_each(|i| {
945                        self.neg.insert(i);
946                    }),
947                };
948            }
949            false => {
950                (new_len..old_len).for_each(|i| {
951                    self.pos.remove(&i);
952                    self.neg.remove(&i);
953                });
954                self.vals.truncate(new_len);
955            }
956        }
957    }
958
959    /// Resizes the `SignVec` in place to a new length, using a closure to create new values.
960    ///
961    /// This method changes the `len` field of the `vals` vector of this `SignVec`, and adjusts the
962    /// elements, `pos`, and `neg` sets accordingly based on the new length and values generated by the
963    /// closure `f`.
964    ///
965    /// # Arguments
966    ///
967    /// * `new_len`: The new length of the `SignVec`.
968    /// * `f`: A closure that creates new values for elements beyond the current length.
969    ///
970    /// # Examples
971    ///
972    /// ```
973    /// use signvec::{SignVec, svec};
974    ///
975    /// let mut sign_vec = svec![5, -10];
976    /// sign_vec.resize_with(5, || 0);
977    ///
978    /// assert_eq!(sign_vec, svec![5, -10, 0, 0, 0]);
979    /// ```
980    #[inline(always)]
981    pub fn resize_with<F>(&mut self, new_len: usize, mut f: F)
982    where
983        F: FnMut() -> T,
984    {
985        let old_len = self.vals.len();
986        match new_len > old_len {
987            true => {
988                (old_len..new_len).for_each(|i| {
989                    let value = f();
990                    match value.sign() {
991                        Sign::Plus => self.pos.insert(i),
992                        Sign::Minus => self.neg.insert(i),
993                    };
994                    self.vals.push(value);
995                });
996            }
997            false => {
998                (new_len..old_len).for_each(|i| {
999                    self.pos.remove(&i);
1000                    self.neg.remove(&i);
1001                });
1002                self.vals.truncate(new_len);
1003            }
1004        }
1005    }
1006    /// Retains only the elements specified by the predicate `f`.
1007    ///
1008    /// This method retains only the elements specified by the predicate `f` in the `vals` vector of
1009    /// this `SignVec`. It also adjusts the `pos` and `neg` sets accordingly based on the retained
1010    /// elements.
1011    ///
1012    /// # Arguments
1013    ///
1014    /// * `f`: A closure that takes a reference to an element and returns `true` if the element should
1015    ///        be retained, or `false` otherwise.
1016    ///
1017    /// # Examples
1018    ///
1019    /// ```
1020    /// use signvec::{SignVec, svec};
1021    ///
1022    /// let mut sign_vec = svec![5, -10, 15];
1023    /// sign_vec.retain(|&x| x >= 0);
1024    ///
1025    /// assert_eq!(sign_vec, svec![5, 15]);
1026    /// ```
1027    #[inline(always)]
1028    pub fn retain<F>(&mut self, f: F)
1029    where
1030        F: FnMut(&T) -> bool,
1031    {
1032        self.vals.retain(f);
1033        self.sync();
1034    }
1035
1036    /// Retains only the elements specified by the mutable predicate `f`.
1037    ///
1038    /// This method retains only the elements specified by the mutable predicate `f` in the `vals`
1039    /// vector of this `SignVec`. It also adjusts the `pos` and `neg` sets accordingly based on the
1040    /// retained elements.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// * `f`: A closure that takes a mutable reference to an element and returns `true` if the
1045    ///        element should be retained, or `false` otherwise.
1046    ///
1047    /// # Examples
1048    ///
1049    /// ```
1050    /// use signvec::{SignVec, svec};
1051    ///
1052    /// let mut sign_vec = svec![5, -10, 15];
1053    /// sign_vec.retain_mut(|x| *x >= 0);
1054    ///
1055    /// assert_eq!(sign_vec, svec![5, 15]);
1056    /// ```
1057    #[inline(always)]
1058    pub fn retain_mut<F>(&mut self, f: F)
1059    where
1060        F: FnMut(&mut T) -> bool,
1061    {
1062        self.vals.retain_mut(f);
1063        self.sync();
1064    }
1065
1066    /// Returns a random index of an element with the specified sign.
1067    ///
1068    /// This method returns a random index of an element with the specified sign (`Sign::Plus` or
1069    /// `Sign::Minus`) in the `SignVec`. If no elements with the specified sign exist, `None` is
1070    /// returned.
1071    ///
1072    /// # Arguments
1073    ///
1074    /// * `sign`: The sign of the element to search for.
1075    /// * `rng`: A mutable reference to a random number generator implementing the `WyRand` trait.
1076    ///
1077    /// # Examples
1078    ///
1079    /// ```
1080    /// use signvec::{SignVec, Sign, svec};
1081    /// use nanorand::WyRand;
1082    ///
1083    /// let sign_vec = svec![5, -10, 15];
1084    /// let mut rng = WyRand::new();
1085    /// let random_index = sign_vec.random(Sign::Plus, &mut rng);
1086    ///
1087    /// assert!(random_index.is_some());
1088    /// ```
1089    #[inline(always)]
1090    pub fn random(&self, sign: Sign, rng: &mut WyRand) -> Option<usize> {
1091        match sign {
1092            Sign::Plus => self.pos.random(rng),
1093            Sign::Minus => self.neg.random(rng),
1094        }
1095    }
1096
1097    /// Returns a random index of an element with a positive sign.
1098    ///
1099    /// This method is a specializion of the `random` function, for situations
1100    /// where the desired sign (positive, in this case) is known at compile time.
1101    /// Approximately 25 % faster than calling `random` with `Sign::Plus`
1102    ///
1103    /// If no elements with a positive sign exist in the `SignVec`, `None` is returned.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// * `rng`: A mutable reference to a random number generator implementing the `WyRand` trait.
1108    ///
1109    /// # Examples
1110    ///
1111    /// ```
1112    /// use signvec::{SignVec, svec};
1113    /// use nanorand::WyRand;
1114    ///
1115    /// let sv = svec![-5, 10, -15];
1116    /// let mut rng = WyRand::new();
1117    /// let idx = sv.random_pos(&mut rng).unwrap();
1118    ///
1119    /// assert_eq!(sv[idx], 10); // Assumes that `svec!` macro creates a vector where the index of 10 is accessible.
1120    /// ```
1121    ///
1122
1123    #[inline(always)]
1124    pub fn random_pos(&self, rng: &mut WyRand) -> Option<usize> {
1125        self.pos.random(rng)
1126    }
1127
1128    /// Returns a random index of an element with a positive sign.
1129    ///
1130    /// This method is a specializion of the `random` function, for situations
1131    /// where the desired sign (negative, in this case) is known at compile time.
1132    /// Approximately 25 % faster than calling `random` with `Sign::Minus`
1133    ///
1134    /// # Arguments
1135    ///
1136    /// * `rng`: A mutable reference to a random number generator implementing the `WyRand` trait.
1137    ///
1138    /// # Examples
1139    ///
1140    /// ```
1141    /// use signvec::{SignVec, svec};
1142    /// use nanorand::WyRand;
1143    ///
1144    /// let sv = svec![5, -10, 15];
1145    /// let mut rng = WyRand::new();
1146    /// let idx = sv.random_neg(&mut rng).unwrap();
1147    ///
1148    /// assert_eq!(sv[idx], -10);
1149    /// ```
1150    #[inline(always)]
1151    pub fn random_neg(&self, rng: &mut WyRand) -> Option<usize> {
1152        self.neg.random(rng)
1153    }
1154
1155    /// Sets the length of the vector.
1156    ///
1157    /// This method sets the length of the vector to `new_len`. If `new_len` is greater than the current
1158    /// length, additional elements are added and initialized with their default values. If `new_len` is
1159    /// less than the current length, the excess elements are removed from the vector.
1160    ///
1161    /// # Safety
1162    ///
1163    /// The caller must ensure that `new_len` is within the bounds of the vector's capacity and that
1164    /// the elements at indices `old_len..new_len` are properly initialized.
1165    ///
1166    /// # Panics
1167    ///
1168    /// Panics if `new_len` is greater than the vector's capacity.
1169    ///
1170    /// # Examples
1171    ///
1172    ///```
1173    /// use signvec::SignVec;
1174    ///
1175    /// unsafe {
1176    /// let mut sign_vec = SignVec::from(vec![5, -10, 15]);
1177    ///
1178    /// sign_vec.resize(5, 0);
1179    ///
1180    /// sign_vec.set_len(5);
1181    ///
1182    /// assert_eq!(sign_vec.len(), 5);
1183    /// }
1184    /// ```
1185    pub unsafe fn set_len(&mut self, new_len: usize) {
1186        // Check that new_len is within the bounds of the vector's capacity to avoid out-of-bounds access.
1187        if new_len > self.vals.capacity() {
1188            panic!("new_len out of bounds: new_len must be less than or equal to capacity()");
1189        }
1190
1191        let old_len = self.vals.len();
1192        match new_len.cmp(&old_len) {
1193            std::cmp::Ordering::Greater => {
1194                // SAFETY: The caller must ensure that the elements at old_len..new_len are properly initialized.
1195                self.vals.set_len(new_len);
1196                let vals_ptr = self.vals.as_mut_ptr();
1197                (old_len..new_len).for_each(|i| {
1198                    // SAFETY: This dereference is safe under the assumption that elements at old_len..new_len are initialized.
1199                    match unsafe { &*vals_ptr.add(i) }.sign() {
1200                        Sign::Plus => {
1201                            self.pos.insert(i);
1202                        }
1203                        Sign::Minus => {
1204                            self.neg.insert(i);
1205                        }
1206                    }
1207                });
1208            }
1209            std::cmp::Ordering::Less => {
1210                // If the new length is less than the old length, remove indices that are no longer valid.
1211                (new_len..old_len).for_each(|i| {
1212                    self.pos.remove(&i);
1213                    self.neg.remove(&i);
1214                });
1215                // SAFETY: This is safe as we're only reducing the vector's length, not accessing any elements.
1216                self.vals.set_len(new_len);
1217            }
1218            std::cmp::Ordering::Equal => {
1219                // If new_len == old_len, there's no need to do anything.
1220            }
1221        }
1222    }
1223
1224    /// Sets the value at the specified index.
1225    ///
1226    /// This method sets the value at the specified index to the given value. It also updates the
1227    /// positive (`pos`) and negative (`neg`) sets accordingly based on the sign change of the new
1228    /// value compared to the old value.
1229    ///
1230    /// # Arguments
1231    ///
1232    /// * `idx`: The index at which to set the value.
1233    /// * `val`: The new value to set.
1234    ///
1235    /// # Panics
1236    ///
1237    /// Panics if `idx` is out of bounds.
1238    ///
1239    /// # Examples
1240    ///
1241    /// ```
1242    /// use signvec::{SignVec, svec};
1243    ///
1244    /// let mut sign_vec = svec![5, -10, 15];
1245    /// sign_vec.set(1, 20);
1246    ///
1247    /// assert_eq!(sign_vec, svec![5, 20, 15]);
1248    /// ```
1249    #[inline(always)]
1250    pub fn set(&mut self, idx: usize, val: T) {
1251        if idx >= self.vals.len() {
1252            panic!(
1253                "Index out of bounds: index {} length {}",
1254                idx,
1255                self.vals.len()
1256            );
1257        }
1258        // Safety: We've verified that idx is within bounds above
1259        unsafe {
1260            self.set_unchecked(idx, val);
1261        }
1262    }
1263
1264    /// Sets the value at the specified index without bounds checking.
1265    ///
1266    /// This method sets the value at the specified index to the given value without performing any
1267    /// bounds checking. It also updates the positive (`pos`) and negative (`neg`) sets accordingly
1268    /// based on the sign change of the new value compared to the old value.
1269    ///
1270    /// # Safety
1271    ///
1272    /// The caller must ensure that `idx` is within the bounds of the vector. Failure to do so may
1273    /// result in undefined behavior, memory corruption, or program crashes due to dereferencing
1274    /// out-of-bounds memory and corruption of the internal `pos` and `neg` sets.
1275    ///
1276    /// # Examples
1277    ///
1278    /// ```
1279    /// use signvec::{SignVec, svec};
1280    ///
1281    /// let mut sign_vec = svec![5, -10, 15];
1282    /// unsafe {
1283    ///     sign_vec.set_unchecked(1, 20);
1284    /// }
1285    ///
1286    /// assert_eq!(sign_vec, svec![5, 20, 15]);
1287    /// ```
1288    #[inline(always)]
1289    pub unsafe fn set_unchecked(&mut self, idx: usize, mut val: T) {
1290        let old_val = &mut *self.vals.as_mut_ptr().add(idx);
1291        let old_sign = old_val.sign();
1292        let new_sign = val.sign();
1293        std::mem::swap(old_val, &mut val);
1294        if old_sign != new_sign {
1295            match new_sign {
1296                Sign::Plus => {
1297                    self.neg.remove(&idx);
1298                    self.pos.insert(idx);
1299                }
1300                Sign::Minus => {
1301                    self.pos.remove(&idx);
1302                    self.neg.insert(idx);
1303                }
1304            }
1305        }
1306    }
1307    /// Shrinks the capacity of the vector to at least `min_capacity`.
1308    ///
1309    /// This method reduces the capacity of the vector to at least `min_capacity` while maintaining
1310    /// its length. If the current capacity is already less than or equal to `min_capacity`, this
1311    /// method does nothing.
1312    ///
1313    /// # Arguments
1314    ///
1315    /// * `min_capacity`: The minimum capacity to which the vector should be shrunk.
1316    ///
1317    /// # Examples
1318    ///
1319    /// ```
1320    /// use signvec::SignVec;
1321    ///
1322    /// let mut sign_vec = SignVec::<f64>::with_capacity(10);
1323    /// sign_vec.extend(&[5.0, -10.0, 15.0]);
1324    /// assert!(sign_vec.capacity() >= 10);
1325    /// sign_vec.shrink_to(2);
1326    /// assert!(sign_vec.capacity() >= 3);
1327    ///
1328    /// ```
1329    #[inline(always)]
1330    pub fn shrink_to(&mut self, min_capacity: usize) {
1331        self.vals.shrink_to(min_capacity);
1332        self.pos.shrink_to(min_capacity);
1333        self.neg.shrink_to(min_capacity);
1334    }
1335
1336    /// Shrinks the capacity of the vector to fit its current length.
1337    ///
1338    /// This method reduces the capacity of the vector to fit its current length. If the current
1339    /// capacity is already equal to the length of the vector, this method does nothing.
1340    ///
1341    /// # Examples
1342    ///
1343    /// ```
1344    /// use signvec::{SignVec, svec};
1345    ///
1346    /// let mut sign_vec = svec![5, -10, 15];
1347    /// sign_vec.push(20);
1348    /// sign_vec.shrink_to_fit();
1349    ///
1350    /// assert_eq!(sign_vec.capacity(), 4); // Assuming the default capacity increase strategy
1351    /// ```
1352    #[inline(always)]
1353    pub fn shrink_to_fit(&mut self) {
1354        self.vals.shrink_to_fit();
1355        self.pos.shrink_to_fit();
1356        self.neg.shrink_to_fit();
1357    }
1358
1359    /// Returns a mutable slice of the unused capacity of the vector.
1360    ///
1361    /// This method returns a mutable slice of the uninitialized memory in the vector's capacity.
1362    /// Modifying the elements in this slice is safe, but reading from them may lead to undefined
1363    /// behavior.
1364    ///
1365    /// # Examples
1366    ///
1367    /// ```
1368    /// use signvec::{SignVec, svec};
1369    /// use std::mem::MaybeUninit;
1370    ///
1371    /// let mut sign_vec = svec![5, -10, 15];
1372    /// let unused_capacity = sign_vec.spare_capacity_mut();
1373    ///
1374    /// // Fill the spare capacity with new values
1375    /// for val in unused_capacity.iter_mut() {
1376    ///     *val = MaybeUninit::new(0);
1377    /// }
1378    ///
1379    /// // Now the spare capacity is filled with zeros
1380    /// ```
1381    #[inline(always)]
1382    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1383        let len = self.vals.len();
1384        let capacity = self.vals.capacity();
1385        unsafe {
1386            // SAFETY: The following is safe because MaybeUninit<T> can be uninitialized,
1387            // and we're only exposing the uninitialized part of the allocated memory.
1388            std::slice::from_raw_parts_mut(
1389                self.vals.as_mut_ptr().add(len) as *mut MaybeUninit<T>,
1390                capacity - len,
1391            )
1392        }
1393    }
1394
1395    /// Splits the vector into two at the given index.
1396    ///
1397    /// This method splits the vector into two at the given index `at`, returning a new vector
1398    /// containing the elements from index `at` onwards. The original vector will contain the
1399    /// elements up to but not including `at`. The positive (`pos`) and negative (`neg`) sets
1400    /// are updated accordingly for both vectors.
1401    ///
1402    /// # Arguments
1403    ///
1404    /// * `at`: The index at which to split the vector.
1405    ///
1406    /// # Panics
1407    ///
1408    /// Panics if `at` is greater than the length of the vector.
1409    ///
1410    /// # Examples
1411    ///
1412    /// ```
1413    /// use signvec::{SignVec, svec};
1414    ///
1415    /// let mut sign_vec = svec![5, -10, 15, -20];
1416    /// let new_vec = sign_vec.split_off(2);
1417    ///
1418    /// assert_eq!(sign_vec, svec![5, -10]);
1419    /// assert_eq!(new_vec, svec![15, -20]);
1420    /// ```
1421    pub fn split_off(&mut self, at: usize) -> SignVec<T> {
1422        // Ensure 'at' is within bounds to prevent out-of-bounds access.
1423        if at > self.vals.len() {
1424            panic!(
1425                "split_off at index out of bounds: the length is {} but the split index is {}",
1426                self.vals.len(),
1427                at
1428            );
1429        }
1430        let new_vals = self.vals.split_off(at);
1431        let mut new_pos = Set::with_max(new_vals.len());
1432        let mut new_neg = Set::with_max(new_vals.len());
1433        (0..new_vals.len()).for_each(|i| {
1434            if self.pos.contains(&(at + i)) {
1435                self.pos.remove(&(at + i));
1436                new_pos.insert(i);
1437            } else if self.neg.remove(&(at + i)) {
1438                // This also acts as a check, removing the item if present.
1439                new_neg.insert(i);
1440            }
1441        });
1442        SignVec {
1443            vals: new_vals,
1444            pos: new_pos,
1445            neg: new_neg,
1446            _marker: PhantomData,
1447        }
1448    }
1449    /// Removes and returns the element at the specified index, replacing it with the last element.
1450    ///
1451    /// This method removes and returns the element at the specified `index`, replacing it with the
1452    /// last element in the vector. The positive (`pos`) and negative (`neg`) sets are updated accordingly.
1453    ///
1454    /// # Arguments
1455    ///
1456    /// * `index`: The index of the element to be removed.
1457    ///
1458    /// # Returns
1459    ///
1460    /// The removed element.
1461    ///
1462    /// # Panics
1463    ///
1464    /// Panics if the `index` is out of bounds.
1465    ///
1466    /// # Examples
1467    ///
1468    /// ```
1469    /// use signvec::{SignVec, svec};
1470    ///
1471    /// let mut sign_vec = svec![5, -10, 15];
1472    /// let removed = sign_vec.swap_remove(1);
1473    ///
1474    /// assert_eq!(removed, -10);
1475    /// assert_eq!(sign_vec, svec![5, 15]);
1476    /// ```
1477    #[inline(always)]
1478    pub fn swap_remove(&mut self, index: usize) -> T {
1479        let removed_element = self.vals.swap_remove(index);
1480        let sign = removed_element.sign();
1481        match sign {
1482            Sign::Plus => self.pos.remove(&index),
1483            Sign::Minus => self.neg.remove(&index),
1484        };
1485
1486        if index < self.vals.len() {
1487            let swapped_element_sign = self.vals[index].sign();
1488            match swapped_element_sign {
1489                Sign::Plus => {
1490                    self.pos.remove(&self.vals.len());
1491                    self.pos.insert(index);
1492                }
1493                Sign::Minus => {
1494                    self.neg.remove(&self.vals.len());
1495                    self.neg.insert(index);
1496                }
1497            }
1498        }
1499        removed_element
1500    }
1501
1502    /// Synchronizes the positive and negative sets with the vector's elements.
1503    ///
1504    /// This method clears the positive (`pos`) and negative (`neg`) sets, and then re-inserts the
1505    /// indices of the elements in the vector according to their signs.
1506    ///
1507    /// # Examples
1508    ///
1509    /// ```
1510    /// use signvec::{SignVec, svec};
1511    ///
1512    /// let mut sign_vec = svec![5, -10, 15];
1513    /// sign_vec.retain(|&x| x >= 0);
1514    /// sign_vec.sync();
1515    ///
1516    /// assert_eq!(sign_vec, svec![5, 15]);
1517    /// ```
1518    #[inline(always)]
1519    pub fn sync(&mut self) {
1520        self.pos.clear();
1521        self.neg.clear();
1522        self.vals.iter().enumerate().for_each(|(idx, val)| {
1523            match val.sign() {
1524                Sign::Plus => self.pos.insert(idx),
1525                Sign::Minus => self.neg.insert(idx),
1526            };
1527        });
1528    }
1529    /// Truncates the `SignVec` to the specified length.
1530    ///
1531    /// This method truncates the `SignVec`, keeping only the first `len` elements. It updates the
1532    /// positive (`pos`) and negative (`neg`) sets accordingly.
1533    ///
1534    /// # Arguments
1535    ///
1536    /// * `len`: The new length of the `SignVec`.
1537    ///
1538    /// # Examples
1539    ///
1540    /// ```
1541    /// use signvec::{SignVec, svec};
1542    ///
1543    /// let mut sign_vec = svec![5, -10, 15];
1544    /// sign_vec.truncate(2);
1545    ///
1546    /// assert_eq!(sign_vec, svec![5, -10]);
1547    /// ```
1548    #[inline(always)]
1549    pub fn truncate(&mut self, len: usize) {
1550        if len < self.vals.len() {
1551            let old_len = self.vals.len();
1552            unsafe {
1553                let vals_ptr = self.vals.as_ptr();
1554                for i in len..old_len {
1555                    let val = &*vals_ptr.add(i);
1556                    match val.sign() {
1557                        Sign::Plus => self.pos.remove(&i),
1558                        Sign::Minus => self.neg.remove(&i),
1559                    };
1560                }
1561            }
1562            self.vals.truncate(len);
1563        }
1564    }
1565
1566    /// Tries to reserve capacity for at least `additional` more elements to be inserted in the vector.
1567    ///
1568    /// This method tries to reserve capacity for at least `additional` more elements to be inserted
1569    /// in the vector. It updates the capacity of the positive (`pos`) and negative (`neg`) sets
1570    /// accordingly.
1571    ///
1572    /// # Arguments
1573    ///
1574    /// * `additional`: The number of additional elements to reserve capacity for.
1575    ///
1576    /// # Returns
1577    ///
1578    /// * `Ok(())` if the capacity was successfully reserved, or an error if the allocation failed.
1579    ///
1580    /// # Examples
1581    ///
1582    /// ```
1583    /// use signvec::{SignVec, svec};
1584    ///
1585    /// let mut sign_vec = svec![5, -10, 15];
1586    /// sign_vec.try_reserve(5).unwrap();
1587    /// ```
1588    pub fn try_reserve(
1589        &mut self,
1590        additional: usize,
1591    ) -> Result<(), std::collections::TryReserveError> {
1592        self.vals.try_reserve(additional)?;
1593        self.pos.reserve(self.vals.len() + additional);
1594        self.neg.reserve(self.vals.len() + additional);
1595        Ok(())
1596    }
1597
1598    /// Tries to reserve the exact capacity for the vector to hold `additional` more elements.
1599    ///
1600    /// This method tries to reserve the exact capacity for the vector to hold `additional` more
1601    /// elements. It updates the capacity of the positive (`pos`) and negative (`neg`) sets
1602    /// accordingly.
1603    ///
1604    /// # Arguments
1605    ///
1606    /// * `additional`: The number of additional elements to reserve capacity for.
1607    ///
1608    /// # Returns
1609    ///
1610    /// * `Ok(())` if the capacity was successfully reserved, or an error if the allocation failed.
1611    ///
1612    /// # Examples
1613    ///
1614    /// ```
1615    /// use signvec::{SignVec, svec};
1616    ///
1617    /// let mut sign_vec = svec![5, -10, 15];
1618    /// sign_vec.try_reserve_exact(5).unwrap();
1619    /// ```
1620    pub fn try_reserve_exact(
1621        &mut self,
1622        additional: usize,
1623    ) -> Result<(), std::collections::TryReserveError> {
1624        self.vals.try_reserve_exact(additional)?;
1625        self.pos.reserve(self.vals.len() + additional);
1626        self.neg.reserve(self.vals.len() + additional);
1627        Ok(())
1628    }
1629
1630    /// Returns an iterator over the values with the specified sign.
1631    ///
1632    /// This method returns an iterator over the values in the `SignVec` with the specified `sign`.
1633    ///
1634    /// # Arguments
1635    ///
1636    /// * `sign`: The sign of the values to iterate over.
1637    ///
1638    /// # Examples
1639    ///
1640    /// ```
1641    /// use signvec::{SignVec, Sign, svec};
1642    ///
1643    /// let sign_vec = svec![5, -10, 15];
1644    /// let positive_values: Vec<&i32> = sign_vec.values(Sign::Plus).collect();
1645    ///
1646    /// assert_eq!(positive_values, vec![&5, &15]);
1647    /// ```
1648    #[inline(always)]
1649    pub fn values(&self, sign: Sign) -> SignVecValues<T> {
1650        SignVecValues::new(self, sign)
1651    }
1652
1653    /// Creates a new empty `SignVec` with the specified capacity.
1654    ///
1655    /// This method creates a new empty `SignVec` with the specified `capacity`.
1656    ///
1657    /// # Arguments
1658    ///
1659    /// * `capacity`: The capacity of the new `SignVec`.
1660    ///
1661    /// # Examples
1662    ///
1663    /// ```
1664    /// use signvec::SignVec;
1665    ///
1666    /// let sign_vec: SignVec<f64> = SignVec::with_capacity(10);
1667    /// assert!(sign_vec.is_empty());
1668    /// ```
1669    #[inline(always)]
1670    pub fn with_capacity(capacity: usize) -> Self {
1671        Self {
1672            vals: Vec::with_capacity(capacity),
1673            pos: Set::with_max(capacity),
1674            neg: Set::with_max(capacity),
1675            _marker: PhantomData,
1676        }
1677    }
1678}
1679
1680/// An iterator that drains elements from a `SignVec`.
1681///
1682/// This iterator yields elements from a `SignVec`, removing them and adjusting the
1683/// internal positive and negative sets accordingly.
1684pub struct SignVecDrain<'a, T: 'a + Clone + Signable> {
1685    /// A mutable reference to the `SignVec` being drained.
1686    sign_vec: &'a mut SignVec<T>,
1687    /// The current index being processed during draining.
1688    current_index: usize,
1689    /// The end index of the drain operation.
1690    drain_end: usize,
1691}
1692
1693impl<'a, T> Iterator for SignVecDrain<'a, T>
1694where
1695    T: Signable + Clone,
1696{
1697    type Item = T;
1698
1699    /// Advances the iterator and returns the next item.
1700    ///
1701    /// This method returns `Some(item)` if there are more items to process,
1702    /// otherwise it returns `None`.
1703    fn next(&mut self) -> Option<Self::Item> {
1704        if self.current_index >= self.drain_end {
1705            return None;
1706        }
1707
1708        // Perform the actual removal.
1709        let result = self.sign_vec.vals.remove(self.current_index);
1710        // No need to adjust self.current_index as we always remove the current element.
1711
1712        // Update pos and neg to reflect the removal.
1713        // Since we are always removing the current element, we just need to update subsequent indices.
1714        // Remove the current index from pos or neg if present.
1715        self.sign_vec.pos.remove(&self.current_index);
1716        self.sign_vec.neg.remove(&self.current_index);
1717
1718        // Adjust indices for remaining elements in pos and neg.
1719        self.sign_vec.pos = self
1720            .sign_vec
1721            .pos
1722            .iter()
1723            .map(|&i| if i > self.current_index { i - 1 } else { i })
1724            .collect();
1725        self.sign_vec.neg = self
1726            .sign_vec
1727            .neg
1728            .iter()
1729            .map(|&i| if i > self.current_index { i - 1 } else { i })
1730            .collect();
1731
1732        // Adjust the drain_end since the vector's length has decreased by one.
1733        self.drain_end -= 1;
1734
1735        Some(result)
1736    }
1737}
1738
1739#[derive(Debug)]
1740pub struct SignVecValues<'a, T>
1741where
1742    T: 'a + Signable + Clone,
1743{
1744    // Store a raw pointer to the vector's data.
1745    vals_ptr: *const T,
1746    indices_iter: std::slice::Iter<'a, usize>,
1747}
1748
1749impl<'a, T> SignVecValues<'a, T>
1750where
1751    T: Signable + Clone,
1752{
1753    #[inline(always)]
1754    pub fn new(sign_vec: &'a SignVec<T>, sign: Sign) -> Self {
1755        // Obtain a raw pointer to the data of the `vals` vector.
1756        let vals_ptr = sign_vec.vals.as_ptr();
1757        let indices_iter = match sign {
1758            Sign::Plus => (&sign_vec.pos).into_iter(),
1759            Sign::Minus => (&sign_vec.neg).into_iter(),
1760        };
1761        SignVecValues {
1762            vals_ptr,
1763            indices_iter,
1764        }
1765    }
1766}
1767
1768impl<'a, T> Iterator for SignVecValues<'a, T>
1769where
1770    T: 'a + Signable + Clone,
1771{
1772    type Item = &'a T;
1773
1774    #[inline(always)]
1775    fn next(&mut self) -> Option<Self::Item> {
1776        self.indices_iter.next().map(|&idx|
1777            // Safety: The index is assumed to be within bounds, as indices are managed internally
1778            // and should be valid for the `vals` vector. Accessing the vector's elements
1779            // via a raw pointer obtained from `as_ptr` assumes that no concurrent modifications
1780            // occur, and the vector's length does not change during iteration.
1781            unsafe { &*self.vals_ptr.add(idx) })
1782    }
1783}
1784
1785/// Allows accessing the underlying vector reference of a `SignVec`.
1786impl<T> AsRef<Vec<T>> for SignVec<T>
1787where
1788    T: Signable + Clone,
1789{
1790    /// Returns a reference to the underlying vector.
1791    fn as_ref(&self) -> &Vec<T> {
1792        &self.vals
1793    }
1794}
1795
1796/// Implements the default trait for `SignVec`.
1797///
1798/// This allows creating a new empty `SignVec` with a default capacity.
1799impl<T> Default for SignVec<T>
1800where
1801    T: Signable + Clone,
1802{
1803    /// Creates a new empty `SignVec` with a default capacity.
1804    ///
1805    /// The default capacity is determined by the `DEFAULT_SET_SIZE` constant.
1806    fn default() -> Self {
1807        Self {
1808            vals: Vec::default(),
1809            pos: Set::with_max(DEFAULT_SET_SIZE),
1810            neg: Set::with_max(DEFAULT_SET_SIZE),
1811            _marker: PhantomData,
1812        }
1813    }
1814}
1815
1816/// Implements extending functionality for references to items.
1817impl<'a, T> Extend<&'a T> for SignVec<T>
1818where
1819    T: Signable + Clone + 'a,
1820{
1821    /// Extends the `SignVec` with items from an iterator over references to items.
1822    ///
1823    /// This method clones each item from the iterator and appends it to the `SignVec`,
1824    /// adjusting the positive and negative sets accordingly based on the sign of each item.
1825    ///
1826    /// # Arguments
1827    ///
1828    /// * `iter`: An iterator over references to items to be extended into the `SignVec`.
1829    ///
1830    /// # Examples
1831    ///
1832    /// ```
1833    /// use signvec::{SignVec, Sign, svec};
1834    ///
1835    /// let mut sign_vec: SignVec<i32> = svec![-5, 10, -15];
1836    /// assert_eq!(sign_vec.len(), 3);
1837    /// assert_eq!(sign_vec.count(Sign::Plus), 1);
1838    /// assert_eq!(sign_vec.count(Sign::Minus), 2);
1839    ///
1840    /// let items: Vec<i32> = vec![5, -10, 15];
1841    /// sign_vec.extend(items.iter());
1842    /// assert_eq!(sign_vec.len(), 6);
1843    ///
1844    /// assert_eq!(sign_vec.count(Sign::Plus), 3);
1845    /// assert_eq!(sign_vec.count(Sign::Minus), 3);
1846    /// ```
1847    fn extend<I>(&mut self, iter: I)
1848    where
1849        I: IntoIterator<Item = &'a T>,
1850    {
1851        for item in iter {
1852            let index = self.vals.len(); // Get the current length before pushing
1853            self.vals.push(item.clone()); // Clone the item and push it onto vals
1854            match item.sign() {
1855                Sign::Plus => {
1856                    self.pos.insert(index);
1857                }
1858                Sign::Minus => {
1859                    self.neg.insert(index);
1860                }
1861            }
1862        }
1863    }
1864}
1865
1866/// Implements extending functionality for owned items.
1867impl<T> Extend<T> for SignVec<T>
1868where
1869    T: Signable + Clone,
1870{
1871    /// Extends the `SignVec` with items from an iterator over owned items.
1872    ///
1873    /// This method appends each item from the iterator to the `SignVec`,
1874    /// adjusting the positive and negative sets accordingly based on the sign of each item.
1875    ///
1876    /// # Arguments
1877    ///
1878    /// * `iter`: An iterator over owned items to be extended into the `SignVec`.
1879    ///
1880    /// # Examples
1881    ///
1882    /// ```
1883    /// use signvec::{svec, Sign, SignVec};
1884    ///
1885    /// let mut sign_vec = svec![-15, 10, -5];
1886    ///
1887    /// assert_eq!(sign_vec.len(), 3);
1888    /// assert_eq!(sign_vec.count(Sign::Plus), 1);
1889    /// assert_eq!(sign_vec.count(Sign::Minus), 2);
1890    ///
1891    /// let items = vec![5, -10, 15];
1892    /// sign_vec.extend(items.into_iter());
1893    ///
1894    /// assert_eq!(sign_vec.len(), 6);
1895    /// assert_eq!(sign_vec.count(Sign::Plus), 3);
1896    /// assert_eq!(sign_vec.count(Sign::Minus), 3);
1897    /// ```
1898    fn extend<I>(&mut self, iter: I)
1899    where
1900        I: IntoIterator<Item = T>,
1901    {
1902        for item in iter {
1903            let index = self.vals.len(); // Get the current length before pushing
1904            match item.sign() {
1905                Sign::Plus => {
1906                    self.pos.insert(index);
1907                }
1908                Sign::Minus => {
1909                    self.neg.insert(index);
1910                }
1911            }
1912            self.vals.push(item); // Push the item onto vals
1913        }
1914    }
1915}
1916
1917impl<T> From<&[T]> for SignVec<T>
1918where
1919    T: Signable + Clone,
1920{
1921    /// Converts a slice reference into a `SignVec` by cloning its elements.
1922    ///
1923    /// # Examples
1924    ///
1925    /// ```
1926    /// use signvec::SignVec;
1927    ///
1928    /// let slice = &[1, 2, 3, 4, 5];
1929    /// let sign_vec: SignVec<_> = slice.into();
1930    /// ```
1931    fn from(slice: &[T]) -> Self {
1932        slice.iter().cloned().collect()
1933    }
1934}
1935
1936impl<T, const N: usize> From<&[T; N]> for SignVec<T>
1937where
1938    T: Signable + Clone,
1939{
1940    /// Converts a shared reference to an array into a `SignVec` by cloning its elements.
1941    ///
1942    /// # Examples
1943    ///
1944    /// ```
1945    /// use signvec::SignVec;
1946    ///
1947    /// let array = &[1, 2, 3, 4, 5];
1948    /// let sign_vec: SignVec<_> = array.into();
1949    /// ```
1950    fn from(array: &[T; N]) -> Self {
1951        array.iter().cloned().collect()
1952    }
1953}
1954
1955impl<T> From<&mut [T]> for SignVec<T>
1956where
1957    T: Signable + Clone,
1958{
1959    /// Converts a mutable slice reference into a `SignVec` by cloning its elements.
1960    ///
1961    /// # Examples
1962    ///
1963    /// ```
1964    /// use signvec::SignVec;
1965    ///
1966    /// let mut mutable_slice = &mut [1, -5, 7];
1967    /// let sign_vec: SignVec<_> = mutable_slice.into();
1968    /// ```
1969    fn from(slice: &mut [T]) -> Self {
1970        slice.iter().cloned().collect()
1971    }
1972}
1973
1974impl<T, const N: usize> From<&mut [T; N]> for SignVec<T>
1975where
1976    T: Signable + Clone,
1977{
1978    /// Converts a mutable reference to an array into a `SignVec` by cloning its elements.
1979    ///
1980    /// # Examples
1981    ///
1982    /// ```
1983    /// use signvec::SignVec;
1984    ///
1985    /// let mut mutable_array = &mut [1.0, 2.0, 3.0];
1986    /// let sign_vec: SignVec<_> = mutable_array.into();
1987    /// ```
1988    fn from(array: &mut [T; N]) -> Self {
1989        array.iter().cloned().collect()
1990    }
1991}
1992
1993impl<T> From<&Vec<T>> for SignVec<T>
1994where
1995    T: Signable + Clone,
1996{
1997    /// Converts a vector reference into a `SignVec` by cloning its elements.
1998    ///
1999    /// # Examples
2000    ///
2001    /// ```
2002    /// use signvec::SignVec;
2003    ///
2004    /// let vec = vec![1, 2, 3, 4, 5];
2005    /// let sign_vec: SignVec<_> = (&vec).into();
2006    /// ```
2007    fn from(vec: &Vec<T>) -> Self {
2008        vec.iter().cloned().collect()
2009    }
2010}
2011
2012impl<T> From<Vec<T>> for SignVec<T>
2013where
2014    T: Signable + Clone,
2015{
2016    /// Converts a vector into a `SignVec`, moving its elements.
2017    ///
2018    /// # Examples
2019    ///
2020    /// ```
2021    /// use signvec::SignVec;
2022    ///
2023    /// let vec = vec![1, 2, 3, 4, 5];
2024    /// let sign_vec: SignVec<_> = vec.into();
2025    /// ```
2026    fn from(vec: Vec<T>) -> Self {
2027        vec.into_iter().collect()
2028    }
2029}
2030
2031impl<T> From<SignVec<T>> for Vec<T>
2032where
2033    T: Signable + Clone,
2034{
2035    /// Converts a `SignVec` into a `Vec`, moving its elements.
2036    ///
2037    /// # Examples
2038    ///
2039    /// ```
2040    /// use signvec::{SignVec, svec};
2041    ///
2042    /// let sv = svec![1, 2, 3, 4, 5];
2043    /// let vec: Vec<_> = Vec::from(&sv);
2044    /// ```
2045    fn from(sign_vec: SignVec<T>) -> Self {
2046        sign_vec.vals.clone()
2047    }
2048}
2049
2050impl<T> From<&SignVec<T>> for Vec<T>
2051where
2052    T: Signable + Clone,
2053{
2054    /// Converts a reference to `SignVec` into a `Vec`, cloning its elements.
2055    ///
2056    /// # Examples
2057    ///
2058    /// ```
2059    /// use signvec::{SignVec, svec};
2060    ///
2061    /// let sign_vec: SignVec<i32> = svec![1, 2, 3, 4, 5];
2062    /// let vec: Vec<i32> = Vec::from(&sign_vec);
2063    ///
2064    /// ```
2065    fn from(sign_vec: &SignVec<T>) -> Self {
2066        sign_vec.vals.clone()
2067    }
2068}
2069
2070impl<T, const N: usize> From<[T; N]> for SignVec<T>
2071where
2072    T: Signable + Clone,
2073{
2074    /// Converts an owned array into a `SignVec`, moving its elements.
2075    ///
2076    /// # Examples
2077    ///
2078    /// ```
2079    /// use signvec::SignVec;
2080    ///
2081    /// let array = [1, 2, 3, 4, 5];
2082    /// let sign_vec: SignVec<_> = array.into();
2083    /// ```
2084    fn from(array: [T; N]) -> Self {
2085        array.into_iter().collect()
2086    }
2087}
2088
2089impl<T> FromIterator<T> for SignVec<T>
2090where
2091    T: Signable + Clone,
2092{
2093    /// Constructs a `SignVec` from an iterator, cloning each element.
2094    ///
2095    /// # Examples
2096    ///
2097    /// ```
2098    /// use signvec::SignVec;
2099    ///
2100    /// let iter = vec![1, -2, 3, -4, 5].into_iter();
2101    /// let sign_vec: SignVec<_> = iter.collect();
2102    /// ```
2103    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2104        let mut vec = Vec::new();
2105        let mut pos = Set::with_max(DEFAULT_SET_SIZE);
2106        let mut neg = Set::with_max(DEFAULT_SET_SIZE);
2107
2108        for (i, item) in iter.into_iter().enumerate() {
2109            if item.sign() == Sign::Plus {
2110                pos.insert(i);
2111            } else {
2112                neg.insert(i);
2113            }
2114            vec.push(item);
2115        }
2116
2117        SignVec {
2118            vals: vec,
2119            pos,
2120            neg,
2121            _marker: PhantomData,
2122        }
2123    }
2124}
2125
2126impl<'a, T> FromIterator<&'a T> for SignVec<T>
2127where
2128    T: 'a + Signable + Clone,
2129{
2130    /// Constructs a `SignVec` from an iterator of references, cloning each element.
2131    ///
2132    /// # Examples
2133    ///
2134    /// ```
2135    /// use signvec::SignVec;
2136    ///
2137    /// let iter = vec![&1, &-2, &3, &-4, &5].into_iter();
2138    /// let sign_vec: SignVec<_> = iter.collect();
2139    /// ```
2140    fn from_iter<I: IntoIterator<Item = &'a T>>(iter: I) -> Self {
2141        let mut vec = Vec::new();
2142        let mut pos = Set::with_max(DEFAULT_SET_SIZE);
2143        let mut neg = Set::with_max(DEFAULT_SET_SIZE);
2144
2145        for (i, item) in iter.into_iter().enumerate() {
2146            let cloned_item = item.clone();
2147            if cloned_item.sign() == Sign::Plus {
2148                pos.insert(i);
2149            } else {
2150                neg.insert(i);
2151            }
2152            vec.push(cloned_item);
2153        }
2154
2155        SignVec {
2156            vals: vec,
2157            pos,
2158            neg,
2159            _marker: PhantomData,
2160        }
2161    }
2162}
2163
2164impl<T> IntoIterator for SignVec<T>
2165where
2166    T: Signable + Clone,
2167{
2168    type Item = T;
2169    type IntoIter = ::std::vec::IntoIter<T>;
2170
2171    /// Converts the `SignVec` into an iterator consuming the original `SignVec`.
2172    ///
2173    /// # Examples
2174    ///
2175    /// ```
2176    /// use signvec::SignVec;
2177    ///
2178    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
2179    /// let mut iter = sign_vec.into_iter();
2180    /// assert_eq!(iter.next(), Some(1));
2181    /// assert_eq!(iter.next(), Some(-2));
2182    /// assert_eq!(iter.next(), Some(3));
2183    /// assert_eq!(iter.next(), None);
2184    /// ```
2185    fn into_iter(self) -> Self::IntoIter {
2186        self.vals.into_iter()
2187    }
2188}
2189
2190impl<'a, T> IntoIterator for &'a SignVec<T>
2191where
2192    T: Signable + Clone,
2193{
2194    type Item = &'a T;
2195    type IntoIter = ::std::slice::Iter<'a, T>;
2196
2197    /// Converts the `SignVec` into an iterator yielding references to elements.
2198    ///
2199    /// # Examples
2200    ///
2201    /// ```
2202    /// use signvec::SignVec;
2203    ///
2204    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
2205    /// let mut iter = sign_vec.iter();
2206    /// assert_eq!(iter.next(), Some(&1));
2207    /// assert_eq!(iter.next(), Some(&-2));
2208    /// assert_eq!(iter.next(), Some(&3));
2209    /// assert_eq!(iter.next(), None);
2210    /// ```
2211    fn into_iter(self) -> Self::IntoIter {
2212        self.vals.iter()
2213    }
2214}
2215
2216impl<'a, T> IntoIterator for &'a mut SignVec<T>
2217where
2218    T: Signable + Clone,
2219{
2220    type Item = &'a mut T;
2221    type IntoIter = ::std::slice::IterMut<'a, T>;
2222
2223    /// Converts the `SignVec` into an iterator yielding mutable references to elements.
2224    ///
2225    /// # Examples
2226    ///
2227    /// ```
2228    /// use signvec::{SignVec, svec};
2229    ///
2230    /// let mut sign_vec = SignVec::from(vec![1, -2, 3]);
2231    /// for elem in &mut sign_vec {
2232    ///    *elem += 1;
2233    /// }
2234    /// assert_eq!(sign_vec, svec![2, -1, 4]);
2235    /// ```
2236    fn into_iter(self) -> Self::IntoIter {
2237        self.vals.iter_mut()
2238    }
2239}
2240
2241// Allowing indexing into SignVec to get a reference to an element
2242impl<T> Index<usize> for SignVec<T>
2243where
2244    T: Signable + Clone,
2245{
2246    type Output = T;
2247
2248    /// Returns a reference to the element at the given index.
2249    ///
2250    /// # Panics
2251    ///
2252    /// Panics if the index is out of bounds.
2253    ///
2254    /// # Examples
2255    ///
2256    /// ```
2257    /// use signvec::SignVec;
2258    ///
2259    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
2260    /// assert_eq!(sign_vec[0], 1);
2261    /// assert_eq!(sign_vec[1], -2);
2262    /// assert_eq!(sign_vec[2], 3);
2263    /// ```
2264    fn index(&self, index: usize) -> &Self::Output {
2265        &self.vals[index]
2266    }
2267}
2268
2269// Allowing dereferencing to a slice of SignVec values
2270impl<T> Deref for SignVec<T>
2271where
2272    T: Signable + Clone,
2273{
2274    type Target = [T];
2275
2276    /// Dereferences the SignVec to a slice of its values.
2277    ///
2278    /// # Examples
2279    ///
2280    /// ```
2281    /// use signvec::SignVec;
2282    ///
2283    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
2284    /// assert_eq!(&*sign_vec, &[1, -2, 3]);
2285    /// ```
2286    fn deref(&self) -> &Self::Target {
2287        &self.vals
2288    }
2289}
2290
2291impl<T> Borrow<[T]> for SignVec<T>
2292where
2293    T: Signable + Clone,
2294{
2295    /// Borrows the SignVec as a slice of its values.
2296    ///
2297    /// # Examples
2298    ///
2299    /// ```
2300    /// use signvec::SignVec;
2301    /// use std::borrow::Borrow;
2302    ///
2303    /// let sign_vec = SignVec::<i32>::from(vec![1, -2, 3]);
2304    /// assert_eq!(<SignVec<i32> as std::borrow::Borrow<[i32]>>::borrow(&sign_vec), &[1, -2, 3]);
2305    /// ```
2306    fn borrow(&self) -> &[T] {
2307        &self.vals
2308    }
2309}
2310
2311impl<T> Hash for SignVec<T>
2312where
2313    T: Signable + Clone + Hash,
2314{
2315    /// Computes the hash value for the SignVec.
2316    ///
2317    /// The hash value includes the length of the SignVec and the hash value of each element.
2318    ///
2319    /// # Examples
2320    ///
2321    /// ```
2322    /// use signvec::SignVec;
2323    /// use std::hash::{Hash, Hasher};
2324    ///
2325    /// let mut hasher = std::collections::hash_map::DefaultHasher::new();
2326    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
2327    /// sign_vec.hash(&mut hasher);
2328    /// let hash_value = hasher.finish();
2329    /// ```
2330    fn hash<H: Hasher>(&self, state: &mut H) {
2331        self.vals.len().hash(state);
2332        for item in &self.vals {
2333            item.hash(state);
2334        }
2335    }
2336}
2337
2338impl<T> Ord for SignVec<T>
2339where
2340    T: Signable + Clone + Ord,
2341{
2342    /// Compares two SignVecs lexicographically.
2343    ///
2344    /// # Examples
2345    ///
2346    /// ```
2347    /// use signvec::SignVec;
2348    ///
2349    /// let vec1 = SignVec::from(vec![1, -2, 3]);
2350    /// let vec2 = SignVec::from(vec![1, -3, 4]);
2351    ///
2352    /// assert!(vec1 > vec2);
2353    /// ```
2354    fn cmp(&self, other: &Self) -> Ordering {
2355        self.vals.cmp(&other.vals)
2356    }
2357}
2358
2359impl<T> PartialOrd for SignVec<T>
2360where
2361    T: Signable + Clone + PartialOrd,
2362{
2363    /// Compares two SignVecs lexicographically.
2364    ///
2365    /// # Examples
2366    ///
2367    /// ```
2368    /// use signvec::SignVec;
2369    ///
2370    /// let vec1 = SignVec::from(vec![1, -2, 3]);
2371    /// let vec2 = SignVec::from(vec![1, -3, 4]);
2372    ///
2373    /// assert!(vec1 > vec2);
2374    /// ```
2375    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2376        self.vals.partial_cmp(&other.vals)
2377    }
2378}
2379
2380impl<T> Eq for SignVec<T> where T: Signable + Clone + Eq {}
2381
2382impl<T> PartialEq for SignVec<T>
2383where
2384    T: Signable + Clone + PartialEq,
2385{
2386    /// Checks if two SignVecs are equal.
2387    ///
2388    /// # Examples
2389    ///
2390    /// ```
2391    /// use signvec::SignVec;
2392    ///
2393    /// let vec1 = SignVec::from(vec![1, -2, 3]);
2394    /// let vec2 = SignVec::from(vec![1, -2, 3]);
2395    ///
2396    /// assert_eq!(vec1, vec2);
2397    /// ```
2398    fn eq(&self, other: &Self) -> bool {
2399        self.vals.eq(&other.vals)
2400    }
2401}
2402
2403// Implementations for comparisons between SignVec and slices, mutable slices, arrays, and vectors
2404
2405impl<T, U> PartialEq<&[U]> for SignVec<T>
2406where
2407    T: PartialEq<U> + Signable + Clone,
2408{
2409    /// Checks if a SignVec is equal to a slice.
2410    ///
2411    /// # Examples
2412    ///
2413    /// ```
2414    /// use signvec::SignVec;
2415    ///
2416    /// let vec = SignVec::<i32>::from(vec![1, -2, 3]);
2417    ///
2418    /// assert_eq!(vec, &[1, -2, 3] as &[i32]);
2419    /// ```
2420    fn eq(&self, other: &&[U]) -> bool {
2421        self.vals.eq(other)
2422    }
2423}
2424
2425impl<T, U> PartialEq<&mut [U]> for SignVec<T>
2426where
2427    T: PartialEq<U> + Signable + Clone,
2428{
2429    /// Checks if a SignVec is equal to a mutable slice.
2430    ///
2431    /// # Examples
2432    ///
2433    /// ```
2434    /// use signvec::SignVec;
2435    ///
2436    /// let vec = SignVec::<f64>::from(vec![1.0, -2.0, 3.0]);
2437    ///
2438    /// assert_eq!(vec, &[1.0, -2.0, 3.0] as &[f64]);
2439    /// ```
2440
2441    fn eq(&self, other: &&mut [U]) -> bool {
2442        self.vals.eq(*other)
2443    }
2444}
2445
2446impl<T, U, const N: usize> PartialEq<[U; N]> for SignVec<T>
2447where
2448    T: PartialEq<U> + Signable + Clone,
2449{
2450    /// Checks if a SignVec is equal to an array.
2451    ///
2452    /// # Examples
2453    ///
2454    /// ```
2455    /// use signvec::SignVec;
2456    ///
2457    /// let vec = SignVec::from(vec![1, -2, 3]);
2458    ///
2459    /// assert_eq!(vec, [1, -2, 3]);
2460    /// ```
2461    fn eq(&self, other: &[U; N]) -> bool {
2462        self.vals.eq(other)
2463    }
2464}
2465
2466impl<T, U> PartialEq<Vec<U>> for SignVec<T>
2467where
2468    T: PartialEq<U> + Signable + Clone,
2469{
2470    /// Checks if a SignVec is equal to a vector.
2471    ///
2472    /// # Examples
2473    ///
2474    /// ```
2475    /// use signvec::SignVec;
2476    ///
2477    /// let vec = SignVec::from(vec![1, -2, 3]);
2478    ///
2479    /// assert_eq!(vec, vec![1, -2, 3]);
2480    /// ```
2481    fn eq(&self, other: &Vec<U>) -> bool {
2482        self.vals.eq(other)
2483    }
2484}
2485
2486#[cfg(test)]
2487mod tests {
2488    use super::*;
2489    use crate::svec;
2490    use fastset::set;
2491    use std::collections::HashSet;
2492
2493    #[derive(Clone, Eq, PartialEq, Default)]
2494    struct Account {
2495        balance: i32, // Assuming balance can be positive or negative
2496    }
2497
2498    impl Account {
2499        fn new(balance: i32) -> Self {
2500            Account { balance }
2501        }
2502
2503        fn balance(&self) -> i32 {
2504            self.balance
2505        }
2506    }
2507
2508    impl Signable for Account {
2509        fn sign(&self) -> Sign {
2510            if self.balance >= 0 {
2511                Sign::Plus
2512            } else {
2513                Sign::Minus
2514            }
2515        }
2516    }
2517
2518    #[test]
2519    fn test_append() {
2520        // Test appending positive elements
2521        let mut vec = svec![-1];
2522        let other = vec![2, -3];
2523        vec.append(&other);
2524        assert_eq!(vec.as_slice(), &[-1, 2, -3]);
2525        assert_eq!(vec.count(Sign::Plus), 1);
2526        assert_eq!(vec.count(Sign::Minus), 2);
2527
2528        // Test appending negative elements
2529        let mut vec = svec![];
2530        let other = vec![-2, 3];
2531        vec.append(&other);
2532        assert_eq!(vec.as_slice(), &[-2, 3]);
2533        assert_eq!(vec.count(Sign::Plus), 1);
2534        assert_eq!(vec.count(Sign::Minus), 1);
2535    }
2536
2537    #[test]
2538    fn test_as_ptr() {
2539        let vec: SignVec<i32> = svec![1, -2, 3];
2540        let ptr = vec.as_ptr();
2541        unsafe {
2542            assert_eq!(*ptr, 1); // First element
2543            assert_eq!(*ptr.offset(1), -2); // Second element
2544            assert_eq!(*ptr.offset(2), 3); // Third element
2545        }
2546    }
2547    #[test]
2548    fn test_as_slice() {
2549        let vec = svec![1, -2, 3];
2550        let slice = vec.as_slice();
2551        assert_eq!(slice, &[1, -2, 3]);
2552    }
2553
2554    #[test]
2555    fn test_capacity() {
2556        let vec = SignVec::<i32>::with_capacity(10);
2557        assert_eq!(vec.capacity(), 10);
2558    }
2559
2560    #[test]
2561    fn test_clear() {
2562        let mut vec = svec![1, -2, 3];
2563        vec.clear();
2564        assert!(vec.is_empty());
2565        assert_eq!(vec.capacity(), 4);
2566    }
2567    #[test]
2568    fn test_count() {
2569        let mut vec = svec![1, -2, 3, -4];
2570        assert_eq!(vec.count(Sign::Plus), 2);
2571        assert_eq!(vec.count(Sign::Minus), 2);
2572
2573        vec.push(5);
2574        assert_eq!(vec.count(Sign::Plus), 3);
2575        assert_eq!(vec.count(Sign::Minus), 2);
2576    }
2577
2578    #[test]
2579    fn test_dedup() {
2580        // Test deduplication of positive elements
2581        let mut vec = svec![1, 2, 2, -3, -3, 4];
2582        vec.dedup();
2583        assert_eq!(vec.as_slice(), &[1, 2, -3, 4]);
2584
2585        // Test deduplication of negative elements
2586        let mut vec = svec![1, 2, -2, -3, -3, 4];
2587        vec.dedup();
2588        assert_eq!(vec.as_slice(), &[1, 2, -2, -3, 4]);
2589    }
2590
2591    #[test]
2592    fn test_dedup_by() {
2593        // Test deduplication using a custom equality function
2594        let mut vec = svec![10, -5, 10, -5];
2595        vec.dedup_by(|a, b| a == b);
2596        assert_eq!(vec.as_slice(), &[10, -5]);
2597
2598        // Test deduplication of complex objects based on a specific property
2599        let mut vec = svec![
2600            Account::new(100),
2601            Account::new(-50),
2602            Account::new(100),
2603            Account::new(-50),
2604        ];
2605        vec.dedup_by(|a, b| a.balance() == b.balance());
2606        assert_eq!(vec.as_slice().len(), 2);
2607    }
2608
2609    #[test]
2610    fn test_dedup_by_key() {
2611        // Test deduplication based on a derived property
2612        let mut vec = svec![
2613            Account::new(100),
2614            Account::new(100),
2615            Account::new(-50),
2616            Account::new(-50),
2617        ];
2618        vec.dedup_by_key(|a| a.balance());
2619        assert_eq!(vec.as_slice().len(), 2);
2620    }
2621
2622    #[test]
2623    fn test_drain() {
2624        // Test draining a range from the middle
2625        let mut vec = svec![1, 2, 3, 4, 5];
2626        let drained_elements: Vec<_> = vec.drain(1..4).collect();
2627        assert_eq!(drained_elements, vec![2, 3, 4]);
2628        assert_eq!(vec.as_slice(), &[1, 5]);
2629
2630        // Test draining the entire vector
2631        let mut vec = svec![1, 2, 3, 4, 5];
2632        let drained_elements: Vec<_> = vec.drain(..).collect();
2633        assert_eq!(drained_elements, vec![1, 2, 3, 4, 5]);
2634        assert!(vec.is_empty());
2635
2636        // Test draining an empty range
2637        let mut vec = svec![1, 2, 3, 4, 5];
2638        let drained_elements: Vec<_> = vec.drain(5..5).collect();
2639        assert!(drained_elements.is_empty());
2640        assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5]);
2641
2642        // Test draining with excluded end bound
2643        let mut vec = svec![1, 2, 3, 4, 5];
2644        let drained_elements: Vec<_> = vec.drain(..=2).collect();
2645        assert_eq!(drained_elements, vec![1, 2, 3]);
2646        assert_eq!(vec.as_slice(), &[4, 5]);
2647    }
2648    #[test]
2649    fn test_extend_from_slice() {
2650        let mut vec = svec![];
2651        let other = vec![1, 2, 3];
2652        vec.extend_from_slice(&other);
2653        assert_eq!(vec.as_slice(), &[1, 2, 3]);
2654    }
2655
2656    #[test]
2657    fn test_extend_from_within() {
2658        let mut vec = svec![0, 1, 2, 3, 4];
2659        vec.extend_from_within(2..);
2660        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4, 2, 3, 4]);
2661        vec.extend_from_within(5..);
2662        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4, 2, 3, 4, 2, 3, 4]);
2663    }
2664    #[test]
2665    fn test_insert() {
2666        let mut vec = svec![1, 2, 3];
2667        vec.insert(1, 4);
2668        assert_eq!(vec.as_slice(), &[1, 4, 2, 3]);
2669        assert_eq!(vec.count(Sign::Plus), 4);
2670    }
2671
2672    #[test]
2673    fn test_indices() {
2674        let vec = svec![1, -2, 3, -4, 5];
2675        assert_eq!(vec.indices(Sign::Plus), &Set::from(vec![0, 2, 4]));
2676        assert_eq!(vec.indices(Sign::Minus), &Set::from(vec![1, 3]));
2677    }
2678
2679    #[test]
2680    fn test_into_boxed_slice() {
2681        let vec = svec![1, 2, 3];
2682        let boxed_slice: Box<[i32]> = vec.into_boxed_slice();
2683        assert_eq!(&*boxed_slice, &[1, 2, 3]);
2684    }
2685
2686    #[test]
2687    fn test_is_empty() {
2688        let vec = SignVec::<i32>::new();
2689        assert!(vec.is_empty());
2690    }
2691
2692    #[test]
2693    fn test_leak() {
2694        let vec = svec![1, 2, 3];
2695        let leaked_slice = vec.leak();
2696        assert_eq!(leaked_slice, &[1, 2, 3]);
2697    }
2698
2699    #[test]
2700    fn test_len() {
2701        let vec = svec![1, 2, 3];
2702        assert_eq!(vec.len(), 3);
2703    }
2704    #[test]
2705    fn test_new() {
2706        let mut sv: SignVec<i32> = SignVec::new();
2707        let input = vec![1, -2, 3, -4, 5];
2708        input.iter().for_each(|&i| {
2709            sv.push(i);
2710        });
2711        assert_eq!(sv.vals, input);
2712        assert_eq!(sv.as_slice(), &[1, -2, 3, -4, 5]);
2713        assert_eq!(sv.count(Sign::Plus), 3);
2714        assert_eq!(sv.count(Sign::Minus), 2);
2715    }
2716
2717    #[test]
2718    fn test_pop() {
2719        let mut vec = svec![1, 2, -3, 4];
2720        assert_eq!(vec.len(), 4);
2721        assert!(vec.indices(Sign::Plus).contains(&3));
2722        assert_eq!(vec.pop(), Some(4));
2723        assert_eq!(vec.len(), 3);
2724        assert!(!vec.indices(Sign::Plus).contains(&3));
2725        assert_eq!(vec.indices(Sign::Plus), &set![0, 1]);
2726        assert_eq!(vec.indices(Sign::Minus), &set![2]);
2727        assert_eq!(vec.pop(), Some(-3));
2728        assert_eq!(vec.len(), 2);
2729        assert!(!vec.indices(Sign::Minus).contains(&2));
2730        assert_eq!(vec.indices(Sign::Plus), &set![0, 1]);
2731        assert_eq!(vec.indices(Sign::Minus), &set![]);
2732    }
2733    #[test]
2734    fn test_push() {
2735        let mut vec = svec![];
2736        vec.push(1);
2737        vec.push(-2);
2738        vec.push(3);
2739        assert_eq!(vec.as_slice(), &[1, -2, 3]);
2740        assert_eq!(vec.count(Sign::Plus), 2);
2741        assert_eq!(vec.count(Sign::Minus), 1);
2742    }
2743
2744    #[test]
2745    fn test_remove() {
2746        let mut vec = svec![1, -2, 3];
2747        vec.remove(1);
2748        assert_eq!(vec.as_slice(), &[1, 3]);
2749        assert_eq!(vec.count(Sign::Plus), 2);
2750        assert_eq!(vec.count(Sign::Minus), 0);
2751    }
2752    #[test]
2753    fn test_reserve() {
2754        let mut vec = svec![1, -2, 3];
2755        vec.reserve(5);
2756        assert!(vec.capacity() >= 5);
2757    }
2758
2759    #[test]
2760    fn test_reserve_exact() {
2761        let mut vec = svec![1, -2, 3];
2762        vec.reserve_exact(5);
2763        assert!(vec.capacity() >= 8);
2764    }
2765
2766    #[test]
2767    fn test_resize() {
2768        let mut vec = svec![1, -2, 3];
2769        vec.resize(5, 0);
2770        assert_eq!(vec.as_slice(), &[1, -2, 3, 0, 0]);
2771        assert_eq!(vec.count(Sign::Plus), 4);
2772        assert_eq!(vec.count(Sign::Minus), 1);
2773    }
2774
2775    #[test]
2776    fn test_resize_with() {
2777        let mut vec = svec![1, -2, 3];
2778        vec.resize_with(5, || -1);
2779        assert_eq!(vec.as_slice(), &[1, -2, 3, -1, -1]);
2780        assert_eq!(vec.count(Sign::Plus), 2);
2781        assert_eq!(vec.count(Sign::Minus), 3);
2782    }
2783
2784    #[test]
2785    fn test_retain() {
2786        let mut vec = svec![1, -2, 3];
2787        vec.retain(|&x| x > 0);
2788        assert_eq!(vec.as_slice(), &[1, 3]);
2789        assert_eq!(vec.count(Sign::Plus), 2);
2790        assert_eq!(vec.count(Sign::Minus), 0);
2791    }
2792
2793    #[test]
2794    fn test_retain_mut() {
2795        let mut vec = svec![1, -2, 3];
2796        vec.retain_mut(|x| *x > 0);
2797        assert_eq!(vec.as_slice(), &[1, 3]);
2798        assert_eq!(vec.count(Sign::Plus), 2);
2799        assert_eq!(vec.count(Sign::Minus), 0);
2800    }
2801
2802    #[test]
2803    fn test_random() {
2804        let mut svec = svec![1, -1, 2, -2, 3];
2805        let mut rng = WyRand::new();
2806        let mut observed_values = HashSet::new();
2807        for _ in 0..100 {
2808            if let Some(value) = svec.random(Sign::Plus, &mut rng) {
2809                assert!(
2810                    svec.pos.contains(&value),
2811                    "Randomly selected value should be in the set"
2812                );
2813                observed_values.insert(value);
2814            }
2815        }
2816        // Check that multiple distinct values are observed
2817        assert!(
2818            observed_values.len() > 1,
2819            "Random should return different values over multiple calls"
2820        );
2821        // Test with empty set
2822        svec.clear();
2823        assert!(
2824            svec.random(Sign::Minus, &mut rng).is_none(),
2825            "Random should return None for an empty set"
2826        );
2827        assert!(
2828            svec.random(Sign::Plus, &mut rng).is_none(),
2829            "Random should return None for an empty set"
2830        );
2831    }
2832
2833    #[test]
2834    fn test_set_len() {
2835        let mut vec = svec![1, -2, 3];
2836        vec.resize(5, 0); // Reserve extra capacity
2837        unsafe {
2838            vec.set_len(5);
2839        }
2840        assert_eq!(vec.as_slice(), &[1, -2, 3, 0, 0]);
2841        assert_eq!(vec.count(Sign::Plus), 4);
2842        assert_eq!(vec.count(Sign::Minus), 1);
2843
2844        unsafe {
2845            vec.set_len(2);
2846        }
2847        assert_eq!(vec.as_slice(), &[1, -2]);
2848        assert_eq!(vec.count(Sign::Plus), 1);
2849        assert_eq!(vec.count(Sign::Minus), 1);
2850    }
2851
2852    #[test]
2853    #[should_panic(expected = "new_len out of bounds")]
2854    fn test_set_len_out_of_bounds() {
2855        let mut vec = svec![1, -2, 3];
2856        unsafe {
2857            vec.set_len(10);
2858        } // Attempt to set length beyond capacity, should panic
2859    }
2860
2861    #[test]
2862    fn test_set_unchecked() {
2863        let mut vec = svec![1, -2, 3];
2864        assert_eq!(vec.count(Sign::Plus), 2);
2865        assert_eq!(vec.count(Sign::Minus), 1);
2866        unsafe {
2867            vec.set_unchecked(1, 5); // Change -2 to 5
2868        }
2869        assert_eq!(vec.as_slice(), &[1, 5, 3]);
2870        assert_eq!(vec.count(Sign::Plus), 3);
2871        assert_eq!(vec.count(Sign::Minus), 0);
2872    }
2873
2874    #[test]
2875    #[should_panic(expected = "Index out of bounds")]
2876    fn test_set_out_of_bounds() {
2877        let mut vec = svec![1, -2, 3];
2878        vec.set(10, 5); // Attempt to set element at index 10, should panic
2879    }
2880
2881    #[test]
2882    fn test_shrink_to() {
2883        let mut vec = SignVec::<i32>::with_capacity(10);
2884        vec.extend_from_slice(&[1, -2, 3]);
2885        assert!(vec.capacity() >= 10);
2886        vec.shrink_to(5);
2887        assert!(vec.capacity() >= 5);
2888        vec.shrink_to(0);
2889        assert!(vec.capacity() >= 3);
2890    }
2891
2892    #[test]
2893    fn test_shrink_to_fit() {
2894        let mut vec = svec![1, -2, 3];
2895        vec.reserve(10); // Reserve extra capacity
2896        vec.shrink_to_fit();
2897        assert_eq!(vec.capacity(), 3);
2898    }
2899
2900    #[test]
2901    fn test_spare_capacity_mut() {
2902        let mut vec = svec![1, -2, 3];
2903        vec.reserve(10); // Reserve extra capacity
2904        let expected_spare_capacity = vec.capacity() - vec.len();
2905        let spare_capacity = vec.spare_capacity_mut();
2906        assert_eq!(spare_capacity.len(), expected_spare_capacity); // Adjusted expectation
2907    }
2908
2909    #[test]
2910    fn test_split_off() {
2911        let mut vec = svec![1, -2, 3];
2912        vec.push(4);
2913        let new_vec = vec.split_off(2);
2914        assert_eq!(vec.len(), 2);
2915        assert_eq!(new_vec.len(), 2);
2916        assert_eq!(vec.as_slice(), &[1, -2]);
2917        assert_eq!(new_vec.as_slice(), &[3, 4]);
2918    }
2919
2920    #[test]
2921    fn test_swap_remove() {
2922        let mut vec = svec![1, -2, 3];
2923        let removed = vec.swap_remove(1);
2924        assert_eq!(removed, -2);
2925        assert_eq!(vec.len(), 2);
2926        assert_eq!(vec.as_slice(), &[1, 3]);
2927    }
2928
2929    #[test]
2930    fn test_sync() {
2931        let mut vec = svec![1, -2, 3];
2932        vec.remove(1); // Remove an element to make the sync necessary
2933        vec.sync();
2934        assert_eq!(vec.count(Sign::Plus), 2);
2935        assert_eq!(vec.count(Sign::Minus), 0);
2936
2937        let mut vec2 = svec![1, -1, 2];
2938        vec2.vals[0] = -3; // Manually change a value to test sync
2939        vec2.sync();
2940        assert!(vec2.indices(Sign::Plus).contains(&2));
2941        assert!(vec2.indices(Sign::Minus).contains(&0));
2942    }
2943
2944    #[test]
2945    fn test_truncate() {
2946        let mut vec = svec![1, -2, 3];
2947        vec.truncate(2);
2948        assert_eq!(vec.len(), 2);
2949        assert_eq!(vec.as_slice(), &[1, -2]);
2950    }
2951
2952    #[test]
2953    fn test_try_reserve() {
2954        let mut vec = svec![1, -2, 3];
2955        vec.try_reserve(2).unwrap();
2956        assert!(vec.capacity() >= 5); // Original capacity + 2
2957
2958        // Try reserving exact additional capacity
2959        vec.try_reserve_exact(3).unwrap();
2960        assert!(vec.capacity() >= 6); // Original capacity + 3
2961    }
2962
2963    #[test]
2964    fn test_values() {
2965        let vec = svec![1, -2, 3];
2966        assert_eq!(vec.values(Sign::Plus).collect::<Vec<_>>(), vec![&1, &3]);
2967        assert_eq!(vec.values(Sign::Minus).collect::<Vec<_>>(), vec![&-2]);
2968    }
2969
2970    #[test]
2971    fn test_with_capacity() {
2972        let vec = SignVec::<i32>::with_capacity(5);
2973        assert_eq!(vec.capacity(), 5);
2974        assert_eq!(vec.len(), 0);
2975    }
2976
2977    #[test]
2978    fn test_set_and_set_unchecked() {
2979        let mut sign_vec = svec![1, -1, 2];
2980        sign_vec.set(1, 3); // Changing -1 to 3
2981        assert_eq!(sign_vec.vals[1], 3);
2982        // Assertions to ensure `pos` and `neg` are correctly updated
2983    }
2984
2985    #[test]
2986    fn test_len_and_is_empty() {
2987        let vec = SignVec::<i32>::new();
2988        assert_eq!(vec.len(), 0);
2989        assert!(vec.is_empty());
2990
2991        let vec = svec![1, -1];
2992        assert_eq!(vec.len(), 2);
2993        assert!(!vec.is_empty());
2994    }
2995
2996    #[test]
2997    fn test_indices_values_count() {
2998        let vec = svec![1, -1, 2, -2, 3];
2999        assert_eq!(vec.count(Sign::Plus), 3);
3000        assert_eq!(vec.count(Sign::Minus), 2);
3001
3002        let plus_indices: Vec<usize> = vec.indices(Sign::Plus).iter().copied().collect();
3003        assert_eq!(plus_indices, vec![0, 2, 4]);
3004
3005        let minus_values: Vec<&i32> = vec.values(Sign::Minus).collect();
3006        assert_eq!(minus_values, vec![&-1, &-2]);
3007    }
3008
3009    #[test]
3010    fn test_capacity_and_with_capacity() {
3011        let vec = SignVec::<isize>::with_capacity(10);
3012        assert!(vec.capacity() >= 10);
3013    }
3014
3015    #[test]
3016    fn test_reserve_and_reserve_exact() {
3017        let mut vec = svec![1, -1, 2];
3018        vec.reserve(8);
3019        assert!(vec.capacity() >= 10);
3020        vec.reserve_exact(20);
3021        assert!(vec.capacity() >= 20);
3022    }
3023    #[test]
3024    fn test_shrink_to_fit_and_shrink_to() {
3025        let mut vec = SignVec::with_capacity(10);
3026        vec.push(1);
3027        vec.push(-1);
3028        vec.shrink_to_fit();
3029        assert_eq!(vec.capacity(), 2);
3030
3031        vec.shrink_to(10);
3032        assert!(vec.capacity() >= 2);
3033    }
3034    #[test]
3035    fn test_into_boxed_slice_and_truncate() {
3036        let mut vec = svec![1, -1, 2, -2, 3];
3037        vec.truncate(3);
3038        assert_eq!(vec.len(), 3);
3039
3040        let boxed_slice = vec.into_boxed_slice();
3041        assert_eq!(boxed_slice.len(), 3);
3042    }
3043    #[test]
3044    fn test_as_slice_and_as_ptr() {
3045        let vec = svec![1, -1, 2];
3046        let slice = vec.as_slice();
3047        assert_eq!(slice, &[1, -1, 2]);
3048
3049        let ptr = vec.as_ptr();
3050        unsafe {
3051            assert_eq!(*ptr, 1);
3052        }
3053    }
3054    #[test]
3055    fn test_swap_remove_and_remove() {
3056        let mut vec = svec![1, -1, 2];
3057        assert_eq!(vec.swap_remove(1), -1);
3058        assert_eq!(vec.len(), 2);
3059
3060        assert_eq!(vec.remove(0), 1);
3061        assert_eq!(vec.len(), 1);
3062    }
3063    #[test]
3064    fn test_push_and_append() {
3065        let mut vec = svec![1, 2];
3066        vec.push(-1);
3067        assert_eq!(vec.len(), 3);
3068        assert!(vec.indices(Sign::Minus).contains(&2));
3069
3070        let other = vec![3, -2];
3071        vec.append(&other);
3072        assert_eq!(vec.len(), 5);
3073        assert!(vec.indices(Sign::Plus).contains(&3));
3074        assert!(vec.indices(Sign::Minus).contains(&4));
3075    }
3076    #[test]
3077    fn test_insert_and_retain() {
3078        let mut vec = svec![1, 2, 3, 2];
3079        vec.insert(1, -1);
3080        assert_eq!(vec.len(), 5);
3081        assert_eq!(*vec.values(Sign::Minus).next().unwrap(), -1);
3082        assert_eq!(vec.indices(Sign::Plus), &set![0, 2, 3, 4]);
3083        assert_eq!(vec.indices(Sign::Minus), &set![1]);
3084        vec.retain(|&x| x != -1);
3085        assert_eq!(vec.len(), 4);
3086        assert!(!vec.indices(Sign::Minus).contains(&1));
3087        assert_eq!(vec.indices(Sign::Plus), &set![0, 1, 2, 3]);
3088        assert_eq!(vec.indices(Sign::Minus), &set![]);
3089    }
3090
3091    // Helper function to create a SignVec and verify its contents
3092    fn check_signvec_contents(vec: SignVec<i32>, expected_vals: &[i32]) {
3093        assert_eq!(vec.vals, expected_vals);
3094    }
3095
3096    #[test]
3097    fn from_slice() {
3098        let slice: &[i32] = &[1, -2, 3];
3099        let sign_vec = SignVec::from(slice);
3100        check_signvec_contents(sign_vec, slice);
3101    }
3102
3103    #[test]
3104    fn from_array() {
3105        let array: &[i32; 3] = &[1, -2, 3];
3106        let sign_vec = SignVec::from(array);
3107        check_signvec_contents(sign_vec, array);
3108    }
3109
3110    #[test]
3111    fn from_owned_array() {
3112        let array = [1, -2, 3]; // Owned array
3113        let sign_vec = SignVec::from(array);
3114        check_signvec_contents(sign_vec, &array);
3115    }
3116
3117    // Tests for AsRef<Vec<T>> for SignVec<T>
3118    #[test]
3119    fn test_as_ref() {
3120        let sign_vec = SignVec::from(&[1, -2, 3][..]);
3121        assert_eq!(sign_vec.as_ref(), &vec![1, -2, 3]);
3122    }
3123
3124    // Tests for Default for SignVec<T>
3125    #[test]
3126    fn test_default() {
3127        let sign_vec: SignVec<i32> = SignVec::default();
3128        assert!(sign_vec.vals.is_empty());
3129        // Further checks can include testing the default state of pos and neg if applicable.
3130    }
3131
3132    // Tests for Extend<&T> for SignVec<T>
3133    #[test]
3134    fn test_extend_ref() {
3135        let mut sign_vec = SignVec::default();
3136        sign_vec.extend(&[1, -2, 3]);
3137        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3138        // Additional checks can verify the correct state of pos and neg.
3139    }
3140
3141    // Tests for Extend<T> for SignVec<T>
3142    #[test]
3143    fn test_extend_owned() {
3144        let mut sign_vec = SignVec::default();
3145        sign_vec.extend(vec![1, -2, 3]);
3146        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3147        // Additional checks can verify the correct state of pos and neg.
3148    }
3149
3150    // Tests for From<&[T]> for SignVec<T>
3151    #[test]
3152    fn test_from_slice() {
3153        let sign_vec = SignVec::from(&[1, -2, 3][..]);
3154        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3155    }
3156
3157    // Tests for From<&[T; N]> for SignVec<T>
3158    #[test]
3159    fn test_from_array_ref() {
3160        let sign_vec = SignVec::from(&[1, -2, 3]);
3161        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3162    }
3163
3164    // Tests for From<&mut [T]> for SignVec<T>
3165    #[test]
3166    fn test_from_mut_slice() {
3167        let sign_vec = SignVec::from(&mut [1, -2, 3][..]);
3168        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3169    }
3170
3171    // Tests for From<&mut [T; N]> for SignVec<T>
3172    #[test]
3173    fn test_from_mut_array_ref() {
3174        let mut array = [1, -2, 3];
3175        let sign_vec = SignVec::from(&mut array);
3176        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3177    }
3178
3179    // Tests for From<&Vec<T>> for SignVec<T>
3180    #[test]
3181    fn test_from_vec_ref() {
3182        let vec = vec![1, -2, 3];
3183        let sign_vec = SignVec::from(&vec);
3184        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3185    }
3186
3187    // Tests for From<Vec<T>> for SignVec<T>
3188    #[test]
3189    fn test_from_vec() {
3190        let vec = vec![1, -2, 3];
3191        let sign_vec = SignVec::from(vec);
3192        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3193    }
3194
3195    // Tests for From<[T; N]> for SignVec<T>
3196    #[test]
3197    fn test_from_array() {
3198        let array = [1, -2, 3];
3199        let sign_vec = SignVec::from(array);
3200        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
3201    }
3202    // Test FromIterator<T> for SignVec<T>
3203    #[test]
3204    fn from_iterator_owned() {
3205        let items = vec![1, -1, 2, -2];
3206        let sign_vec: SignVec<i32> = items.into_iter().collect();
3207        assert_eq!(sign_vec.vals, vec![1, -1, 2, -2]);
3208        // Additional checks can be added for pos and neg sets.
3209    }
3210
3211    // Test FromIterator<&T> for SignVec<T>
3212    #[test]
3213    fn from_iterator_ref() {
3214        let items = [1, -1, 2, -2];
3215        let sign_vec: SignVec<i32> = items.iter().collect();
3216        assert_eq!(sign_vec.vals, vec![1, -1, 2, -2]);
3217        // Additional checks can be added for pos and neg sets.
3218    }
3219
3220    // Test IntoIterator for SignVec<T> (owned iteration)
3221    #[test]
3222    fn into_iterator_owned() {
3223        let sign_vec = SignVec::from(&[1, -1, 2, -2][..]);
3224        let collected: Vec<i32> = sign_vec.into_iter().collect();
3225        assert_eq!(collected, vec![1, -1, 2, -2]);
3226    }
3227
3228    // Test IntoIterator for &SignVec<T> (immutable reference iteration)
3229    #[test]
3230    fn into_iterator_ref() {
3231        let sign_vec = SignVec::from(&[1, -1, 2, -2][..]);
3232        let collected: Vec<&i32> = (&sign_vec).into_iter().collect();
3233        assert_eq!(collected, vec![&1, &-1, &2, &-2]);
3234    }
3235
3236    // Test IntoIterator for &mut SignVec<T> (mutable reference iteration)
3237    #[test]
3238    fn into_iterator_mut_ref() {
3239        let mut sign_vec = SignVec::from(&[1, -1, 2, -2][..]);
3240        let mut collected: Vec<&mut i32> = (&mut sign_vec).into_iter().collect();
3241        // Perform a mutation as a demonstration.
3242        collected.iter_mut().for_each(|x| **x *= 2);
3243        assert_eq!(sign_vec.vals, vec![2, -2, 4, -4]);
3244    }
3245    // Test for Index trait implementation
3246    #[test]
3247    fn index_test() {
3248        let sv = SignVec::from(vec![1, -2, 3]);
3249        assert_eq!(sv[0], 1);
3250        assert_eq!(sv[1], -2);
3251        assert_eq!(sv[2], 3);
3252    }
3253
3254    // Correction for the Deref test to properly use slicing
3255    #[test]
3256    fn deref_test() {
3257        let sv = SignVec::from(vec![1, -2, 3]);
3258        let slice: &[i32] = &sv; // Directly use Deref to get a slice
3259        assert_eq!(slice, &[1, -2, 3]);
3260    }
3261
3262    // Test for Borrow trait implementation
3263    #[test]
3264    fn borrow_test() {
3265        let sv = SignVec::from(vec![1, -2, 3]);
3266        let slice: &[i32] = sv.borrow();
3267        assert_eq!(slice, &[1, -2, 3]);
3268    }
3269
3270    // Test for Hash trait implementation
3271    #[test]
3272    fn hash_test() {
3273        use std::collections::hash_map::DefaultHasher;
3274        use std::hash::Hasher;
3275
3276        let sv = SignVec::from(vec![1, -2, 3]);
3277        let mut hasher = DefaultHasher::new();
3278        sv.hash(&mut hasher);
3279        let hash = hasher.finish();
3280
3281        let mut hasher_vec = DefaultHasher::new();
3282        vec![1, -2, 3].hash(&mut hasher_vec);
3283        let hash_vec = hasher_vec.finish();
3284
3285        assert_eq!(hash, hash_vec);
3286    }
3287
3288    // Test for Ord and PartialOrd trait implementations
3289    #[test]
3290    fn ord_partial_ord_test() {
3291        let sv1 = SignVec::from(vec![1, 2, 3]);
3292        let sv2 = SignVec::from(vec![1, 2, 4]);
3293        assert!(sv1 < sv2);
3294        assert!(sv2 > sv1);
3295    }
3296
3297    // Test for Eq and PartialEq trait implementations
3298    #[test]
3299    fn eq_partial_eq_test() {
3300        let sv1 = SignVec::from(vec![1, 2, 3]);
3301        let sv2 = SignVec::from(vec![1, 2, 3]);
3302        let sv3 = SignVec::from(vec![1, 2, 4]);
3303        assert_eq!(sv1, sv2);
3304        assert_ne!(sv1, sv3);
3305    }
3306
3307    #[test]
3308    fn partial_eq_with_others_test() {
3309        let sv = SignVec::from(vec![1, 2, 3]);
3310
3311        // When comparing SignVec with a slice, ensure you're passing a reference to the slice,
3312        // not a double reference. The trait implementation expects a single reference.
3313        let slice: &[i32] = &[1, 2, 3];
3314        assert_eq!(sv, slice); // Use sv directly without an additional &, since PartialEq<&[U]> is implemented
3315
3316        // Similarly, for a mutable slice, pass it as a single reference.
3317        let mut_slice: &mut [i32] = &mut [1, 2, 3];
3318        assert_eq!(sv, mut_slice); // Same as above, no double referencing
3319
3320        // For comparing with a Vec<U>, the implementation should already handle it correctly.
3321        assert_eq!(sv, vec![1, 2, 3]); // Direct comparison with Vec<U> is supported
3322    }
3323}