//! Serde support for serializing Rust collections as Preserves sets.
//!
//! Serde doesn't include sets in its data model, so we do some somewhat awful tricks to force
//! things to come out the way we want them.
//!
//! # Example
//!
//! Annotate collection-valued fields that you want to (en|de)code as Preserves `Set`s with
//! `#[serde(with = "preserves::set")]`:
//!
//! ```rust
//! #[derive(serde::Serialize, serde::Deserialize)]
//! struct Example {
//!   #[serde(with = "preserves::set")]
//!   items: preserves::value::Set<String>,
//! }
//! ```

use crate::value::{self, to_value, IOValue, UnwrappedIOValue};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::iter::IntoIterator;

#[doc(hidden)]
pub fn serialize<S, T, Item>(s: T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: IntoIterator<Item = Item>,
    Item: Serialize,
{
    let s = s.into_iter().map(to_value).collect::<value::Set<IOValue>>();
    UnwrappedIOValue::from(s).wrap().serialize(serializer)
}

#[doc(hidden)]
pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    // Relies on the way we hack around serde's data model in de.rs and value/de.rs.
    T::deserialize(deserializer)
}
