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