fast-able 1.20.2

The world's martial arts are fast and unbreakable; 天下武功 唯快不破
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
use serde::{Deserializer, Serialize, Serializer};
use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::cell::UnsafeCell;
use std::fmt::{Debug, Formatter};
use std::iter::FusedIterator;
use std::ops::{Index, IndexMut};
use std::slice::Iter as SliceIter;
use std::sync::Arc;
use std::vec::IntoIter;

// Re-export guard types from guard_common
// 从 guard_common 重新导出守护类型
pub use crate::guard_common::{MutRefGuard, ReadGuard, RefGuard, WriteGuard};

/// Synchronous vector supporting fine-grained lock control
/// 同步向量类型,支持细粒度锁控制,更安全地访问数据
///
/// Locking strategy:
/// - Read operations like `get`: Vec read lock + value read lock
/// - Value modification operations like `get_mut`: Vec read lock + value write lock
/// - Structure modification operations like `push`/`remove`: Vec write lock
/// 锁策略:
/// - get 等读取操作: Vec读锁 + 值的读锁
/// - get_mut 等修改值操作: Vec读锁 + 值的写锁
/// - push/remove 等修改结构操作: Vec写锁
///
/// This allows:
/// - Multiple threads can read different values simultaneously
/// - When one thread modifies a value, other threads can still read other values
/// - Exclusive access when modifying the Vec structure
/// 这样可以实现:
/// - 多个线程可以同时读取不同的值
/// - 一个线程修改某个值时,其他线程仍可读取其他值
/// - 修改Vec结构时独占访问
pub struct SyncVec<V> {
    dirty: UnsafeCell<Vec<RwLock<V>>>,
    lock: RwLock<()>,
}

/// This is safe, dirty mutex ensures safety
/// 这是安全的,dirty 互斥锁保证了安全性
unsafe impl<V> Send for SyncVec<V> {}

/// This is safe, dirty mutex ensures safety
/// 这是安全的,dirty 互斥锁保证了安全性
unsafe impl<V> Sync for SyncVec<V> {}

impl<V> Default for SyncVec<V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V> From<Vec<V>> for SyncVec<V> {
    fn from(v: Vec<V>) -> Self {
        Self::with_vec(v)
    }
}

impl<V> FromIterator<V> for SyncVec<V> {
    fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
        let mut v = Vec::new();
        for item in iter {
            v.push(RwLock::new(item));
        }
        Self {
            dirty: UnsafeCell::new(v),
            lock: RwLock::new(()),
        }
    }
}

impl<V> Extend<V> for SyncVec<V> {
    fn extend<T: IntoIterator<Item = V>>(&mut self, iter: T) {
        let v = self.dirty.get_mut();
        for item in iter {
            v.push(RwLock::new(item));
        }
    }
}

impl<V> SyncVec<V> {
    pub fn new_arc() -> Arc<Self> {
        Arc::new(Self::new())
    }

    pub const fn new() -> Self {
        Self {
            dirty: UnsafeCell::new(Vec::new()),
            lock: RwLock::new(()),
        }
    }

    pub fn with_vec(vec: Vec<V>) -> Self {
        let mut v = Vec::with_capacity(vec.len());
        for item in vec {
            v.push(RwLock::new(item));
        }
        Self {
            dirty: UnsafeCell::new(v),
            lock: RwLock::new(()),
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            dirty: UnsafeCell::new(Vec::with_capacity(capacity)),
            lock: RwLock::new(()),
        }
    }

    #[inline(always)]
    fn as_arr(&self) -> &Vec<RwLock<V>> {
        unsafe { &*self.dirty.get() }
    }

    #[inline(always)]
    fn as_arr_mut(&self) -> &mut Vec<RwLock<V>> {
        unsafe { &mut *self.dirty.get() }
    }

    #[inline(always)]
    pub fn insert(&self, index: usize, v: V) {
        let _lock = self.lock.write();
        self.as_arr_mut().insert(index, RwLock::new(v));
    }

    #[inline(always)]
    pub fn push(&self, v: V) {
        let _lock = self.lock.write();
        self.as_arr_mut().push(RwLock::new(v));
    }

    #[inline(always)]
    pub fn push_return(&self, v: V) -> usize {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        let index = u.len();
        u.push(RwLock::new(v));
        index
    }

