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> std::fmt::Display for ReadGuard<'_, V>
264where
265 V: std::fmt::Display,
266{
267 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
268 self.v.fmt(f)
269 }
270}
271
272impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
274 fn as_ref(&self) -> &V {
275 self.v
276 }
277}
278
279pub struct ReadGuardVec<'a, V> {
280 _lock: spin::RwLockReadGuard<'a, ()>,
281 v: &'a Vec<V>,
282}
283
284impl<'a, V> Deref for ReadGuardVec<'a, V> {
285 type Target = Vec<V>;
286 fn deref(&self) -> &Self::Target {
287 self.v
288 }
289}
290
291impl<'a, V> AsRef<Vec<V>> for ReadGuardVec<'a, V> {
293 fn as_ref(&self) -> &Vec<V> {
294 self.v
295 }
296}
297
298impl<'a, V> Debug for ReadGuardVec<'_, V>
300where
301 V: Debug,
302{
303 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
304 write!(f, "{:?}", self.v)
305 }
306}
307
308impl<'a, V> std::fmt::Display for ReadGuardVec<'_, V>
310where
311 V: std::fmt::Display,
312{
313 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
314 self.v.fmt(f)
315 }
316}
317
318pub struct WriteGuard<'a, V> {
319 _lock: spin::RwLockWriteGuard<'a, ()>,
320 v: &'a mut V,
321}
322
323impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
325 fn as_ref(&self) -> &V {
326 self.v
327 }
328}
329
330impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
332 fn as_mut(&mut self) -> &mut V {
333 self.v
334 }
335}
336
337impl<'a, V> Deref for WriteGuard<'_, V> {
338 type Target = V;
339
340 fn deref(&self) -> &Self::Target {
341 self.v
342 }
343}
344
345impl<'a, V> DerefMut for WriteGuard<'_, V> {
346 fn deref_mut(&mut self) -> &mut Self::Target {
347 self.v
348 }
349}
350
351impl<'a, V> Debug for WriteGuard<'_, V>
352where
353 V: Debug,
354{
355 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
356 write!(f, "{:?}", self.v)
357 }
358}
359
360impl<'a, V> std::fmt::Display for WriteGuard<'_, V> {
362 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
363 self.v.fmt(f)
364 }
365}
366
367pub struct Iter<'a, V> {
368 _lock: Option<spin::RwLockReadGuard<'a, ()>>,
369 lock_arc: Option<Arc<spin::RwLockReadGuard<'a, ()>>>,
370 inner: SliceIter<'a, V>,
371}
372
373impl<'a, V> Iter<'a, V> {
374 pub fn clone_lock(&mut self) -> Arc<spin::RwLockReadGuard<'a, ()>> {
375 if self._lock.is_some() {
376 let lock = self._lock.take().expect("lock is None");
377 let lock = Arc::new(lock);
378 self.lock_arc = Some(lock.clone());
379 lock
380 } else {
381 self.lock_arc.as_ref().expect("lock_arc is None").clone()
382 }
383 }
384}
385
386impl<'a, V> Iterator for Iter<'a, V> {
387 type Item = &'a V;
388 fn next(&mut self) -> Option<Self::Item> {
389 self.inner.next()
390 }
391}
392
393pub struct IterMut<'a, V> {
394 _lock: spin::rwlock::RwLockWriteGuard<'a, ()>,
395 inner: SliceIterMut<'a, V>,
396}
397
398impl<'a, V> Deref for IterMut<'a, V> {
399 type Target = SliceIterMut<'a, V>;
400
401 fn deref(&self) -> &Self::Target {
402 &self.inner
403 }
404}
405
406impl<'a, V> DerefMut for IterMut<'a, V> {
407 fn deref_mut(&mut self) -> &mut Self::Target {
408 &mut self.inner
409 }
410}
411
412impl<'a, V> Iterator for IterMut<'a, V> {
413 type Item = &'a mut V;
414
415 fn next(&mut self) -> Option<Self::Item> {
416 self.inner.next()
417 }
418}
419
420impl<'a, V> IntoIterator for &'a SyncVec<V> {
421 type Item = &'a V;
422 type IntoIter = Iter<'a, V>;
423
424 fn into_iter(self) -> Self::IntoIter {
425 self.iter()
426 }
427}
428
429impl<V> IntoIterator for SyncVec<V> {
430 type Item = V;
431 type IntoIter = IntoIter<V>;
432
433 fn into_iter(self) -> Self::IntoIter {
434 self.into_iter()
435 }
436}
437
438impl<V> Serialize for SyncVec<V>
439where
440 V: Serialize,
441{
442 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
443 where
444 S: Serializer,
445 {
446 self.dirty_ref().serialize(serializer)
447 }
448}
449
450impl<'de, V> serde::Deserialize<'de> for SyncVec<V>
451where
452 V: serde::Deserialize<'de>,
453{
454 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
455 where
456 D: Deserializer<'de>,
457 {
458 let m = Vec::deserialize(deserializer)?;
459 Ok(Self::from(m))
460 }
461}
462
463impl<V> Debug for SyncVec<V>
464where
465 V: Debug,
466{
467 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
468 write!(f, "{:?}", self.dirty_ref())
469 }
470}
471
472impl<V: std::fmt::Display> std::fmt::Display for SyncVec<V> {
474 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
475 write!(f, "{}", self.dirty_ref())
476 }
477}
478
479impl<V> Index<usize> for SyncVec<V> {
481 type Output = V;
482 fn index(&self, index: usize) -> &Self::Output {
483 &self.as_arr()[index]
484 }
485}
486
487impl<V: PartialEq> PartialEq for SyncVec<V> {
488 fn eq(&self, other: &Self) -> bool {
489 self.dirty_ref().eq(other.dirty_ref().as_ref())
490 }
491}
492
493impl<V: Clone> Clone for SyncVec<V> {
494 fn clone(&self) -> Self {
495 SyncVec::from(self.dirty_ref().to_vec())
496 }
497}
498
499#[macro_export]
500macro_rules! sync_vec {
501 () => (
502 $crate::sync::SyncVec::new()
503 );
504 ($elem:expr; $n:expr) => (
505 $crate::sync::SyncVec::with_vec(vec![$elem;$n])
506 );
507 ($($x:expr),+ $(,)?) => (
508 $crate::sync::SyncVec::with_vec(vec![$($x),+,])
509 );
510}
511
512#[test]
513fn test_case() {
514 struct D {}
515 impl D {
516 fn is_some(&self) -> bool {
517 println!("is_some");
518 true
519 }
520 fn take(&mut self) -> Option<bool> {
521 println!("take");
522 Some(true)
523 }
524 }
525
526 let mut d = D {};
527 if let (true, Some(d)) = (d.is_some(), d.take()) {
528 println!("d is {d}");
529 }
530}