alpm_srcinfo/source_info/helper.rs
1use std::collections::HashSet;
2
3use serde::{Serialize, Serializer};
4
5/// Serializes a [`HashSet`] as [`Vec`].
6///
7/// Converts `value` to a `Vec<T>` and calls `Vec::sort_unstable` on it.
8/// This is necessary to guarantee idempotent ordering in serialized output.
9///
10/// We use `sort_unstable`, as we know that all elements are unique.
11///
12/// # Errors
13///
14/// Returns an error if serializing the `Vec<T>` fails.
15pub fn ordered_hashset<S, V: Serialize + Ord>(
16 value: &HashSet<V>,
17 serializer: S,
18) -> Result<S::Ok, S::Error>
19where
20 S: Serializer,
21{
22 let mut list: Vec<&V> = value.iter().collect();
23 list.sort_unstable();
24 list.serialize(serializer)
25}
26
27/// Serializes an `Override<HashSet<V>>` as `Override<Vec<V>>`.
28///
29/// Converts `value` to an `Override<Vec<V>>` and calls `Vec::sort_unstable` on it.
30/// This is necessary to guarantee idempotent ordering in the serialized output.
31///
32/// We use `sort_unstable`, as we know that all elements are unique.
33///
34/// # Errors
35///
36/// Returns an error if serializing the `Override<Vec<V>>` fails.
37pub fn ordered_optional_hashset<S, V: Serialize + Ord>(
38 value: &Option<HashSet<V>>,
39 serializer: S,
40) -> Result<S::Ok, S::Error>
41where
42 S: Serializer,
43{
44 match value {
45 Option::None => value.serialize(serializer),
46 Option::Some(value) => {
47 let mut list: Vec<&V> = value.iter().collect();
48 list.sort_unstable();
49 let option = Some(value);
50 option.serialize(serializer)
51 }
52 }
53}