//! Common functionality.

use std::collections::HashSet;

use serde::{Serialize, Serializer};

/// Serializes a [`HashSet`] of `T` as an ordered [`Vec`] of `T`.
pub(crate) fn ordered_set<S, T: Ord + Serialize>(
    value: &HashSet<T>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut ordered: Vec<_> = value.iter().collect();
    ordered.sort();
    ordered.serialize(serializer)
}

/// Returns a [`HashSet`] of `T` as an ordered [`Vec`] of `&T`.
pub(crate) fn set_to_vec<T: Ord>(value: &HashSet<T>) -> Vec<&T> {
    let mut ordered: Vec<_> = value.iter().collect();
    ordered.sort();
    ordered
}

/// Serializes an [`Option<HashSet>`] of `T` as an ordered [`Option<Vec>`] of `T`.
pub(crate) fn ordered_option_set<S, T: Ord + Serialize>(
    value: &Option<HashSet<T>>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(value) = value {
        let mut ordered: Vec<_> = value.iter().collect();
        ordered.sort();
        Some(ordered).serialize(serializer)
    } else {
        (None as Option<&HashSet<T>>).serialize(serializer)
    }
}
