aboutsummaryrefslogtreecommitdiff
path: root/src/util.rs
blob: 017ef002adf374f34a435c41598b5ad859a424ac (plain) (blame)
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
use serde::Serialize;

use tokio::sync::watch;

/// Utility function: encodes any serializable value in MessagePack binary format
/// using the RMP library.
///
/// Field names and variant names are included in the serialization.
/// This is used internally by the netapp communication protocol.
pub fn rmp_to_vec_all_named<T>(val: &T) -> Result<Vec<u8>, rmp_serde::encode::Error>
where
	T: Serialize + ?Sized,
{
	let mut wr = Vec::with_capacity(128);
	let mut se = rmp_serde::Serializer::new(&mut wr)
		.with_struct_map()
		.with_string_variants();
	val.serialize(&mut se)?;
	Ok(wr)
}

/// This async function returns only when a true signal was received
/// from a watcher that tells us when to exit.
/// Usefull in a select statement to interrupt another
/// future:
/// ```
/// select!(
///     _ = a_long_task() => Success,
///     _ = await_exit(must_exit) => Interrupted,
/// )
/// ```
pub async fn await_exit(mut must_exit: watch::Receiver<bool>) {
	loop {
		if must_exit.recv().await == Some(true) {
			return;
		}
	}
}