type_weave/
lib.rs

1//! A library for merging layered data.
2//!
3//! This crate is primarily intended for helping with configuration,
4//! as multiple instances of a struct may need to be joined in a layered fashion.
5//!
6//! See [`Weave`] for more information on its usage and default type implementations.
7//!
8//! # Features
9//!
10//! The `derive` feature (enabled by default) adds a derive macro for `Weave`,
11//! which implements the trait for structs entirely composed of fields that
12//! also implement the trait.
13//!
14//! [`Weave`]: crate::Weave
15
16#[cfg(feature = "derive")]
17pub use type_weave_derive::Weave;
18
19/// Trait for layered type merging.
20pub trait Weave<T = Self> {
21    /// Merge the values, prioritizing `self`.
22    ///
23    /// # Example
24    /// ```
25    /// # use type_weave::Weave;
26    /// # fn main() {
27    /// let a = Some("a");
28    /// let b = Some("b");
29    ///
30    /// assert_eq!(a.over(b), Some("a"));
31    /// # }
32    fn over(self, other: T) -> Self;
33
34    /// Merge the values, prioritizing `other`.
35    ///
36    /// # Example
37    /// ```
38    /// # use type_weave::Weave;
39    /// # fn main() {
40    /// let a = Some("a");
41    /// let b = Some("b");
42    ///
43    /// assert_eq!(a.under(b), Some("b"));
44    /// # }
45    fn under(self, other: T) -> Self;
46}
47
48impl Weave for bool {
49    fn over(self, other: Self) -> Self {
50        self || other
51    }
52
53    fn under(self, other: Self) -> Self {
54        self || other
55    }
56}
57
58impl<T> Weave for Option<T> {
59    fn over(self, other: Self) -> Self {
60        self.or(other)
61    }
62
63    fn under(self, other: Self) -> Self {
64        other.or(self)
65    }
66}