fast_able/
vec2.rs

1use serde::{Deserializer, Serialize, Serializer};
2use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
3use std::cell::UnsafeCell;
4use std::fmt::{Debug, Formatter};
5use std::iter::FusedIterator;
6use std::ops::{Index, IndexMut};
7use std::slice::Iter as SliceIter;
8use std::sync::Arc;
9use std::vec::IntoIter;
10
11// Re-export guard types from guard_common
12// 从 guard_common 重新导出守护类型
13pub use crate::guard_common::{MutRefGuard, ReadGuard, RefGuard, WriteGuard};
14
15/// Synchronous vector supporting fine-grained lock control
16/// 同步向量类型,支持细粒度锁控制,更安全地访问数据
17///
18/// Locking strategy:
19/// - Read operations like `get`: Vec read lock + value read lock
20/// - Value modification operations like `get_mut`: Vec read lock + value write lock
21/// - Structure modification operations like `push`/`remove`: Vec write lock
22/// 锁策略:
23/// - get 等读取操作: Vec读锁 + 值的读锁
24/// - get_mut 等修改值操作: Vec读锁 + 值的写锁
25/// - push/remove 等修改结构操作: Vec写锁
26///
27/// This allows:
28/// - Multiple threads can read different values simultaneously
29/// - When one thread modifies a value, other threads can still read other values
30/// - Exclusive access when modifying the Vec structure
31/// 这样可以实现:
32/// - 多个线程可以同时读取不同的值
33/// - 一个线程修改某个值时,其他线程仍可读取其他值
34/// - 修改Vec结构时独占访问
35pub struct SyncVec<V> {
36    dirty: UnsafeCell<Vec<RwLock<V>>>,
37    lock: RwLock<()>,
38}
39
40/// This is safe, dirty mutex ensures safety
41/// 这是安全的,dirty 互斥锁保证了安全性
42unsafe impl<V> Send for SyncVec<V> {}
43
44/// This is safe, dirty mutex ensures safety
45/// 这是安全的,dirty 互斥锁保证了安全性
46unsafe impl<V> Sync for SyncVec<V> {}
47
48impl<V> Default for SyncVec<V> {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl<V> From<Vec<V>> for SyncVec<V> {
55    fn from(v: Vec<V>) -> Self {
56        Self::with_vec(v)
57    }
58}
59
60impl<V> FromIterator<V> for SyncVec<V> {
61    fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
62        let mut v = Vec::new();
63        for item in iter {
64            v.push(RwLock::new(item));
65        }
66        Self {
67            dirty: UnsafeCell::new(v),
68            lock: RwLock::new(()),
69        }
70    }
71}
72
73impl<V> Extend<V> for SyncVec<V> {
74    fn extend<T: IntoIterator<Item = V>>(&mut self, iter: T) {
75        let v = self.dirty.get_mut();
76        for item in iter {
77            v.push(RwLock::new(item));
78        }
79    }
80}
81
82
83impl<V> SyncVec<V> {
84    pub fn new_arc() -> Arc<Self> {
85        Arc::new(Self::new())
86    }
87
88    pub const fn new() -> Self {
89        Self {
90            dirty: UnsafeCell::new(Vec::new()),
91            lock: RwLock::new(()),
92        }
93    }
94
95    pub fn with_vec(vec: Vec<V>) -> Self {
96        let mut v = Vec::with_capacity(vec.len());
97        for item in vec {
98            v.push(RwLock::new(item));
99        }
100        Self {
101            dirty: UnsafeCell::new(v),
102            lock: RwLock::new(()),
103        }
104    }
105
106    pub fn with_capacity(capacity: usize) -> Self {
107        Self {
108            dirty: UnsafeCell::new(Vec::with_capacity(capacity)),
109            lock: RwLock::new(()),
110        }
111    }
112
113    #[inline(always)]
114    fn as_arr(&self) -> &Vec<RwLock<V>> {
115        unsafe { &*self.dirty.get() }
116    }
117
118    #[inline(always)]
119    fn as_arr_mut(&self) -> &mut Vec<RwLock<V>> {
120        unsafe { &mut *self.dirty.get() }
121    }
122
123    #[inline(always)]
124    pub fn insert(&self, index: usize, v: V) {
125        let _lock = self.lock.write();
126        self.as_arr_mut().insert(index, RwLock::new(v));
127    }
128
129    #[inline(always)]
130    pub fn push(&self, v: V) {
131        let _lock = self.lock.write();
132        self.as_arr_mut().push(RwLock::new(v));
133    }
134
135    #[inline(always)]
136    pub fn push_return(&self, v: V) -> usize {
137        let _lock = self.lock.write();
138        let u = self.as_arr_mut();
139        let index = u.len();
140        u.push(RwLock::new(v));
141        index
142    }
143
144    #[inline(always)]
145    pub fn push_vec(&self, input_arr: Vec<V>) {
146        let mut _lock = self.lock.write();
147        let u = self.as_arr_mut();
148        for ele in input_arr.into_iter() {
149            u.push(RwLock::new(ele));
150        }
151    }
152
153    pub fn pop(&self) -> Option<V> {
154        let _lock = self.lock.write();
155        let u = self.as_arr_mut();
156        u.pop().map(|v| v.into_inner())
157    }
158
159    pub fn remove(&self, index: usize) -> Option<V> {
160        let _lock = self.lock.write();
161        let u = self.as_arr_mut();
162        if u.len() > index {
163            let v = u.remove(index);
164            Some(v.into_inner())
165        } else {
166            None
167        }
168    }
169
170    pub fn len(&self) -> usize {
171        let _lock = self.lock.read();
172        let u = self.as_arr();
173        u.len()
174    }
175
176    pub fn is_empty(&self) -> bool {
177        let _lock = self.lock.read();
178        let u = self.as_arr();
179        u.is_empty()
180    }
181
182    pub fn clear(&self) {
183        let _lock = self.lock.write();
184        let u = self.as_arr_mut();
185        u.clear();
186    }
187
188    pub fn shrink_to_fit(&self) {
189        let _lock = self.lock.write();
190        let u = self.as_arr_mut();
191        u.shrink_to_fit();
192    }
193
194    /// Get a reference to the value at index, protected by Vec read lock (value no lock)
195    /// 获取索引处的值引用,使用Vec读锁 (值无锁)
196    ///
197    /// # Safety
198    /// 此方法绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用它。
199    /// This method bypasses the `RwLock` protecting the value.
200    /// It should only be used when you are sure that no other thread is modifying the value.
201    #[inline]
202    pub fn get(&self, index: usize) -> Option<RefGuard<'_, V>> {
203        let _lock = self.lock.read();
204        let u = self.as_arr();
205        if let Some(v_lock) = u.get(index) {
206            // SAFETY: 只有Vec结构锁保护,值无锁
207            let value_ptr = unsafe {
208                let lock_ptr = v_lock as *const RwLock<V> as *mut RwLock<V>;
209                &*(*lock_ptr).get_mut()
210            };
211            Some(RefGuard {
212                _lock,
213                _value: value_ptr,
214            })
215        } else {
216            None
217        }
218    }
219
220    /// Get a reference to the value at index (unchecked), protected by Vec read lock (value no lock)
221    /// 获取索引处的值引用(无检查),使用Vec读锁 (值无锁)
222    ///
223    /// # Safety
224    /// 此方法绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用它。
225    /// This method bypasses the `RwLock` protecting the value.
226    /// It should only be used when you are sure that no other thread is modifying the value.
227    #[inline]
228    pub fn get_uncheck(&self, index: usize) -> RefGuard<'_, V> {
229        let _lock = self.lock.read();
230        let u = self.as_arr();
231        let v_lock = &u[index];
232        // SAFETY: 只有Vec结构锁保护,值无锁
233        let value_ptr = unsafe {
234            let lock_ptr = v_lock as *const RwLock<V> as *mut RwLock<V>;
235            &*(*lock_ptr).get_mut()
236        };
237        RefGuard {
238            _lock,
239            _value: value_ptr,
240        }
241    }
242
243    /// Get a reference to the value at index, protected by Vec read lock + value read lock
244    /// 获取索引处的值引用,使用Vec读锁 + 值的读锁保护
245    #[inline]
246    pub fn get_rlock(&self, index: usize) -> Option<ReadGuard<'_, V>> {
247        let _lock = self.lock.read();
248        let u = self.as_arr();
249        if let Some(v_lock) = u.get(index) {
250            let _value_lock = v_lock.read();
251            Some(ReadGuard { _lock, _value_lock })
252        } else {
253            None
254        }
255    }
256
257    /// Get a mutable reference to the value at index, protected by Vec read lock + value write lock
258    /// 获取索引处的可变值引用,使用Vec读锁 + 值的写锁保护
259    #[inline]
260    pub fn get_mut_lock(&self, index: usize) -> Option<WriteGuard<'_, V>> {
261        let _lock = self.lock.read();
262        let u = self.as_arr();
263        if let Some(v_lock) = u.get(index) {
264            let _value_lock = v_lock.write();
265            Some(WriteGuard { _lock, _value_lock })
266        } else {
267            None
268        }
269    }
270
271    /// Get a mutable reference to the value at index, protected by Vec read lock (value no lock)
272    /// 获取索引处的可变值引用,使用Vec读锁 (值无锁)
273    #[inline]
274    pub fn get_mut(&self, index: usize) -> Option<MutRefGuard<'_, V>> {
275        let _lock = self.lock.read();
276        let u = self.as_arr();
277        if let Some(v_lock) = u.get(index) {
278            let value_ptr = unsafe {
279                let lock_ptr = v_lock as *const RwLock<V> as *mut RwLock<V>;
280                &mut *(*lock_ptr).get_mut()
281            };
282            Some(MutRefGuard {
283                _lock,
284                _value: value_ptr,
285            })
286        } else {
287            None
288        }
289    }
290
291    #[inline]
292    pub fn contains(&self, x: &V) -> bool
293    where
294        V: PartialEq,
295    {
296        let _lock = self.lock.read();
297        let u = self.as_arr();
298        for item in u {
299            if *item.read() == *x {
300                return true;
301            }
302        }
303        false
304    }
305
306    /// Safety; Get an iterator over the values, protected by Vec read lock + individual value read locks
307    /// 安全地访问每个数据,获取迭代器,使用Vec读锁 + 各个值的读锁保护
308    pub fn iter_rlock(&self) -> IterRLock<'_, V> {
309        let _lock = self.lock.read();
310        let u = self.as_arr();
311        IterRLock {
312            _lock,
313            inner: u.iter(),
314        }
315    }
316
317    /// 不锁值,只锁Vec结构,适用于只读但不修改值的场景
318    ///
319    /// # Safety
320    /// 此方法是不安全的,因为它绕过了保护每个值的 `RwLock`。
321    /// 仅当您确定没有其他线程正在修改这些值时才应使用它。
322    ///
323    /// This method is unsafe because it bypasses the `RwLock` protecting each value.
324    /// It should only be used when you are sure that no other thread is modifying the values.
325    pub fn iter(&self) -> Iter<'_, V> {
326        let _lock = self.lock.read();
327        let u = self.as_arr();
328        Iter {
329            _lock,
330            inner: u.iter(),
331        }
332    }
333
334    /// Get a mutable iterator over the values, protected by Vec read lock + individual value write locks
335    /// 获取可变迭代器,使用Vec读锁 + 各个值的写锁保护
336    pub fn iter_mut_lock(&self) -> IterLock<'_, V> {
337        let _lock = self.lock.read();
338        let u = self.as_arr();
339        IterLock {
340            _lock,
341            inner: u.iter(),
342        }
343    }
344
345    /// Get a mutable iterator over the values, protected by Vec read lock (value no lock)
346    /// 获取可变迭代器,使用Vec读锁 (值无锁)
347    ///
348    /// # Safety
349    /// 此方法绕过了保护每个值的 `RwLock`。
350    /// 仅当您确定没有其他线程正在修改这些值时才应使用它。
351    ///
352    /// This method bypasses the `RwLock` protecting each value.
353    /// It should only be used when you are sure that no other thread is modifying the values.
354    pub fn iter_mut(&self) -> IterMut<'_, V> {
355        let _lock = self.lock.read();
356        let u = self.as_arr();
357        IterMut {
358            _lock,
359            inner: u.iter(),
360        }
361    }
362
363    pub fn into_iter(self) -> IntoIter<V> {
364        let _lock = self.lock.write();
365        let m = self.dirty.into_inner();
366        let mut v = Vec::with_capacity(m.len());
367        for item in m {
368            v.push(item.into_inner());
369        }
370        v.into_iter()
371    }
372
373    pub fn dirty_ref(&self) -> RefGuard<'_, Vec<RwLock<V>>> {
374        RefGuard {
375            _lock: self.lock.read(),
376            _value: self.as_arr(),
377        }
378    }
379
380    pub fn into_inner(self) -> Vec<V> {
381        let m = self.dirty.into_inner();
382        let mut v = Vec::with_capacity(m.len());
383        for item in m {
384            v.push(item.into_inner());
385        }
386        v
387    }
388
389    pub fn to_vec(&self) -> Vec<V>
390    where
391        V: Clone,
392    {
393        let _lock = self.lock.read();
394        let u = self.as_arr();
395        let mut v = Vec::with_capacity(u.len());
396        for item in u {
397            v.push(item.read().clone());
398        }
399        v
400    }
401}
402
403pub struct IterRLock<'a, V> {
404    pub(crate) _lock: RwLockReadGuard<'a, ()>,
405    pub(crate) inner: SliceIter<'a, RwLock<V>>,
406}
407
408impl<'a, V> Iterator for IterRLock<'a, V> {
409    type Item = RwLockReadGuard<'a, V>;
410    fn next(&mut self) -> Option<Self::Item> {
411        self.inner.next().map(|v| v.read())
412    }
413}
414
415impl<'a, V> ExactSizeIterator for IterRLock<'a, V> {
416    fn len(&self) -> usize {
417        self.inner.len()
418    }
419}
420
421impl<'a, V> DoubleEndedIterator for IterRLock<'a, V> {
422    fn next_back(&mut self) -> Option<Self::Item> {
423        self.inner.next_back().map(|v| v.read())
424    }
425}
426
427impl<'a, V> FusedIterator for IterRLock<'a, V> {}
428
429pub struct IterLock<'a, V> {
430    pub(crate) _lock: RwLockReadGuard<'a, ()>,
431    pub(crate) inner: SliceIter<'a, RwLock<V>>,
432}
433
434impl<'a, V> Iterator for IterLock<'a, V> {
435    type Item = RwLockWriteGuard<'a, V>;
436
437    fn next(&mut self) -> Option<Self::Item> {
438        self.inner.next().map(|v| v.write())
439    }
440}
441
442impl<'a, V> ExactSizeIterator for IterLock<'a, V> {
443    fn len(&self) -> usize {
444        self.inner.len()
445    }
446}
447
448impl<'a, V> DoubleEndedIterator for IterLock<'a, V> {
449    fn next_back(&mut self) -> Option<Self::Item> {
450        self.inner.next_back().map(|v| v.write())
451    }
452}
453
454impl<'a, V> FusedIterator for IterLock<'a, V> {}
455
456/// 不锁值的迭代器,只锁Vec结构
457/// Iterator that only locks Vec structure, not individual values
458pub struct Iter<'a, V> {
459    pub(crate) _lock: RwLockReadGuard<'a, ()>,
460    pub(crate) inner: SliceIter<'a, RwLock<V>>,
461}
462
463impl<'a, V> Iterator for Iter<'a, V> {
464    type Item = &'a V;
465
466    fn next(&mut self) -> Option<Self::Item> {
467        self.inner.next().map(|v| {
468            // SAFETY: 调用者通过使用 unsafe fn iter 保证没有并发写入
469            unsafe {
470                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
471                &*(*lock_ptr).get_mut()
472            }
473        })
474    }
475}
476
477impl<'a, V> ExactSizeIterator for Iter<'a, V> {
478    fn len(&self) -> usize {
479        self.inner.len()
480    }
481}
482
483impl<'a, V> DoubleEndedIterator for Iter<'a, V> {
484    fn next_back(&mut self) -> Option<Self::Item> {
485        self.inner.next_back().map(|v| {
486            // SAFETY: 调用者通过使用 unsafe fn iter 保证没有并发写入
487            unsafe {
488                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
489                &*(*lock_ptr).get_mut()
490            }
491        })
492    }
493}
494
495impl<'a, V> FusedIterator for Iter<'a, V> {}
496
497/// 不锁值的可变迭代器,只锁Vec结构
498/// Mutable iterator that only locks Vec structure, not individual values
499pub struct IterMut<'a, V> {
500    pub(crate) _lock: RwLockReadGuard<'a, ()>,
501    pub(crate) inner: SliceIter<'a, RwLock<V>>,
502}
503
504impl<'a, V> Iterator for IterMut<'a, V> {
505    type Item = &'a mut V;
506
507    fn next(&mut self) -> Option<Self::Item> {
508        self.inner.next().map(|v| {
509            // SAFETY: 调用者通过使用此方法保证没有并发写入
510            unsafe {
511                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
512                &mut *(*lock_ptr).get_mut()
513            }
514        })
515    }
516}
517
518impl<'a, V> ExactSizeIterator for IterMut<'a, V> {
519    fn len(&self) -> usize {
520        self.inner.len()
521    }
522}
523
524impl<'a, V> DoubleEndedIterator for IterMut<'a, V> {
525    fn next_back(&mut self) -> Option<Self::Item> {
526        self.inner.next_back().map(|v| {
527            // SAFETY: 调用者通过使用此方法保证没有并发写入
528            unsafe {
529                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
530                &mut *(*lock_ptr).get_mut()
531            }
532        })
533    }
534}
535
536impl<'a, V> FusedIterator for IterMut<'a, V> {}
537
538impl<'a, V> IntoIterator for &'a SyncVec<V> {
539    type Item = &'a V;
540    type IntoIter = Iter<'a, V>;
541
542    fn into_iter(self) -> Self::IntoIter {
543        self.iter()
544    }
545}
546
547impl<'a, V> IntoIterator for &'a mut SyncVec<V> {
548    type Item = &'a mut V;
549    type IntoIter = IterMut<'a, V>;
550
551    fn into_iter(self) -> Self::IntoIter {
552        self.iter_mut()
553    }
554}
555
556impl<V> IntoIterator for SyncVec<V> {
557    type Item = V;
558    type IntoIter = IntoIter<V>;
559
560    fn into_iter(self) -> Self::IntoIter {
561        self.into_iter()
562    }
563}
564
565impl<V> Serialize for SyncVec<V>
566where
567    V: Serialize,
568{
569    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
570    where
571        S: Serializer,
572    {
573        use serde::ser::SerializeSeq;
574        let _lock = self.lock.read();
575        let v = unsafe { &*self.dirty.get() };
576        let mut seq = serializer.serialize_seq(Some(v.len()))?;
577        for element in v {
578            seq.serialize_element(&*element.read())?;
579        }
580        seq.end()
581    }
582}
583
584impl<'de, V> serde::Deserialize<'de> for SyncVec<V>
585where
586    V: serde::Deserialize<'de>,
587{
588    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
589    where
590        D: Deserializer<'de>,
591    {
592        let m = Vec::deserialize(deserializer)?;
593        Ok(Self::from(m))
594    }
595}
596
597impl<V> Debug for SyncVec<V>
598where
599    V: Debug,
600{
601    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
602        write!(f, "{:?}", self.dirty_ref())
603    }
604}
605
606impl<V: std::fmt::Display> std::fmt::Display for SyncVec<V> {
607    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
608        let _lock = self.lock.read();
609        let v = unsafe { &*self.dirty.get() };
610        write!(f, "[")?;
611        for (i, item) in v.iter().enumerate() {
612            if i > 0 {
613                write!(f, ", ")?;
614            }
615            write!(f, "{}", item.read())?;
616        }
617        write!(f, "]")
618    }
619}
620
621impl<V: PartialEq> PartialEq for SyncVec<V> {
622    fn eq(&self, other: &Self) -> bool {
623        let _lock1 = self.lock.read();
624        let _lock2 = other.lock.read();
625        let v1 = unsafe { &*self.dirty.get() };
626        let v2 = unsafe { &*other.dirty.get() };
627        if v1.len() != v2.len() {
628            return false;
629        }
630        for (i1, i2) in v1.iter().zip(v2.iter()) {
631            if *i1.read() != *i2.read() {
632                return false;
633            }
634        }
635        true
636    }
637}
638
639impl<V: Clone> Clone for SyncVec<V> {
640    fn clone(&self) -> Self {
641        let _lock = self.lock.read();
642        let v = unsafe { &*self.dirty.get() };
643        let mut new_vec = Vec::with_capacity(v.len());
644        for item in v {
645            new_vec.push(RwLock::new(item.read().clone()));
646        }
647        Self {
648            dirty: UnsafeCell::new(new_vec),
649            lock: RwLock::new(()),
650        }
651    }
652}
653
654impl<V> Index<usize> for SyncVec<V> {
655    type Output = V;
656
657    /// Get a reference to the value at index, bypassing the lock.
658    /// 获取索引处的值引用,绕过锁。
659    ///
660    /// # Safety
661    /// This method is unsafe because it bypasses the `RwLock` protecting the value.
662    /// It should only be used when you are sure that no other thread is modifying the value.
663    /// Concurrent access using this method is undefined behavior.
664    ///
665    /// # 安全性
666    /// 此方法是不安全的,因为它绕过了保护值的 `RwLock`。
667    /// 仅当您确定没有其他线程正在修改该值时才应使用它。
668    /// 使用此方法进行并发访问是未定义行为。
669    fn index(&self, index: usize) -> &Self::Output {
670        unsafe {
671            let v = &*self.dirty.get();
672            // We need to get &V from &RwLock<V> without locking.
673            // Since we are in an unsafe block and claiming it's unsafe/no concurrent access,
674            // we can cast the &RwLock<V> to &mut RwLock<V> (conceptually) to use get_mut(),
675            // or rely on the fact that we are bypassing the lock.
676            // However, RwLock::get_mut requires &mut RwLock.
677            // We only have &RwLock.
678            // We can cast &RwLock to &mut RwLock because we are asserting exclusive access (via the safety contract).
679            let lock_ptr = &v[index] as *const RwLock<V> as *mut RwLock<V>;
680            (*lock_ptr).get_mut()
681        }
682    }
683}
684
685impl<V> IndexMut<usize> for SyncVec<V> {
686    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
687        // This is unsafe because we are bypassing the `RwLock` protecting the value.
688        // 这是不安全的,因为我们绕过了保护值的 `RwLock`。
689        let v = self.dirty.get_mut();
690        v[index].get_mut()
691    }
692}
693
694#[macro_export]
695macro_rules! sync_vec {
696    () => (
697        $crate::SyncVec::new()
698    );
699    ($elem:expr; $n:expr) => (
700        $crate::SyncVec::with_vec(vec![$elem;$n])
701    );
702    ($($x:expr),+ $(,)?) => (
703        $crate::SyncVec::with_vec(vec![$($x),+,])
704    );
705}
706
707#[test]
708fn test_case() {
709    struct D {}
710    impl D {
711        fn is_some(&self) -> bool {
712            println!("is_some");
713            true
714        }
715        fn take(&mut self) -> Option<bool> {
716            println!("take");
717            Some(true)
718        }
719    }
720
721    let mut d = D {};
722    if let (true, Some(d)) = (d.is_some(), d.take()) {
723        println!("d is {d}");
724    }
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730    use std::sync::Arc;
731    use std::thread;
732
733    #[test]
734    fn test_new_and_capacity() {
735        let vec: SyncVec<i32> = SyncVec::new();
736        assert!(vec.is_empty());
737        assert_eq!(vec.len(), 0);
738
739        let vec: SyncVec<i32> = SyncVec::with_capacity(10);
740        assert!(vec.is_empty());
741        assert_eq!(vec.len(), 0);
742    }
743
744    #[test]
745    fn test_push_and_get() {
746        let vec = SyncVec::new();
747        vec.push(1);
748        vec.push(2);
749        vec.push(3);
750
751        assert_eq!(vec.len(), 3);
752        assert_eq!(*vec.get(0).unwrap(), 1);
753        assert_eq!(*vec.get(1).unwrap(), 2);
754        assert_eq!(*vec.get(2).unwrap(), 3);
755        assert!(vec.get(3).is_none());
756    }
757
758    #[test]
759    fn test_index_methods() {
760        let mut vec = SyncVec::new();
761        vec.push(10);
762        vec.push(20);
763
764        assert_eq!(vec[0], 10);
765        assert_eq!(vec[1], 20);
766
767        {
768            let val = &mut vec[0];
769            *val = 100;
770        }
771        assert_eq!(vec[0], 100);
772    }
773
774    #[test]
775    #[should_panic(expected = "index out of bounds")]
776    fn test_index_panic() {
777        let vec = SyncVec::new();
778        vec.push(1);
779        let _ = vec[1];
780    }
781
782    #[test]
783    #[should_panic(expected = "index out of bounds")]
784    fn test_index_mut_panic() {
785        let mut vec = SyncVec::new();
786        vec.push(1);
787        let _ = &mut vec[1];
788    }
789
790    #[test]
791    fn test_remove_and_pop() {
792        let vec = SyncVec::new();
793        vec.push(1);
794        vec.push(2);
795        vec.push(3);
796
797        assert_eq!(vec.pop(), Some(3));
798        assert_eq!(vec.len(), 2);
799
800        assert_eq!(vec.remove(0), Some(1));
801        assert_eq!(vec.len(), 1);
802        assert_eq!(*vec.get(0).unwrap(), 2);
803    }
804
805    #[test]
806    fn test_concurrency() {
807        let vec = Arc::new(SyncVec::new());
808        let mut handles = vec![];
809
810        // Multiple writers
811        for i in 0..10 {
812            let vec = vec.clone();
813            handles.push(thread::spawn(move || {
814                for j in 0..100 {
815                    vec.push(i * 100 + j);
816                }
817            }));
818        }
819
820        for handle in handles {
821            handle.join().unwrap();
822        }
823
824        assert_eq!(vec.len(), 1000);
825    }
826
827    #[test]
828    fn test_concurrent_modify() {
829        let vec = Arc::new(SyncVec::new());
830        for i in 0..100 {
831            vec.push(i);
832        }
833
834        let vec_clone = vec.clone();
835        let handle = thread::spawn(move || {
836            for i in 0..100 {
837                if let Some(mut guard) = vec_clone.get_mut(i) {
838                    *guard += 1;
839                }
840            }
841        });
842
843        // Concurrent read
844        for i in 0..100 {
845            if let Some(val) = vec.get(i) {
846                let _ = *val; // Just read
847            }
848        }
849
850        handle.join().unwrap();
851
852        // Verify modifications
853        for i in 0..100 {
854            assert_eq!(*vec.get(i).unwrap(), i + 1);
855        }
856    }
857
858    #[test]
859    fn test_iter() {
860        let vec = SyncVec::new();
861        vec.push(1);
862        vec.push(2);
863        vec.push(3);
864
865        let mut sum = 0;
866        for item in vec.iter() {
867            sum += *item;
868        }
869        assert_eq!(sum, 6);
870    }
871
872    #[test]
873    fn test_iter_mut() {
874        let vec = SyncVec::new();
875        vec.push(1);
876        vec.push(2);
877        vec.push(3);
878
879        for mut item in vec.iter_mut() {
880            *item *= 2;
881        }
882
883        assert_eq!(*vec.get(0).unwrap(), 2);
884        assert_eq!(*vec.get(1).unwrap(), 4);
885        assert_eq!(*vec.get(2).unwrap(), 6);
886    }
887
888    #[test]
889    fn test_clear() {
890        let vec = SyncVec::new();
891        vec.push(1);
892        vec.clear();
893        assert!(vec.is_empty());
894    }
895
896    #[test]
897    fn test_contains() {
898        let vec = SyncVec::new();
899        vec.push(1);
900        vec.push(2);
901        assert!(vec.contains(&1));
902        assert!(!vec.contains(&3));
903    }
904
905    #[test]
906    fn test_iterator_traits() {
907        let vec = SyncVec::new();
908        vec.push(1);
909        vec.push(2);
910        vec.push(3);
911
912        let mut iter = vec.iter();
913        assert_eq!(iter.len(), 3);
914        assert_eq!(*iter.next().unwrap(), 1);
915        assert_eq!(iter.len(), 2);
916        assert_eq!(*iter.next_back().unwrap(), 3);
917        assert_eq!(iter.len(), 1);
918        assert_eq!(*iter.next().unwrap(), 2);
919        assert_eq!(iter.len(), 0);
920        assert!(iter.next().is_none());
921        assert!(iter.next_back().is_none());
922
923        let mut vec = SyncVec::new();
924        vec.push(1);
925        vec.push(2);
926        vec.push(3);
927        let mut iter_mut = vec.iter_mut();
928        assert_eq!(iter_mut.len(), 3);
929        assert_eq!(*iter_mut.next().unwrap(), 1);
930        assert_eq!(iter_mut.len(), 2);
931        assert_eq!(*iter_mut.next_back().unwrap(), 3);
932        assert_eq!(iter_mut.len(), 1);
933        assert_eq!(*iter_mut.next().unwrap(), 2);
934        assert_eq!(iter_mut.len(), 0);
935        assert!(iter_mut.next().is_none());
936        assert!(iter_mut.next_back().is_none());
937    }
938
939    #[test]
940    fn test_from_iter_and_extend() {
941        let vec: SyncVec<i32> = SyncVec::from_iter(vec![1, 2, 3]);
942        assert_eq!(vec.len(), 3);
943        assert_eq!(*vec.get(0).unwrap(), 1);
944
945        let mut vec = SyncVec::new();
946        vec.extend(vec![1, 2, 3]);
947        assert_eq!(vec.len(), 3);
948        assert_eq!(*vec.get(0).unwrap(), 1);
949    }
950
951    #[test]
952    fn test_iter_notlock() {
953        let vec = SyncVec::new();
954        vec.push(1);
955        vec.push(2);
956        vec.push(3);
957
958        // 测试 iter 基本功能
959        let mut sum = 0;
960        for item in vec.iter() {
961            sum += *item;
962        }
963        assert_eq!(sum, 6);
964
965        // 测试 ExactSizeIterator
966        let iter = vec.iter();
967        assert_eq!(iter.len(), 3);
968    }
969
970    #[test]
971    fn test_iter_double_ended() {
972        let vec = SyncVec::new();
973        vec.push(1);
974        vec.push(2);
975        vec.push(3);
976
977        let mut iter = vec.iter();
978        assert_eq!(*iter.next().unwrap(), 1);
979        assert_eq!(*iter.next_back().unwrap(), 3);
980        assert_eq!(*iter.next().unwrap(), 2);
981        assert!(iter.next().is_none());
982    }
983
984    #[test]
985    fn test_iter_empty() {
986        let vec: SyncVec<i32> = SyncVec::new();
987
988        let mut count = 0;
989        for _ in vec.iter() {
990            count += 1;
991        }
992        assert_eq!(count, 0);
993
994        let iter = vec.iter();
995        assert_eq!(iter.len(), 0);
996    }
997
998    #[test]
999    fn test_into_iter_ref() {
1000        let vec = SyncVec::new();
1001        vec.push(10);
1002        vec.push(20);
1003        vec.push(30);
1004
1005        // 测试 IntoIterator for &SyncVec
1006        let mut sum = 0;
1007        for item in &vec {
1008            sum += *item;
1009        }
1010        assert_eq!(sum, 60);
1011
1012        // 确保 vec 仍然可用
1013        assert_eq!(vec.len(), 3);
1014    }
1015
1016    #[test]
1017    fn test_into_iter_mut() {
1018        let mut vec = SyncVec::new();
1019        vec.push(1);
1020        vec.push(2);
1021        vec.push(3);
1022
1023        // 测试 IntoIterator for &mut SyncVec
1024        for mut item in &mut vec {
1025            *item *= 2;
1026        }
1027
1028        assert_eq!(*vec.get(0).unwrap(), 2);
1029        assert_eq!(*vec.get(1).unwrap(), 4);
1030        assert_eq!(*vec.get(2).unwrap(), 6);
1031    }
1032
1033    #[test]
1034    fn test_into_iter_owned() {
1035        let vec = SyncVec::new();
1036        vec.push(1);
1037        vec.push(2);
1038        vec.push(3);
1039
1040        // 测试 IntoIterator for SyncVec (消耗所有权)
1041        let collected: Vec<_> = vec.into_iter().collect();
1042        assert_eq!(collected, vec![1, 2, 3]);
1043    }
1044}