use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use serde::{Deserialize, Serialize};
use std::fmt;
#[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()
}
}
pub struct Node {
handle: Handle<Coords>,
id: NodeId,
}
impl Node {
pub fn create_in(coords: Handle<Coords>, coord: &[f64]) -> Result<Self> {
let id = coords.write().add_node(coord)?;
Ok(Self { handle: coords, id })
}
pub fn acquire(coords: Handle<Coords>, id: NodeId) -> Result<Self> {
coords.write().incref(id)?;
Ok(Self { handle: coords, id })
}
#[cfg(feature = "python-api")]
pub(crate) fn from_parts(handle: Handle<Coords>, id: NodeId) -> Self {
Self { handle, id }
}
pub fn id(&self) -> NodeId {
self.id
}
pub fn id_in(&self, coords: &Handle<Coords>) -> Result<NodeId> {
if self.handle.same_object(coords) {
Ok(self.id)
} else {
Err(PyrucastError::Message(format!(
"node {} belongs to another Coords",
self.id
)))
}
}
pub fn coords(&self) -> Handle<Coords> {
self.handle.clone()
}
pub fn position(&self) -> Result<Vec<f64>> {
Ok(self.handle.read().position(self.id)?.to_vec())
}
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);
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 {
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),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::handle::Handle;
#[test]
fn a_node_holds_one_unit_until_dropped() {
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.read().refcount(id), 1);
drop(n);
assert_eq!(coords.read().refcount(id), 0);
assert_eq!(coords.read().node_count(), 1);
}
#[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 #"));
}
}