Skip to main content

ratio_graph/
serde_utils.rs

1//! # Serde utilities
2//!
3//! ## License
4//!
5//! This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
6//! If a copy of the MPL was not distributed with this file,
7//! You can obtain one at <https://mozilla.org/MPL/2.0/>.
8//!
9//! **Code examples both in the docstrings and rendered documentation are free to use.**
10
11use std::collections::{BTreeMap, BTreeSet};
12
13/// Whether a value equals its type's default.
14pub fn is_default<T: Default + PartialEq>(t: &T) -> bool {
15    t == &T::default()
16}
17
18/// Whether a vec is empty.
19pub fn is_empty_vec<T>(t: &[T]) -> bool {
20    t.is_empty()
21}
22
23/// Whether a set is empty.
24pub fn is_empty_set<T>(t: &BTreeSet<T>) -> bool {
25    t.is_empty()
26}
27
28/// Whether a map is empty.
29pub fn is_empty_map<K, V>(t: &BTreeMap<K, V>) -> bool {
30    t.is_empty()
31}
32
33/// Helper for serializing maps with consistent ordering.
34pub fn sort_alphabetically<T: serde::Serialize, S: serde::Serializer>(
35    value: &T,
36    serializer: S,
37) -> Result<S::Ok, S::Error> {
38    let value = serde_json::to_value(value).map_err(serde::ser::Error::custom)?;
39    serde::Serialize::serialize(&value, serializer)
40}