Struct sodg::Sodg

source ·
pub struct Sodg { /* private fields */ }
Expand description

A struct that represents a Surging Object Di-Graph (SODG).

You add vertices to it, bind them one to one with edges, put data into some of them, and read data back, for example:

use sodg::Sodg;
use sodg::DeadRelay;
let mut sodg = Sodg::empty();
sodg.add(0).unwrap();
sodg.add(1).unwrap();
sodg.bind(0, 1, "a").unwrap();
sodg.add(2).unwrap();
sodg.bind(1, 2, "b").unwrap();
assert_eq!(2, sodg.find(0, "a.b", &mut DeadRelay::default()).unwrap());

This package is used in reo project, as a memory model for objects and dependencies between them.

Implementations§

source§

impl Sodg

source

pub fn alert_on(&mut self, a: Alert)

Attach a new alert to this graph.

For example, you don’t want more than one edge to depart from any vertex:

use sodg::Sodg;
let mut g = Sodg::empty();
g.alerts_on().unwrap();
g.alert_on(|g, vx| {
  for v in vx {
    if g.kids(v).unwrap().len() > 1 {
      return vec![format!("Too many kids at ν{v}")];
    }
  }
  return vec![];
});
g.add(0).unwrap();
g.add(1).unwrap();
g.add(2).unwrap();
g.bind(0, 1, "first").unwrap();
assert!(g.bind(0, 2, "second").is_err());
source

pub fn alerts_off(&mut self)

Disable all alerts.

source

pub fn alerts_on(&mut self) -> Result<()>

Enable all alerts.

This function also runs all vertices through all checks and returns the list of errors found. If everything was fine, an empty vector is returned.

Errors

An error may be returned if validation fails, after the alerts are turned ON.

source

pub fn validate(&self, vx: Vec<u32>) -> Result<()>

Check all alerts for the given list of vertices.

Errors

If any of them have any issues, Err is returned.

source§

impl Sodg

source

pub fn empty() -> Self

Make an empty Sodg, with no vertices and no edges.

Panics

May panic if vertices provided to alerts are absent (should never happen, though).

source§

impl Sodg

source

pub fn v_print(&self, v: u32) -> Result<String>

Print a single vertex to a string, which can be used for logging and debugging.

Errors

If the vertex is absent, an error may be returned.

source§

impl Sodg

source

pub fn to_dot(&self) -> String

Print SODG as a DOT graph.

For example, for this code:

use sodg::Hex;
use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.put(0, &Hex::from_str_bytes("hello")).unwrap();
g.add(1).unwrap();
g.bind(0, 1, "foo").unwrap();
g.bind(0, 1, "bar").unwrap();
let dot = g.to_dot();
println!("{}", dot);

The printout will look approximately like this:

digraph {
  v0[shape=circle,label="ν0"];
  v0 -> v1 [label="bar"];
  v0 -> v1 [label="foo"];
  v1[shape=circle,label="ν1"];
}
source§

impl Sodg

source

pub fn find<T: Relay>(&self, v1: u32, loc: &str, relay: &T) -> Result<u32>

Find a vertex in the Sodg by its locator using a Relay to provide alternative edge names, if the desired ones are not found.

For example, here is how LambdaRelay may be used with a “relaying” function:

use sodg::Sodg;
use sodg::DeadRelay;
use sodg::LambdaRelay;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.add(1).unwrap();
g.bind(0, 1, "foo").unwrap();
assert!(g.find(0, "bar", &DeadRelay::default()).is_err());
let v = g.find(0, "bar", &LambdaRelay::new(|v, a| {
  assert_eq!(a, "bar");
  Ok("foo".to_string())
})).unwrap();
assert_eq!(1, v);
Errors

If v1 is absent, an Err will be returned.

If searching algorithm fails to find the destination, an Err will be returned.

source§

impl Sodg

source

pub fn inspect(&self, loc: &str) -> Result<String>

Find an object by the provided locator and print its tree of sub-objects and edges.

The function is mostly used for testing.

Errors

If it’s impossible to inspect, an error will be returned.

source§

impl Sodg

source

pub fn merge(&mut self, g: &Self, left: u32, right: u32) -> Result<()>

Merge another graph into the current one.

It is expected that both graphs are trees! If they are not, the result is unpredictable.

The right vertex is mapped to the left vertex. The decisions about their kids are made recursively.

The left vertex is expected to be the root of the current graph, while the right vertex is the root of the graph being merged into the current one.

Errors

If it’s impossible to merge, an error will be returned.

source§

impl Sodg

source

pub fn len(&self) -> usize

Get total number of vertices in the graph.

source

pub fn ids(&self) -> Vec<u32>

Get all IDs of vertices, in a vector.

source

pub fn is_empty(&self) -> bool

Is it empty?

Emptiness means that not a single vertex is in the graph.

For example:

use sodg::Sodg;
let mut sodg = Sodg::empty();
sodg.add(0).unwrap();
sodg.add(42).unwrap();
sodg.bind(0, 42, "hello").unwrap();
source§

impl Sodg

source

pub fn next_id(&mut self) -> u32

Get next unique ID of a vertex.

This ID will never be returned by [next_id()] again. Also, this ID will not be equal to any of the existing IDs of vertices.

source§

impl Sodg

source

pub fn add(&mut self, v1: u32) -> Result<()>

Add a new vertex v1 to itself.

For example:

use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.add(42).unwrap();
g.bind(0, 42, "hello").unwrap();

