1use serde::{Deserializer, Serialize, Serializer};
2use spin::RwLock;
3use std::cell::UnsafeCell;
4use std::fmt::{Debug, Formatter, Pointer};
5use std::ops::{Deref, DerefMut, Index};
6use std::slice::{Iter as SliceIter, IterMut as SliceIterMut};
7use std::sync::Arc;
8use std::vec::IntoIter;
9
10pub struct SyncVec<V> {
11 dirty: UnsafeCell<Vec<V>>,
12 lock: RwLock<()>,
13}
14
15unsafe impl<V> Send for SyncVec<V> {}
17
18unsafe impl<V> Sync for SyncVec<V> {}
20
21impl<V> Default for SyncVec<V> {
22 fn default() -> Self {
23 Self::new()
24 }
25}
26
27impl<V> From<Vec<V>> for SyncVec<V> {
28 fn from(v: Vec<V>) -> Self {
29 Self::with_vec(v)
30 }
31}
32
33impl<V> SyncVec<V>
34where
35 V: Clone,
36{
37 pub fn to_vec(&self) -> Vec<V> {
38 let mut v = Vec::new();
39 for i in self.iter() {
40 v.push(i.clone());
41 }
42 v
43 }
44}
45
46impl<V> SyncVec<V> {
47 pub fn new_arc() -> Arc<Self> {
48 Arc::new(Self::new())
49 }
50
51 pub const fn new() -> Self {
52 Self {
53 dirty: UnsafeCell::new(Vec::new()),
54 lock: RwLock::new(()),
55 }
56 }
57
58 pub const fn with_vec(vec: Vec<V>) -> Self {
59 Self {
60 dirty: UnsafeCell::new(vec),
61 lock: RwLock::new(()),
62 }
63 }
64
65 pub fn with_capacity(capacity: usize) -> Self {
66 Self {
67 dirty: UnsafeCell::new(Vec::with_capacity(capacity)),
68 lock: RwLock::new(()),
69 }
70 }
71
72 #[inline(always)]
73 fn as_arr(&self) -> &Vec<V> {
74 unsafe { &*self.dirty.get() }
75 }
76
77 #[inline(always)]
78 fn as_arr_mut(&self) -> &mut Vec<V> {
79 unsafe { &mut *self.dirty.get() }
80 }
81
82 #[inline(always)]
83 pub fn insert(&self, index: usize, v: V) {
84 let _lock = self.lock.write();
85 self.as_arr_mut().insert(index, v);
86 }
87
88 #[inline(always)]
89 pub fn push(&self, v: V) {
90 let _lock = self.lock.write();
91 self.as_arr_mut().push(v);
92 }
93
94 #[inline(always)]
95 pub fn push_return(&self, v: V) -> usize {
96 let _lock = self.lock.write();
97 let u = self.as_arr_mut();
98 let index = u.len();
99 u.push(v);
100 index
101 }
102
103 #[inline(always)]
104 pub fn push_vec(&self, input_arr: Vec<V>) {
105 let mut _lock = self.lock.write();
106 let u = self.as_arr_mut();
107 for ele in input_arr.into_iter() {
108 u.push(ele);
109 }
110 }
111
112 pub fn pop(&self) -> Option<V> {
113 let _lock = self.lock.write();
114 let u = self.as_arr_mut();
115 let r = u.pop();
116 r
117 }
118
119 pub fn remove(&self, index: usize) -> Option<V> {
120 let _lock = self.lock.write();
121 let u = self.as_arr_mut();
122 if u.len() > index {
123 let v = u.remove(index);
124 Some(v)
125 } else {
126 None
127 }
128 }
129
130 pub fn len(&self) -> usize {
131 let _lock = self.lock.read();
132 let u = self.as_arr();
133 u.len()
134 }
135
136 pub fn is_empty(&self) -> bool {
137 let _lock = self.lock.read();
138 let u = self.as_arr();
139 u.is_empty()
140 }
141
142 pub fn clear(&self) {
143 let _lock = self.lock.write();
144 let u = self.as_arr_mut();
145 u.clear();
146 }
147
148 pub fn shrink_to_fit(&self) {
149 let _lock = self.lock.write();
150 let u = self.as_arr_mut();
151 u.shrink_to_fit();
152 }
153
154 pub const fn from(vec: Vec<V>) -> Self {
155 let s = Self::with_vec(vec);
156 s
157 }
158
159 #[inline]
160 pub fn get(&self, index: usize) -> Option<ReadGuard<'_, V>> {
161 let _lock = self.lock.read();
162 let u = self.as_arr();
163 if u.get(index).is_none() {
164 None
165 } else {
166 Some(ReadGuard {
167 _lock,
168 v: &u[index],
169 })
170 }
171 }
172
173 #[inline]
174 pub fn get_uncheck(&self, index: usize) -> ReadGuard<'_, V> {
175 let _lock = self.lock.read();
176 let u = self.as_arr();
177 ReadGuard {
178 _lock,
179 v: &u[index],
180 }
181 }
182
183 #[inline]
184 pub fn get_mut(&self, index: usize) -> Option<WriteGuard<'_, V>> {
185 let _lock = self.lock.write();
186 let u = self.as_arr_mut();
187 if u.get(index).is_none() {
188 return None;
189 }
190 Some(WriteGuard {
191 _lock,
192 v: &mut u[index],
193 })
194 }
195
196 #[inline]
197 pub fn contains(&self, x: &V) -> bool
198 where
199 V: PartialEq,
200 {
201 let _lock = self.lock.read();
202 let u = self.as_arr();
203 u.contains(x)
204 }
205
206 pub fn iter(&self) -> Iter<'_, V> {
207 let _lock = self.lock.read();
208 let u = self.as_arr();
209 Iter {
210 _lock: Some(_lock),
211 lock_arc: None,
212 inner: u.iter(),
213 }
214 }
215
216 pub fn iter_mut<'a>(&'a self) -> IterMut<'a, V> {
217 let mut _lock: spin::rwlock::RwLockWriteGuard<'_, ()> = self.lock.write();
218 let iter = self.as_arr_mut().iter_mut();
219 let iter = IterMut { _lock, inner: iter };
220 return iter;
221 }
222
223 pub fn into_iter(self) -> IntoIter<V> {
224 let _lock = self.lock.write();
225 let m = self.dirty.into_inner();
226 m.into_iter()
227 }
228
229 pub fn dirty_ref(&self) -> ReadGuardVec<V> {
230 ReadGuardVec {
231 _lock: self.lock.read(),
232 v: self.as_arr(),
233 }
234 }
235
236 pub fn into_inner(self) -> Vec<V> {
237 self.dirty.into_inner()
238 }
239}
240
241pub struct ReadGuard<'a, V> {
242 _lock: spin::RwLockReadGuard<'a, ()>,
243 v: &'a V,
244}
245
246impl<'a, V> Deref for ReadGuard<'a, V> {
247 type Target = V;
248 fn deref(&self) -> &Self::Target {
249 self.v
250 }
251}
252
253impl<'a, V> Debug for ReadGuard<'_, V>
254where
255 V: Debug,
256{
257 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
258 write!(f, "{:?}", self.v)
259 }
260}
261
262impl<'a, V> PartialEq for ReadGuard<'a, V>
263where
264 V: PartialEq,
265{
266 fn eq(&self, other: &Self) -> bool {
267 self.v.eq(other.v)
268 }
269}
270
271impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
272
273impl<'a, V> std::fmt::Display for ReadGuard<'_, V>
275where
276 V: std::fmt::Display,
277{
278 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
279 self.v.fmt(f)
280 }
281}
282
283impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
285 fn as_ref(&self) -> &V {
286 self.v
287 }
288}
289
290pub struct ReadGuardVec<'a, V> {
291 _lock: spin::RwLockReadGuard<'a, ()>,
292 v: &'a Vec<V>,
293}
294
295impl<'a, V> Deref for ReadGuardVec<'a, V> {
296 type Target = Vec<V>;
297 fn deref(&self) -> &Self::Target {
298 self.v
299 }
300}
301
302impl<'a, V> PartialEq for ReadGuardVec<'a, V>
303where
304 V: PartialEq,
305{
306 fn eq(&self, other: &Self) -> bool {
307 self.v.eq(other.v)
308 }
309}
310
311impl<'a, V> PartialEq<Vec<V>> for ReadGuardVec<'a, V>
312where
313 V: PartialEq,
314{
315 fn eq(&self, other: &Vec<V>) -> bool {
316 self.v.eq(other)
317 }
318}
319
320impl<'a, V> PartialEq<&Vec<V>> for ReadGuardVec<'a, V>
321where
322 V: PartialEq,
323{
324 fn eq(&self, other: &&Vec<V>) -> bool {
325 self.v.eq(*other)
326 }
327}
328
329impl<'a, V> AsRef<Vec<V>> for ReadGuardVec<'a, V> {
331 fn as_ref(&self) -> &Vec<V> {
332 self.v
333 }
334}
335
336impl<'a, V> Debug for ReadGuardVec<'_, V>
338where
339 V: Debug,
340{
341 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
342 write!(f, "{:?}", self.v)
343 }
344}
345
346impl<'a, V> std::fmt::Display for ReadGuardVec<'_, V>
348where
349 V: std::fmt::Display,
350{
351 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
352 self.v.fmt(f)
353 }
354}
355
356pub struct WriteGuard<'a, V> {
357 _lock: spin::RwLockWriteGuard<'a, ()>,
358 v: &'a mut V,
359}
360
361impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
363 fn as_ref(&self) -> &V {
364 self.v
365 }
366}
367
368impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
370 fn as_mut(&mut self) -> &mut V {
371 self.v
372 }
373}
374
375impl<'a, V> Deref for WriteGuard<'_, V> {
376 type Target = V;
377
378 fn deref(&self) -> &Self::Target {
379 self.v
380 }
381}
382
383impl<'a, V> DerefMut for WriteGuard<'_, V> {
384 fn deref_mut(&mut self) -> &mut Self::Target {
385 self.v
386 }
387}
388
389impl<'a, V> Debug for WriteGuard<'_, V>
390where
391 V: Debug,
392{
393 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
394 write!(f, "{:?}", self.v)
395 }
396}
397
398impl<'a, V> std::fmt::Display for WriteGuard<'_, V> {
400 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
401 self.v.fmt(f)
402 }
403}
404
405pub struct Iter<'a, V> {
406 _lock: Option<spin::RwLockReadGuard<'a, ()>>,
407 lock_arc: Option<Arc<spin::RwLockReadGuard<'a, ()>>>,
408 inner: SliceIter<'a, V>,
409}
410
411impl<'a, V> Iter<'a, V> {
412 pub fn clone_lock(&mut self) -> Arc<spin::RwLockReadGuard<'a, ()>> {
413 if self._lock.is_some() {
414 let lock = self._lock.take().expect("lock is None");
415 let lock = Arc::new(lock);
416 self.lock_arc = Some(lock.clone());
417 lock
418 } else {
419 self.lock_arc.as_ref().expect("lock_arc is None").clone()
420 }
421 }
422}
423
424impl<'a, V> Iterator for Iter<'a, V> {
425 type Item = &'a V;
426 fn next(&mut self) -> Option<Self::Item> {
427 self.inner.next()
428 }
429}
430
431pub struct IterMut<'a, V> {
432 _lock: spin::rwlock::RwLockWriteGuard<'a, ()>,
433 inner: SliceIterMut<'a, V>,
434}
435
436impl<'a, V> Deref for IterMut<'a, V> {
437 type Target = SliceIterMut<'a, V>;
438
439 fn deref(&self) -> &Self::Target {
440 &self.inner
441 }
442}
443
444impl<'a, V> DerefMut for IterMut<'a, V> {
445 fn deref_mut(&mut self) -> &mut Self::Target {
446 &mut self.inner
447 }
448}
449
450impl<'a, V> Iterator for IterMut<'a, V> {
451 type Item = &'a mut V;
452
453 fn next(&mut self) -> Option<Self::Item> {
454 self.inner.next()
455 }
456}
457
458impl<'a, V> IntoIterator for &'a SyncVec<V> {
459 type Item = &'a V;
460 type IntoIter = Iter<'a, V>;
461
462 fn into_iter(self) -> Self::IntoIter {
463 self.iter()
464 }
465}
466
467impl<V> IntoIterator for SyncVec<V> {
468 type Item = V;
469 type IntoIter = IntoIter<V>;
470
471 fn into_iter(self) -> Self::IntoIter {
472 self.into_iter()
473 }
474}
475
476impl<V> Serialize for SyncVec<V>
477where
478 V: Serialize,
479{
480 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
481 where
482 S: Serializer,
483 {
484 self.dirty_ref().serialize(serializer)
485 }
486}
487
488impl<'de, V> serde::Deserialize<'de> for SyncVec<V>
489where
490 V: serde::Deserialize<'de>,
491{
492 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
493 where
494 D: Deserializer<'de>,
495 {
496 let m = Vec::deserialize(deserializer)?;
497 Ok(Self::from(m))
498 }
499}
500
501impl<V> Debug for SyncVec<V>
502where
503 V: Debug,
504{
505 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
506 write!(f, "{:?}", self.dirty_ref())
507 }
508}
509
510impl<V: std::fmt::Display> std::fmt::Display for SyncVec<V> {
512 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
513 write!(f, "{}", self.dirty_ref())
514 }
515}
516
517impl<V> Index<usize> for SyncVec<V> {
519 type Output = V;
520 fn index(&self, index: usize) -> &Self::Output {
521 &self.as_arr()[index]
522 }
523}
524
525impl<V: PartialEq> PartialEq for SyncVec<V> {
526 fn eq(&self, other: &Self) -> bool {
527 self.dirty_ref().eq(other.dirty_ref().as_ref())
528 }
529}
530
531impl<V: Clone> Clone for SyncVec<V> {
532 fn clone(&self) -> Self {
533 SyncVec::from(self.dirty_ref().to_vec())
534 }
535}
536
537#[macro_export]
538macro_rules! sync_vec {
539 () => (
540 $crate::SyncVec::new()
541 );
542 ($elem:expr; $n:expr) => (
543 $crate::SyncVec::with_vec(vec![$elem;$n])
544 );
545 ($($x:expr),+ $(,)?) => (
546 $crate::SyncVec::with_vec(vec![$($x),+,])
547 );
548}
549
550#[test]
551fn test_case() {
552 struct D {}
553 impl D {
554 fn is_some(&self) -> bool {
555 println!("is_some");
556 true
557 }
558 fn take(&mut self) -> Option<bool> {
559 println!("take");
560 Some(true)
561 }
562 }
563
564 let mut d = D {};
565 if let (true, Some(d)) = (d.is_some(), d.take()) {
566 println!("d is {d}");
567 }
568}