surrealdb_core/mac/
mod.rs

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
/// Converts some text into a new line byte string
#[macro_export]
#[doc(hidden)]
macro_rules! bytes {
	($expression:expr) => {
		format!("{}\n", $expression).into_bytes()
	};
}

/// Creates a new b-tree map of key-value pairs
#[macro_export]
#[doc(hidden)]
macro_rules! map {
    ($($k:expr => $v:expr),* $(,)? $( => $x:expr )?) => {{
        let mut m = ::std::collections::BTreeMap::new();
        $(m.extend($x.iter().map(|(k, v)| (k.clone(), v.clone())));)?
        $(m.insert($k, $v);)+
        m
    }};
}

/// Matches on a specific config environment
#[macro_export]
#[doc(hidden)]
macro_rules! get_cfg {
	($i:ident : $($s:expr),+) => (
		let $i = || { $( if cfg!($i=$s) { return $s; } );+ "unknown"};
	)
}

/// A macro that allows lazily parsing a value from the environment variable,
/// with a fallback default value if the variable is not set or parsing fails.
///
/// # Parameters
///
/// - `$key`: An expression representing the name of the environment variable.
/// - `$t`: The type of the value to be parsed.
/// - `$default`: The default value to fall back to if the environment variable
///   is not set or parsing fails.
///
/// # Return Value
///
/// A lazy static variable of type `once_cell::sync::Lazy`, which holds the parsed value
/// from the environment variable or the default value.
#[macro_export]
macro_rules! lazy_env_parse {
	($key:expr, $t:ty, $default:expr) => {
		once_cell::sync::Lazy::new(|| {
			std::env::var($key)
				.and_then(|s| Ok(s.parse::<$t>().unwrap_or($default)))
				.unwrap_or($default)
		})
	};
}

/// Lazily parses an environment variable into a specified type. If the environment variable is not set or the parsing fails,
/// it returns a default value.
///
/// # Parameters
///
/// - `$key`: A string literal representing the name of the environment variable.
/// - `$t`: The type to parse the environment variable into.
/// - `$default`: A fallback function or constant value to be returned if the environment variable is not set or the parsing fails.
///
/// # Returns
///
/// A `Lazy` static variable that stores the parsed value or the default value.
#[macro_export]
macro_rules! lazy_env_parse_or_else {
	($key:expr, $t:ty, $default:expr) => {
		once_cell::sync::Lazy::new(|| {
			std::env::var($key)
				.and_then(|s| Ok(s.parse::<$t>().unwrap_or_else($default)))
				.unwrap_or_else($default)
		})
	};
}

#[cfg(test)]
#[macro_export]
macro_rules! async_defer{
	(let $bind:ident = ($capture:expr) defer { $($d:tt)* } after { $($t:tt)* }) => {
		async {
			async_defer!(@captured);
			async_defer!(@catch_unwind);

			#[allow(unused_mut)]
			let mut v = Some($capture);
			#[allow(unused_mut)]
			let mut $bind = Captured(&mut v);
			let res = CatchUnwindFuture(async { $($t)* }).await;
			#[allow(unused_variables,unused_mut)]
			if let Some(mut $bind) = v.take(){
				async { $($d)* }.await;
			}
			match res{
				Ok(x) => x,
				Err(e) => ::std::panic::resume_unwind(e)
			}

		}
	};

	(defer { $($d:tt)* } after { $($t:tt)* }) => {
		async {
			async_defer!(@catch_unwind);

			let res = CatchUnwindFuture(async { $($t)* }).await;
			#[allow(unused_variables)]
			async { $($d)* }.await;
			match res{
				Ok(x) => x,
				Err(e) => ::std::panic::resume_unwind(e)
			}

		}
	};

	(@captured) => {
		// unwraps are save cause the value can only be taken by consuming captured.
		pub struct Captured<'a,T>(&'a mut Option<T>);
		impl<T> ::std::ops::Deref for Captured<'_,T>{
			type Target = T;

			fn deref(&self) -> &T{
				self.0.as_ref().unwrap()
			}
		}
		impl<T> ::std::ops::DerefMut for Captured<'_,T>{
			fn deref_mut(&mut self) -> &mut T{
				self.0.as_mut().unwrap()
			}
		}
		impl<T> Captured<'_,T>{
			#[allow(dead_code)]
			pub fn take(self) -> T{
				self.0.take().unwrap()
			}
		}
	};

	(@catch_unwind) => {
		struct CatchUnwindFuture<F>(F);
		impl<F,R> ::std::future::Future for CatchUnwindFuture<F>
			where F: ::std::future::Future<Output = R>,
		{
			type Output = ::std::thread::Result<R>;

			fn poll(self: ::std::pin::Pin<&mut Self>, cx: &mut ::std::task::Context<'_>) -> ::std::task::Poll<Self::Output>{
				let pin = unsafe{ self.map_unchecked_mut(|x| &mut x.0) };
				match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(||{
					pin.poll(cx)
				})) {
					Ok(x) => x.map(Ok),
					Err(e) => ::std::task::Poll::Ready(Err(e))
				}
			}
		}
	};
}

#[cfg(test)]
mod test {
	#[tokio::test]
	async fn async_defer_basic() {
		let mut counter = 0;

		async_defer!(defer {
			assert_eq!(counter,1);
		} after {
			assert_eq!(counter,0);
			counter += 1;
		})
		.await;

		async_defer!(let t = (()) defer {
			panic!("shouldn't be called");
		} after {
			assert_eq!(counter,1);
			counter += 1;
			t.take();
		})
		.await;
	}

	#[tokio::test]
	#[should_panic(expected = "this is should be the message of the panic")]
	async fn async_defer_panic() {
		let mut counter = 0;

		async_defer!(defer {
			// This should still execute
			assert_eq!(counter,1);
			panic!("this is should be the message of the panic")
		} after {
			assert_eq!(counter,0);
			counter += 1;
			panic!("this panic should be caught")
		})
		.await;
	}
}