If vertex v1 already exists in the graph, Ok will be returned.

Errors

If alerts trigger any error, the error will be returned here.

source

pub fn bind(&mut self, v1: u32, v2: u32, a: &str) -> Result<()>

Make an edge e1 from vertex v1 to vertex v2 and put a label on it.

For example:

use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.add(42).unwrap();
g.bind(0, 42, "forward").unwrap();
g.bind(42, 0, "backward").unwrap();

If an edge with this label already exists, it will be replaced with a new edge.

Errors

If either vertex v1 or v2 is absent, an Err will be returned.

If v1 equals to v2, an Err will be returned.

The label a can’t be empty. If it is empty, an Err will be returned.

If alerts trigger any error, the error will be returned here.

source

pub fn put(&mut self, v: u32, d: &Hex) -> Result<()>

Set vertex data.

For example:

use sodg::Hex;
use sodg::Sodg;
let mut g = Sodg::empty();
g.add(42).unwrap();
g.put(42, &Hex::from_str_bytes("hello, world!")).unwrap();
Errors

If vertex v1 is absent, an Err will be returned.

If alerts trigger any error, the error will be returned here.

source

pub fn data(&mut self, v: u32) -> Result<Hex>

Read vertex data, and then submit the vertex to garbage collection.

For example:

use sodg::Hex;
use sodg::Sodg;
let mut g = Sodg::empty();
g.add(42).unwrap();
let data = Hex::from_str_bytes("hello, world!");
g.put(42, &data).unwrap();
assert_eq!(data, g.data(42).unwrap());
#[cfg(feature = "gc")]
assert!(g.is_empty());

If there is no data, an empty Hex will be returned, for example:

use sodg::Sodg;
let mut g = Sodg::empty();
g.add(42).unwrap();
assert!(g.data(42).unwrap().is_empty());
Errors

If vertex v1 is absent, an Err will be returned.

If garbage collection triggers any error, the error will be returned here.

source

pub fn kids(&self, v: u32) -> Result<Vec<(String, u32)>>

Find all kids of a vertex.

For example:

use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.add(42).unwrap();
g.bind(0, 42, "k").unwrap();
let (a, to) = g.kids(0).unwrap().first().unwrap().clone();
assert_eq!("k", a);
assert_eq!(42, to);

Just in case, if you need to put all names into a single line:

use itertools::Itertools;
use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.add(42).unwrap();
g.bind(0, 42, "a").unwrap();
g.bind(0, 42, "b").unwrap();
g.bind(0, 42, "c").unwrap();
assert_eq!("a,b,c", g.kids(0).unwrap().into_iter().map(|(a, _)| a).collect::<Vec<String>>().join(","));
Errors

If vertex v1 is absent, Err will be returned.

source

pub fn kid(&self, v: u32, a: &str) -> Option<u32>

Find a kid of a vertex, by its edge name, and return the ID of the vertex found.

For example:

use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.add(42).unwrap();
g.bind(0, 42, "k").unwrap();
assert_eq!(42, g.kid(0, "k").unwrap());

If vertex v1 is absent, None will be returned.

source§

impl Sodg

source

pub fn save(&self, path: &Path) -> Result<usize>

Save the entire Sodg into a binary file.

The entire Sodg can be restored from the file. The function returns the size of the file just saved. In order to restore from the file, use Sodg::load.

Errors

If impossible to save, an error will be returned.

source

pub fn load(path: &Path) -> Result<Self>

Load the entire Sodg from a binary file previously created by Sodg::save.

Errors

If impossible to load, an error will be returned.

source§

impl Sodg

source

pub fn slice(&self, loc: &str) -> Result<Self>

Take a slice of the graph, keeping only the vertex specified by the locator and its kids, recursively found in the entire graph.

Errors

If impossible to slice, an error will be returned.

source

pub fn slice_some( &self, loc: &str, p: impl Fn(u32, u32, String) -> bool ) -> Result<Self>

Take a slice of the graph, keeping only the vertex specified by the locator and its kids, recursively found in the entire graph, but only if the provided predicate agrees with the selection of the kids.

Errors

If impossible to slice, an error will be returned.

source§

impl Sodg

source

pub fn to_xml(&self) -> Result<String>

Make XML graph.

For example, for this code:

use sodg::Hex;
use sodg::Sodg;
let mut g = Sodg::empty();
g.add(0).unwrap();
g.put(0, &Hex::from_str_bytes("hello")).unwrap();
g.add(1).unwrap();
g.bind(0, 1, "foo").unwrap();
g.bind(0, 1, "bar").unwrap();
let xml = g.to_xml().unwrap();
println!("{}", xml);

The printout will look like this:

<?xml version="1.1" encoding="UTF-8"?>
<sodg>
    <v id="0">
        <e a="foo" to="1" />
        <e a="bar" to="1" />
        <data>68 65 6C 6C 6F</data>
    </v>
    <v id="1" />
</sodg>
Errors

If it’s impossible to print it to XML, an Err may be returned. Problems may also be caused by XML errors from the XML builder library.

Trait Implementations§

source§

impl Clone for Sodg

source§

fn clone(&self) -> Self

Make a clone of the graph.

1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Sodg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for Sodg

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Sodg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Serialize for Sodg

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl RefUnwindSafe for Sodg

§

impl Send for Sodg

§

impl Sync for Sodg

§

impl Unpin for Sodg

§

impl UnwindSafe for Sodg

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,