fieldmasker 0.0.1

A utility for selecting and filtering response fields via field masks.
Documentation
use std::collections::BTreeMap;

/// Schema node kinds used by [`Node`].
#[derive(Clone)]
pub(crate) enum Kind {
    /// Scalar value (e.g., numbers, strings, booleans).
    Scalar,
    /// Struct/object with named fields.
    Object(BTreeMap<String, Node>),
    /// Sequence (e.g., `Vec<T>`): schema describes the element type.
    Array(Box<Node>),
    /// Map with `String` keys and uniform value type.
    Map(Box<Node>),
}

/// A schema node used to validate field masks and drive selective serialization.
///
/// Construct nodes using the builder methods below. Most users will not need to touch
/// this directly when using the `derive` feature.
#[derive(Clone)]
pub struct Node {
    pub(crate) kind: Kind,
}

/// A schema node used to validate field masks and drive selective serialization.
///
/// Construct nodes using the builder methods below. Most users will not need to touch
/// this directly when using the `derive` feature.
impl Node {
    /// Creates a scalar node.
    pub const fn scalar() -> Self {
        Self { kind: Kind::Scalar }
    }

    /// Creates an object node from `(field, node)` pairs.
    ///
    /// # Example
    /// ```
    /// # use fieldmasker::spec::Node;
    /// let user = Node::object([
    ///     ("id", Node::scalar()),
    ///     ("name", Node::scalar()),
    /// ]);
    /// ```
    pub fn object(fields: impl IntoIterator<Item = (impl Into<String>, Node)>) -> Self {
        Self {
            kind: Kind::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect()),
        }
    }

    /// Creates an array node (sequence) with the given element schema.
    pub fn array(elem: Node) -> Self {
        Self {
            kind: Kind::Array(Box::new(elem)),
        }
    }

    /// Creates a map node with `String` keys and the given value schema.
    pub fn map(val: Node) -> Self {
        Self {
            kind: Kind::Map(Box::new(val)),
        }
    }
}