clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 1 MCard Marking State Models (Sprint 509, 551).

use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};

use crate::cpn::mcard_token::{
    qualified_record_hash, record_from_canonical_json, DEFAULT_TIMESTAMP,
};

/// Lossless canonical multiset marking `PlaceId -> Vec<QualifiedMCardRef>` (`a:hex`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct MCardMarking {
    /// Token reference lists indexed by place ID.
    pub by_place: BTreeMap<String, Vec<String>>,
}

impl<'de> Deserialize<'de> for MCardMarking {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum MarkingHelper {
            Wrapped { by_place: BTreeMap<String, Vec<String>> },
            Transparent(BTreeMap<String, Vec<String>>),
        }

        let helper = MarkingHelper::deserialize(deserializer)?;
        match helper {
            MarkingHelper::Wrapped { by_place } => Ok(MCardMarking { by_place }),
            MarkingHelper::Transparent(by_place) => Ok(MCardMarking { by_place }),
        }
    }
}

impl MCardMarking {
    /// Creates an empty `MCardMarking`.
    pub fn new() -> Self {
        Self { by_place: BTreeMap::new() }
    }

    /// Builder method to append a token reference to `place_id`.
    pub fn with_token(mut self, place_id: &str, token_ref: &str) -> Self {
        self.append(place_id, token_ref.to_string());
        self
    }

    /// Restricts this marking to a subset of place IDs.
    pub fn restrict(&self, place_ids: &BTreeSet<String>) -> Self {
        let mut by_place = BTreeMap::new();
        for pid in place_ids {
            if let Some(vals) = self.by_place.get(pid) {
                by_place.insert(pid.clone(), vals.clone());
            }
        }
        Self { by_place }
    }

    /// Returns the multiset mapping indexed by place ID (compatible with sheaf Marking).
    pub fn tokens(&self) -> &BTreeMap<String, Vec<String>> {
        &self.by_place
    }

    /// Returns the ordered list of qualified token references at `place_id`.
    pub fn place_refs(&self, place_id: &str) -> Vec<String> {
        self.by_place.get(place_id).cloned().unwrap_or_default()
    }

    /// Alias for `place_refs(place_id)` returning token references at `place_id`.
    pub fn tokens_at(&self, place_id: &str) -> Vec<String> {
        self.place_refs(place_id)
    }

    /// Returns the current token count at `place_id`.
    pub fn count(&self, place_id: &str) -> usize {
        self.by_place.get(place_id).map(|v| v.len()).unwrap_or(0)
    }

    /// Projects the multiset marking into an integer occupancy map `PlaceId -> usize`.
    pub fn token_counts(&self) -> BTreeMap<String, usize> {
        self.by_place.iter().map(|(k, v)| (k.clone(), v.len())).collect()
    }

    /// Appends `qualified_ref` to `place_id`.
    pub fn append(&mut self, place_id: &str, qualified_ref: String) {
        self.by_place.entry(place_id.to_string()).or_default().push(qualified_ref);
    }

    /// Pops and returns the first token reference from `place_id`, if non-empty.
    pub fn pop_first(&mut self, place_id: &str) -> Option<String> {
        let vec = self.by_place.get_mut(place_id)?;
        if vec.is_empty() { None } else { Some(vec.remove(0)) }
    }

    /// Computes a deterministic `a:hex` state hash over the canonical marking JSON.
    pub fn state_hash(&self, algorithm: Option<&str>) -> Result<String, String> {
        let val = serde_json::to_value(&self.by_place)
            .map_err(|e| format!("Failed to serialize MCardMarking: {e}"))?;
        let rec = record_from_canonical_json(&val, algorithm, Some(DEFAULT_TIMESTAMP))?;
        Ok(qualified_record_hash(&rec))
    }
}