    #[inline(always)]
    pub fn push_vec(&self, input_arr: Vec<V>) {
        let mut _lock = self.lock.write();
        let u = self.as_arr_mut();
        for ele in input_arr.into_iter() {
            u.push(RwLock::new(ele));
        }
    }

    pub fn pop(&self) -> Option<V> {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        u.pop().map(|v| v.into_inner())
    }

    pub fn remove(&self, index: usize) -> Option<V> {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        if u.len() > index {
            let v = u.remove(index);
            Some(v.into_inner())
        } else {
            None
        }
    }

    pub fn len(&self) -> usize {
        let _lock = self.lock.read();
        let u = self.as_arr();
        u.len()
    }

    pub fn is_empty(&self) -> bool {
        let _lock = self.lock.read();
        let u = self.as_arr();
        u.is_empty()
    }

    pub fn clear(&self) {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        u.clear();
    }

    pub fn shrink_to_fit(&self) {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        u.shrink_to_fit();
    }

    /// Get a reference to the value at index, protected by Vec read lock (value no lock)
    /// 获取索引处的值引用,使用Vec读锁 (值无锁)
    ///
    /// # Safety
    /// 此方法绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用它。
    /// This method bypasses the `RwLock` protecting the value.
    /// It should only be used when you are sure that no other thread is modifying the value.
    #[inline]
    pub fn get(&self, index: usize) -> Option<RefGuard<'_, V>> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        if let Some(v_lock) = u.get(index) {
            // SAFETY: 只有Vec结构锁保护,值无锁
            let value_ptr = unsafe {
                let lock_ptr = v_lock as *const RwLock<V> as *mut RwLock<V>;
                &*(*lock_ptr).get_mut()
            };
            Some(RefGuard {
                _lock,
                _value: value_ptr,
            })
        } else {
            None
        }
    }

    /// Get a reference to the value at index (unchecked), protected by Vec read lock (value no lock)
    /// 获取索引处的值引用(无检查),使用Vec读锁 (值无锁)
    ///
    /// # Safety
    /// 此方法绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用它。
    /// This method bypasses the `RwLock` protecting the value.
    /// It should only be used when you are sure that no other thread is modifying the value.
    #[inline]
    pub fn get_uncheck(&self, index: usize) -> RefGuard<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        let v_lock = &u[index];
        // SAFETY: 只有Vec结构锁保护,值无锁
        let value_ptr = unsafe {
            let lock_ptr = v_lock as *const RwLock<V> as *mut RwLock<V>;
            &*(*lock_ptr).get_mut()
        };
        RefGuard {
            _lock,
            _value: value_ptr,
        }
    }

    /// Get a reference to the value at index, protected by Vec read lock + value read lock
    /// 获取索引处的值引用,使用Vec读锁 + 值的读锁保护
    #[inline]
    pub fn get_rlock(&self, index: usize) -> Option<ReadGuard<'_, V>> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        if let Some(v_lock) = u.get(index) {
            let _value_lock = v_lock.read();
            Some(ReadGuard { _lock, _value_lock })
        } else {
            None
        }
    }

    /// Get a mutable reference to the value at index, protected by Vec read lock + value write lock
    /// 获取索引处的可变值引用,使用Vec读锁 + 值的写锁保护
    #[inline]
    pub fn get_mut_lock(&self, index: usize) -> Option<WriteGuard<'_, V>> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        if let Some(v_lock) = u.get(index) {
            let _value_lock = v_lock.write();
            Some(WriteGuard { _lock, _value_lock })
        } else {
            None
        }
    }

    /// Get a mutable reference to the value at index, protected by Vec read lock (value no lock)
    /// 获取索引处的可变值引用,使用Vec读锁 (值无锁)
    #[inline]
    pub fn get_mut(&self, index: usize) -> Option<MutRefGuard<'_, V>> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        if let Some(v_lock) = u.get(index) {
            let value_ptr = unsafe {
                let lock_ptr = v_lock as *const RwLock<V> as *mut RwLock<V>;
                &mut *(*lock_ptr).get_mut()
            };
            Some(MutRefGuard {
                _lock,
                _value: value_ptr,
            })
        } else {
            None
        }
    }

    #[inline]
    pub fn contains(&self, x: &V) -> bool
    where
        V: PartialEq,
    {
        let _lock = self.lock.read();
        let u = self.as_arr();
        for item in u {
            let value_ptr = unsafe {
                let lock_ptr = item as *const RwLock<V> as *mut RwLock<V>;
                &*(*lock_ptr).get_mut()
            };
            if value_ptr == x {
                return true;
            }
        }
        false
    }

    #[inline]
    pub fn contains_lock(&self, x: &V) -> bool
    where
        V: PartialEq,
    {
        let _lock = self.lock.read();
        let u = self.as_arr();
        for item in u {
            if *item.read() == *x {
                return true;
            }
        }
        false
    }

    /// Safety; Get an iterator over the values, protected by Vec read lock + individual value read locks
    /// 安全地访问每个数据,获取迭代器,使用Vec读锁 + 各个值的读锁保护
    pub fn iter_rlock(&self) -> IterRLock<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        IterRLock {
            _lock,
            inner: u.iter(),
        }
    }

    /// 不锁值,只锁Vec结构,适用于只读但不修改值的场景
    ///
    /// # Safety
    /// 此方法是不安全的,因为它绕过了保护每个值的 `RwLock`。
    /// 仅当您确定没有其他线程正在修改这些值时才应使用它。
    ///
    /// This method is unsafe because it bypasses the `RwLock` protecting each value.
    /// It should only be used when you are sure that no other thread is modifying the values.
    pub fn iter(&self) -> Iter<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        Iter {
            _lock,
            inner: u.iter(),
        }
    }

    /// Get a mutable iterator over the values, protected by Vec read lock + individual value write locks
    /// 获取可变迭代器,使用Vec读锁 + 各个值的写锁保护
    pub fn iter_mut_lock(&self) -> IterLock<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        IterLock {
            _lock,
            inner: u.iter(),
        }
    }

    /// Get a mutable iterator over the values, protected by Vec read lock (value no lock)
    /// 获取可变迭代器,使用Vec读锁 (值无锁)
    ///
    /// # Safety
    /// 此方法绕过了保护每个值的 `RwLock`。
    /// 仅当您确定没有其他线程正在修改这些值时才应使用它。
    ///
    /// This method bypasses the `RwLock` protecting each value.
    /// It should only be used when you are sure that no other thread is modifying the values.
    pub fn iter_mut(&self) -> IterMut<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        IterMut {
            _lock,
            inner: u.iter(),
        }
    }

    pub fn into_iter(self) -> IntoIter<V> {
        let _lock = self.lock.write();
        let m = self.dirty.into_inner();
        let mut v = Vec::with_capacity(m.len());
        for item in m {
            v.push(item.into_inner());
        }
        v.into_iter()
    }

    pub fn dirty_ref(&self) -> RefGuard<'_, Vec<RwLock<V>>> {
        RefGuard {
            _lock: self.lock.read(),
            _value: self.as_arr(),
        }
    }

    pub fn into_inner(self) -> Vec<V> {
        let m = self.dirty.into_inner();
        let mut v = Vec::with_capacity(m.len());
        for item in m {
            v.push(item.into_inner());
        }
        v
    }

    pub fn to_vec(&self) -> Vec<V>
    where
        V: Clone,
    {
        let _lock = self.lock.read();
        let u = self.as_arr();
        let mut v = Vec::with_capacity(u.len());
        for item in u {
            v.push(item.read().clone());
        }
        v
    }
}

