pyrucast 0.7.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
//! Node — RAII accessor to a node of a [`Coords`].
//!
//! `Node` is the **user-facing interface** to a node: it holds a handle to
//! its `Coords` and a node id, and automatically maintains the
//! **internal** node refcount (`Clone` increments, `Drop` decrements). As
//! long as at least one `Node` exists, the node is protected from the
//! `Coords`'s garbage collector.
//!
//! Internal code can still manipulate [`crate::atoms::NodeId`]
//! values directly, but then loses the automatic GC protection: it must
//! call [`Coords::incref`](crate::coords::Coords::incref) /
//! [`Coords::decref`](crate::coords::Coords::decref)
//! by hand.
//!
//! # Example
//!
//! ```
//! use pyrucast::coords::Coords;
//! use pyrucast::atoms::Node;
//! use pyrucast::handle::Handle;
//!
//! let coords = Handle::new(Coords::new(2).unwrap());
//! let n = Node::create_in(coords.clone(), &[1.0, 2.0]).unwrap();
//! assert_eq!(n.position().unwrap(), vec![1.0, 2.0]);
//!
//! // The GC does not touch a node that a live Node still references.
//! assert_eq!(coords.write().gc(), 0);
//!
//! let id = n.id();
//! drop(n);
//! // Now the refcount is 0; gc collects.
//! assert_eq!(coords.write().gc(), 1);
//! assert!(!coords.read().is_alive(id));
//! ```

use crate::coords::Coords;
use crate::error::Result;
use crate::handle::Handle;
use serde::{Deserialize, Serialize};
use std::fmt;

/// Stable internal identifier of a node inside a `Coords`.
///
/// ```
/// # use pyrucast::atoms::NodeId;
/// // Un identifiant nu : il circule partout, sans porter le magasin.
/// let id = NodeId(3);
/// assert_eq!(id.0, 3);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct NodeId(pub u32);

impl fmt::Debug for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "NodeId({})", self.0)
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl crate::dump::Dump for NodeId {
    fn render(&self, _opts: &crate::dump::DumpOptions) -> String {
        self.to_string()
    }
}

/// RAII accessor to a node of a `Coords`.
///
/// ```
/// # use pyrucast::atoms::Node;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// let coords = Handle::new(Coords::new(2).unwrap());
/// let n = Node::create_in(coords.clone(), &[1.0, 2.0]).unwrap();
///
/// // Un `Node` est un **ticket** : tant qu'il vit, le nœud survit au gc.
/// assert_eq!(coords.write().gc(), 0);
/// drop(n);
/// assert_eq!(coords.write().gc(), 1);
/// ```
pub struct Node {
    handle: Handle<Coords>,
    id: NodeId,
}

impl Node {
    /// Add a new node to the pointed `Coords` and return a `Node`
    /// referencing it (refcount = 1).
    ///
    /// ```
    /// # use pyrucast::atoms::Node;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// let n = Node::create_in(coords.clone(), &[1.0, 2.0]).unwrap();
    /// assert_eq!(n.position().unwrap(), vec![1.0, 2.0]);
    /// ```
    pub fn create_in(coords: Handle<Coords>, coord: &[f64]) -> Result<Self> {
        // `add_node` initializes refcount = 1; this Node takes that unit.
        let id = coords.write().add_node(coord)?;
        Ok(Self { handle: coords, id })
    }

    /// Build an additional `Node` for an existing id (refcount += 1).
    ///
    /// ```
    /// # use pyrucast::atoms::Node;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// let n = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
    /// // Un second accesseur sur le même id : le nœud a maintenant deux tickets.
    /// let m = Node::acquire(coords.clone(), n.id()).unwrap();
    /// assert_eq!(m.id(), n.id());
    /// ```
    pub fn acquire(coords: Handle<Coords>, id: NodeId) -> Result<Self> {
        coords.write().incref(id)?;
        Ok(Self { handle: coords, id })
    }

    /// Build a `Node` from a handle and an id that have **already been
    /// incremented** on the Coords side. Internal escape hatch used
    /// by FFI wrappers that have already paid the refcount increment.
    #[cfg(feature = "python-api")]
    pub(crate) fn from_parts(handle: Handle<Coords>, id: NodeId) -> Self {
        Self { handle, id }
    }

    /// Internal identifier of the node.
    ///
    /// ```
    /// # use pyrucast::atoms::Node;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// let n = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
    /// let m = Node::create_in(coords, &[1.0, 0.0]).unwrap();
    /// assert_ne!(n.id(), m.id()); // ids distincts, attribués à la création
    /// ```
    pub fn id(&self) -> NodeId {
        self.id
    }

