Skip to main content

altium_format/traits/
params.rs

1//! Parameter-based serialization traits for schematic records.
2
3use crate::error::Result;
4use crate::types::{ParameterCollection, UnknownFields};
5
6/// Import a type from a parameter collection.
7///
8/// This trait is automatically implemented by the `AltiumRecord` and `AltiumBase`
9/// derive macros for parameter-based record types.
10pub trait FromParams: Sized {
11    /// Parse this type from a parameter collection.
12    fn from_params(params: &ParameterCollection) -> Result<Self>;
13
14    /// Parse this type and collect unknown parameters for non-destructive editing.
15    fn from_params_preserving(params: &ParameterCollection) -> Result<(Self, UnknownFields)> {
16        let value = Self::from_params(params)?;
17        Ok((value, UnknownFields::default()))
18    }
19}
20
21/// Export a type to a parameter collection.
22///
23/// This trait is automatically implemented by the `AltiumRecord` and `AltiumBase`
24/// derive macros for parameter-based record types.
25pub trait ToParams {
26    /// Export this type to a new parameter collection.
27    fn to_params(&self) -> ParameterCollection {
28        let mut params = ParameterCollection::new();
29        self.append_to_params(&mut params);
30        params
31    }
32
33    /// Append this type's parameters to an existing collection.
34    ///
35    /// This is used for composition - base types append their fields first,
36    /// then derived types append their own fields.
37    fn append_to_params(&self, params: &mut ParameterCollection);
38}
39
40// Blanket implementations for Option<T>
41impl<T: FromParams> FromParams for Option<T> {
42    fn from_params(params: &ParameterCollection) -> Result<Self> {
43        // For Option, we try to parse but return None on any failure
44        match T::from_params(params) {
45            Ok(v) => Ok(Some(v)),
46            Err(_) => Ok(None),
47        }
48    }
49}
50
51impl<T: ToParams> ToParams for Option<T> {
52    fn append_to_params(&self, params: &mut ParameterCollection) {
53        if let Some(v) = self {
54            v.append_to_params(params);
55        }
56    }
57}