pub struct IterRLock<'a, V> {
    pub(crate) _lock: RwLockReadGuard<'a, ()>,
    pub(crate) inner: SliceIter<'a, RwLock<V>>,
}

impl<'a, V> Iterator for IterRLock<'a, V> {
    type Item = RwLockReadGuard<'a, V>;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| v.read())
    }
}

impl<'a, V> ExactSizeIterator for IterRLock<'a, V> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, V> DoubleEndedIterator for IterRLock<'a, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|v| v.read())
    }
}

impl<'a, V> FusedIterator for IterRLock<'a, V> {}

pub struct IterLock<'a, V> {
    pub(crate) _lock: RwLockReadGuard<'a, ()>,
    pub(crate) inner: SliceIter<'a, RwLock<V>>,
}

impl<'a, V> Iterator for IterLock<'a, V> {
    type Item = RwLockWriteGuard<'a, V>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| v.write())
    }
}

impl<'a, V> ExactSizeIterator for IterLock<'a, V> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, V> DoubleEndedIterator for IterLock<'a, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|v| v.write())
    }
}

impl<'a, V> FusedIterator for IterLock<'a, V> {}

/// 不锁值的迭代器,只锁Vec结构
/// Iterator that only locks Vec structure, not individual values
pub struct Iter<'a, V> {
    pub(crate) _lock: RwLockReadGuard<'a, ()>,
    pub(crate) inner: SliceIter<'a, RwLock<V>>,
}