    /// Handle to the owning `Coords` (internal clone).
    ///
    /// ```
    /// # use pyrucast::atoms::Node;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # use pyrucast::handle::Handle as H;
    /// let n = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
    /// // Le nœud porte son magasin : aucun argument `Coords` ailleurs.
    /// assert!(H::same_object(&n.coords(), &coords));
    /// ```
    pub fn coords(&self) -> Handle<Coords> {
        self.handle.clone()
    }

    /// Coordinates (copied) in the `Coords`'s active set.
    ///
    /// ```
    /// # use pyrucast::atoms::Node;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// let n = Node::create_in(coords, &[1.5, -2.0]).unwrap();
    /// assert_eq!(n.position().unwrap(), vec![1.5, -2.0]);
    /// ```
    pub fn position(&self) -> Result<Vec<f64>> {
        Ok(self.handle.read().position(self.id)?.to_vec())
    }

    /// Set the coordinates of the node in the active set.
    ///
    /// ```
    /// # use pyrucast::atoms::Node;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// let n = Node::create_in(coords, &[0.0, 0.0]).unwrap();
    /// n.set_position(&[3.0, 4.0]).unwrap();
    /// assert_eq!(n.position().unwrap(), vec![3.0, 4.0]);
    /// ```
    pub fn set_position(&self, coords: &[f64]) -> Result<()> {
        self.handle.write().set_position(self.id, coords)?;
        Ok(())
    }
}

impl Clone for Node {
    fn clone(&self) -> Self {
        let _ = self.handle.write().incref(self.id);
        Self {
            handle: self.handle.clone(),
            id: self.id,
        }
    }
}

impl Drop for Node {
    fn drop(&mut self) {
        let _ = self.handle.write().decref(self.id);
    }
}

impl fmt::Debug for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("Node");
        s.field("id", &self.id).field("handle", &self.handle);
        // Debug may take the lock to surface the actual values (Display
        // stays lock-free). If the node is no longer reachable, fall back
        // to the error rather than failing to format.
        match self.position() {
            Ok(coord) => s.field("position", &coord),
            Err(e) => s.field("position", &format_args!("<{e}>")),
        };
        s.finish()
    }
}

impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Display stays lock-free; use Debug or `position()` for the values.
        write!(f, "<Node #{}>", self.id)
    }
}

impl crate::dump::Dump for Node {
    fn render(&self, opts: &crate::dump::DumpOptions) -> String {
        match self.position() {
            Ok(c) => {
                let coords: Vec<String> = c
                    .iter()
                    .map(|v| crate::dump::fmt_float(*v, opts.precision))
                    .collect();
                format!("Node #{} @ ({})", self.id, coords.join(", "))
            }
            Err(e) => format!("Node #{} <{e}>", self.id),
        }
    }
}

// ─── Unit tests ─────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handle::Handle;

    #[test]
    fn node_protects_from_gc() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let n = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let id = n.id();
        assert_eq!(coords.write().gc(), 0);
        assert!(coords.read().is_alive(id));
        drop(n);
        assert_eq!(coords.write().gc(), 1);
        assert!(!coords.read().is_alive(id));
    }

    #[test]
    fn clone_and_drop_maintain_refcount() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let id = n.id();
        let m = n.clone();
        assert_eq!(coords.read().refcount(id), 2);
        drop(n);
        assert_eq!(coords.read().refcount(id), 1);
        drop(m);
        assert_eq!(coords.read().refcount(id), 0);
    }

    #[test]
    fn acquire_shares_same_id() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n = Node::create_in(coords.clone(), &[7.0]).unwrap();
        let id = n.id();
        let m = Node::acquire(coords.clone(), id).unwrap();
        assert_eq!(n.id(), m.id());
        assert_eq!(coords.read().refcount(id), 2);
        drop(n);
        drop(m);
        assert_eq!(coords.read().refcount(id), 0);
    }

    #[test]
    fn position_and_set_position() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let n = Node::create_in(coords, &[1.0, 2.0]).unwrap();
        assert_eq!(n.position().unwrap(), vec![1.0, 2.0]);
        n.set_position(&[5.0, 6.0]).unwrap();
        assert_eq!(n.position().unwrap(), vec![5.0, 6.0]);
    }

    #[test]
    fn debug_and_display() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let n = Node::create_in(coords, &[1.5, 2.5]).unwrap();
        let d = format!("{:?}", n);
        assert!(d.contains("Node"));
        assert!(d.contains("position"));
        assert!(d.contains("1.5") && d.contains("2.5"));
        let s = format!("{}", n);
        assert!(s.starts_with("<Node #"));
    }
}