capability-skeleton 0.1.0

A Rust library for managing and building complex hierarchical tree structures such as skill trees. Supports serialization, error handling, and deep tree metrics.
Documentation
// ---------------- [ File: capability-skeleton/src/skeleton.rs ]
crate::ix!();

/// The entire skeleton, storing a list of nodes plus an optional root_id.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder, Default, Setters, MutGetters, Getters)]
#[builder(pattern="owned", setter(into))]
#[getset(get="pub", get_mut="pub", set="pub")]
pub struct Skeleton {

    /// This field holds *verbatim* the lower-kebab-case target-name belonging to the tree grow process.
    #[builder(default = "\"target\".to_string()")]
    target_name: String,

    /// The nodes in this skeleton
    #[builder(default)]
    nodes: Vec<SkeletonNode>,

    /// The root node’s ID, if any
    #[builder(default)]
    root_id: Option<u16>,
}

impl Skeleton {
    #[instrument(level="trace", skip(path))]
    pub fn from_toml_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, SkeletonError> {
        tracing::trace!("Reading Skeleton from TOML file: {:?}", path.as_ref());
        let text = std::fs::read_to_string(path)?;
        let skeleton = toml::from_str::<Self>(&text)
            .map_err(SkeletonError::TomlError)?;
        Ok(skeleton)
    }

    #[instrument(level="trace", skip(self, path))]
    pub fn to_toml_file<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), SkeletonError> {
        tracing::trace!("Writing Skeleton to TOML file: {:?}", path.as_ref());
        let serialized = toml::to_string_pretty(self)
            .map_err(SkeletonError::TomlWriteError)?;
        std::fs::write(path, serialized)?;
        Ok(())
    }

    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    pub fn root_node(&self) -> Option<&SkeletonNode> {
        self.root_id
            .and_then(|rid| self.nodes.iter().find(|n| n.id() == rid))
    }
}