impl<'a, V> Iterator for Iter<'a, V> {
    type Item = &'a V;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| {
            // SAFETY: 调用者通过使用 unsafe fn iter 保证没有并发写入
            unsafe {
                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
                &*(*lock_ptr).get_mut()
            }
        })
    }
}

impl<'a, V> ExactSizeIterator for Iter<'a, V> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, V> DoubleEndedIterator for Iter<'a, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|v| {
            // SAFETY: 调用者通过使用 unsafe fn iter 保证没有并发写入
            unsafe {
                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
                &*(*lock_ptr).get_mut()
            }
        })
    }
}

impl<'a, V> FusedIterator for Iter<'a, V> {}

/// 不锁值的可变迭代器,只锁Vec结构
/// Mutable iterator that only locks Vec structure, not individual values
pub struct IterMut<'a, V> {
    pub(crate) _lock: RwLockReadGuard<'a, ()>,
    pub(crate) inner: SliceIter<'a, RwLock<V>>,
}

impl<'a, V> Iterator for IterMut<'a, V> {
    type Item = &'a mut V;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| {
            // SAFETY: 调用者通过使用此方法保证没有并发写入
            unsafe {
                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
                &mut *(*lock_ptr).get_mut()
            }
        })
    }
}

impl<'a, V> ExactSizeIterator for IterMut<'a, V> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, V> DoubleEndedIterator for IterMut<'a, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|v| {
            // SAFETY: 调用者通过使用此方法保证没有并发写入
            unsafe {
                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
                &mut *(*lock_ptr).get_mut()
            }
        })
    }
}

impl<'a, V> FusedIterator for IterMut<'a, V> {}

impl<'a, V> IntoIterator for &'a SyncVec<V> {
    type Item = &'a V;
    type IntoIter = Iter<'a, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, V> IntoIterator for &'a mut SyncVec<V> {
    type Item = &'a mut V;
    type IntoIter = IterMut<'a, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<V> IntoIterator for SyncVec<V> {
    type Item = V;
    type IntoIter = IntoIter<V>;

    fn into_iter(self) -> Self::IntoIter {
        self.into_iter()
    }
}

impl<V> Serialize for SyncVec<V>
where
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeSeq;
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        let mut seq = serializer.serialize_seq(Some(v.len()))?;
        for element in v {
            seq.serialize_element(&*element.read())?;
        }
        seq.end()
    }
}

impl<'de, V> serde::Deserialize<'de> for SyncVec<V>
where
    V: serde::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let m = Vec::deserialize(deserializer)?;
        Ok(Self::from(m))
    }
}

impl<V> Debug for SyncVec<V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.dirty_ref())
    }
}

impl<V: std::fmt::Display> std::fmt::Display for SyncVec<V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        write!(f, "[")?;
        for (i, item) in v.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}", item.read())?;
        }
        write!(f, "]")
    }
}

impl<V: PartialEq> PartialEq for SyncVec<V> {
    fn eq(&self, other: &Self) -> bool {
        let _lock1 = self.lock.read();
        let _lock2 = other.lock.read();
        let v1 = unsafe { &*self.dirty.get() };
        let v2 = unsafe { &*other.dirty.get() };
        if v1.len() != v2.len() {
            return false;
        }
        for (i1, i2) in v1.iter().zip(v2.iter()) {
            if *i1.read() != *i2.read() {
                return false;
            }
        }
        true
    }
}

impl<V: Clone> Clone for SyncVec<V> {
    fn clone(&self) -> Self {
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        let mut new_vec = Vec::with_capacity(v.len());
        for item in v {
            new_vec.push(RwLock::new(item.read().clone()));
        }
        Self {
            dirty: UnsafeCell::new(new_vec),
            lock: RwLock::new(()),
        }
    }
}

impl<V> Index<usize> for SyncVec<V> {
    type Output = V;

