dprint_core/communication/
utils.rs1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::rc::Rc;
4use std::sync::atomic::AtomicBool;
5use std::sync::atomic::Ordering;
6
7#[derive(Default)]
8pub struct AtomicFlag(AtomicBool);
9
10impl AtomicFlag {
11 pub fn raise(&self) -> bool {
12 !self.0.swap(true, Ordering::SeqCst)
13 }
14
15 pub fn is_raised(&self) -> bool {
16 self.0.load(Ordering::SeqCst)
17 }
18}
19
20#[derive(Default)]
21pub struct IdGenerator(RefCell<u32>);
22
23impl IdGenerator {
24 pub fn next(&self) -> u32 {
25 let mut borrow = self.0.borrow_mut();
26 let next = *borrow;
27 *borrow += 1;
28 next
29 }
30}
31
32pub struct RcIdStoreOwnedGuard<T> {
33 store: RcIdStore<T>,
34 message_id: u32,
35}
36
37impl<T> Drop for RcIdStoreOwnedGuard<T> {
38 fn drop(&mut self) {
39 self.store.take(self.message_id);
40 }
41}
42
43pub struct RcIdStoreGuard<'a, T> {
44 store: &'a RcIdStore<T>,
45 message_id: u32,
46}
47
48impl<T> Drop for RcIdStoreGuard<'_, T> {
49 fn drop(&mut self) {
50 self.store.take(self.message_id);
51 }
52}
53
54pub struct RcIdStore<T>(Rc<RefCell<HashMap<u32, T>>>);
56
57impl<T> Default for RcIdStore<T> {
58 fn default() -> Self {
59 Self(Default::default())
60 }
61}
62
63impl<T> RcIdStore<T> {
64 pub fn new() -> Self {
65 Default::default()
66 }
67
68 pub fn store(&self, message_id: u32, data: T) {
69 self.0.borrow_mut().insert(message_id, data);
70 }
71
72 pub fn store_with_guard(&self, message_id: u32, data: T) -> RcIdStoreGuard<'_, T> {
73 self.store(message_id, data);
74 RcIdStoreGuard { store: self, message_id }
75 }
76
77 pub fn store_with_owned_guard(&self, message_id: u32, data: T) -> RcIdStoreOwnedGuard<T> {
78 self.store(message_id, data);
79 RcIdStoreOwnedGuard {
80 store: self.clone(),
81 message_id,
82 }
83 }
84
85 pub fn take(&self, message_id: u32) -> Option<T> {
86 self.0.borrow_mut().remove(&message_id)
87 }
88
89 pub fn take_all(&self) -> HashMap<u32, T> {
90 let mut map = self.0.borrow_mut();
91 std::mem::take(&mut *map)
92 }
93}
94
95impl<T: Clone> RcIdStore<T> {
96 pub fn get_cloned(&self, message_id: u32) -> Option<T> {
97 self.0.borrow().get(&message_id).cloned()
98 }
99}
100
101impl<T> Clone for RcIdStore<T> {
104 fn clone(&self) -> Self {
105 Self(self.0.clone())
106 }
107}