    /// Get a reference to the value at index, bypassing the lock.
    /// 获取索引处的值引用,绕过锁。
    ///
    /// # Safety
    /// This method is unsafe because it bypasses the `RwLock` protecting the value.
    /// It should only be used when you are sure that no other thread is modifying the value.
    /// Concurrent access using this method is undefined behavior.
    ///
    /// # 安全性
    /// 此方法是不安全的,因为它绕过了保护值的 `RwLock`。
    /// 仅当您确定没有其他线程正在修改该值时才应使用它。
    /// 使用此方法进行并发访问是未定义行为。
    fn index(&self, index: usize) -> &Self::Output {
        unsafe {
            let v = &*self.dirty.get();
            // We need to get &V from &RwLock<V> without locking.
            // Since we are in an unsafe block and claiming it's unsafe/no concurrent access,
            // we can cast the &RwLock<V> to &mut RwLock<V> (conceptually) to use get_mut(),
            // or rely on the fact that we are bypassing the lock.
            // However, RwLock::get_mut requires &mut RwLock.
            // We only have &RwLock.
            // We can cast &RwLock to &mut RwLock because we are asserting exclusive access (via the safety contract).
            let lock_ptr = &v[index] as *const RwLock<V> as *mut RwLock<V>;
            (*lock_ptr).get_mut()
        }
    }
}

impl<V> IndexMut<usize> for SyncVec<V> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        // This is unsafe because we are bypassing the `RwLock` protecting the value.
        // 这是不安全的,因为我们绕过了保护值的 `RwLock`。
        let v = self.dirty.get_mut();
        v[index].get_mut()
    }
}

#[macro_export]
macro_rules! sync_vec {
    () => (
        $crate::SyncVec::new()
    );
    ($elem:expr; $n:expr) => (
        $crate::SyncVec::with_vec(vec![$elem;$n])
    );
    ($($x:expr),+ $(,)?) => (
        $crate::SyncVec::with_vec(vec![$($x),+,])
    );
}

#[test]
fn test_case() {
    struct D {}
    impl D {
        fn is_some(&self) -> bool {
            println!("is_some");
            true
        }
        fn take(&mut self) -> Option<bool> {
            println!("take");
            Some(true)
        }
    }

    let mut d = D {};
    if let (true, Some(d)) = (d.is_some(), d.take()) {
        println!("d is {d}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn test_new_and_capacity() {
        let vec: SyncVec<i32> = SyncVec::new();
        assert!(vec.is_empty());
        assert_eq!(vec.len(), 0);

        let vec: SyncVec<i32> = SyncVec::with_capacity(10);
        assert!(vec.is_empty());
        assert_eq!(vec.len(), 0);
    }

    #[test]
    fn test_push_and_get() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.len(), 3);
        assert_eq!(*vec.get(0).unwrap(), 1);
        assert_eq!(*vec.get(1).unwrap(), 2);
        assert_eq!(*vec.get(2).unwrap(), 3);
        assert!(vec.get(3).is_none());
    }

    #[test]
    fn test_index_methods() {
        let mut vec = SyncVec::new();
        vec.push(10);
        vec.push(20);

        assert_eq!(vec[0], 10);
        assert_eq!(vec[1], 20);

        {
            let val = &mut vec[0];
            *val = 100;
        }
        assert_eq!(vec[0], 100);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_panic() {
        let vec = SyncVec::new();
        vec.push(1);
        let _ = vec[1];
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_mut_panic() {
        let mut vec = SyncVec::new();
        vec.push(1);
        let _ = &mut vec[1];
    }

    #[test]
    fn test_remove_and_pop() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.pop(), Some(3));
        assert_eq!(vec.len(), 2);

        assert_eq!(vec.remove(0), Some(1));
        assert_eq!(vec.len(), 1);
        assert_eq!(*vec.get(0).unwrap(), 2);
    }

    #[test]
    fn test_concurrency() {
        let vec = Arc::new(SyncVec::new());
        let mut handles = vec![];

        // Multiple writers
        for i in 0..10 {
            let vec = vec.clone();
            handles.push(thread::spawn(move || {
                for j in 0..100 {
                    vec.push(i * 100 + j);
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        assert_eq!(vec.len(), 1000);
    }

    #[test]
    fn test_concurrent_modify() {
        let vec = Arc::new(SyncVec::new());
        for i in 0..100 {
            vec.push(i);
        }

        let vec_clone = vec.clone();
        let handle = thread::spawn(move || {
            for i in 0..100 {
                if let Some(mut guard) = vec_clone.get_mut(i) {
                    *guard += 1;
                }
            }
        });

        // Concurrent read
        for i in 0..100 {
            if let Some(val) = vec.get(i) {
                let _ = *val; // Just read
            }
        }

        handle.join().unwrap();

        // Verify modifications
        for i in 0..100 {
            assert_eq!(*vec.get(i).unwrap(), i + 1);
        }
    }

    #[test]
    fn test_iter() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        let mut sum = 0;
        for item in vec.iter() {
            sum += *item;
        }
        assert_eq!(sum, 6);
    }

    #[test]
    fn test_iter_mut() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        for mut item in vec.iter_mut() {
            *item *= 2;
        }

        assert_eq!(*vec.get(0).unwrap(), 2);
        assert_eq!(*vec.get(1).unwrap(), 4);
        assert_eq!(*vec.get(2).unwrap(), 6);
    }

    #[test]
    fn test_clear() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.clear();
        assert!(vec.is_empty());
    }

    #[test]
    fn test_contains() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        assert!(vec.contains(&1));
        assert!(!vec.contains(&3));
    }

    #[test]
    fn test_iterator_traits() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        let mut iter = vec.iter();
        assert_eq!(iter.len(), 3);
        assert_eq!(*iter.next().unwrap(), 1);
        assert_eq!(iter.len(), 2);
        assert_eq!(*iter.next_back().unwrap(), 3);
        assert_eq!(iter.len(), 1);
        assert_eq!(*iter.next().unwrap(), 2);
        assert_eq!(iter.len(), 0);
        assert!(iter.next().is_none());
        assert!(iter.next_back().is_none());

        let mut vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);
        let mut iter_mut = vec.iter_mut();
        assert_eq!(iter_mut.len(), 3);
        assert_eq!(*iter_mut.next().unwrap(), 1);
        assert_eq!(iter_mut.len(), 2);
        assert_eq!(*iter_mut.next_back().unwrap(), 3);
        assert_eq!(iter_mut.len(), 1);
        assert_eq!(*iter_mut.next().unwrap(), 2);
        assert_eq!(iter_mut.len(), 0);
        assert!(iter_mut.next().is_none());
        assert!(iter_mut.next_back().is_none());
    }

    #[test]
    fn test_from_iter_and_extend() {
        let vec: SyncVec<i32> = SyncVec::from_iter(vec![1, 2, 3]);
        assert_eq!(vec.len(), 3);
        assert_eq!(*vec.get(0).unwrap(), 1);

        let mut vec = SyncVec::new();
        vec.extend(vec![1, 2, 3]);
        assert_eq!(vec.len(), 3);
        assert_eq!(*vec.get(0).unwrap(), 1);
    }

    #[test]
    fn test_iter_notlock() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        // 测试 iter 基本功能
        let mut sum = 0;
        for item in vec.iter() {
            sum += *item;
        }
        assert_eq!(sum, 6);

        // 测试 ExactSizeIterator
        let iter = vec.iter();
        assert_eq!(iter.len(), 3);
    }

    #[test]
    fn test_iter_double_ended() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        let mut iter = vec.iter();
        assert_eq!(*iter.next().unwrap(), 1);
        assert_eq!(*iter.next_back().unwrap(), 3);
        assert_eq!(*iter.next().unwrap(), 2);
        assert!(iter.next().is_none());
    }

    #[test]
    fn test_iter_empty() {
        let vec: SyncVec<i32> = SyncVec::new();

        let mut count = 0;
        for _ in vec.iter() {
            count += 1;
        }
        assert_eq!(count, 0);

        let iter = vec.iter();
        assert_eq!(iter.len(), 0);
    }

    #[test]
    fn test_into_iter_ref() {
        let vec = SyncVec::new();
        vec.push(10);
        vec.push(20);
        vec.push(30);

        // 测试 IntoIterator for &SyncVec
        let mut sum = 0;
        for item in &vec {
            sum += *item;
        }
        assert_eq!(sum, 60);

        // 确保 vec 仍然可用
        assert_eq!(vec.len(), 3);
    }

    #[test]
    fn test_into_iter_mut() {
        let mut vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        // 测试 IntoIterator for &mut SyncVec
        for mut item in &mut vec {
            *item *= 2;
        }

        assert_eq!(*vec.get(0).unwrap(), 2);
        assert_eq!(*vec.get(1).unwrap(), 4);
        assert_eq!(*vec.get(2).unwrap(), 6);
    }

    #[test]
    fn test_into_iter_owned() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        // 测试 IntoIterator for SyncVec (消耗所有权)
        let collected: Vec<_> = vec.into_iter().collect();
        assert_eq!(collected, vec![1, 2, 3]);
    }
}