Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Last active July 27, 2024 17:55
Show Gist options
  • Save jweinst1/202092d6cc56a066d177d4c74474f739 to your computer and use it in GitHub Desktop.
Save jweinst1/202092d6cc56a066d177d4c74474f739 to your computer and use it in GitHub Desktop.
graph processing in rust
use std::fmt;
use std::clone::Clone;
use std::cmp::Eq;
#[derive(Debug)]
#[derive(Eq, Hash, PartialEq)]
struct Value(String);
impl Clone for Value {
fn clone(&self) -> Self {
Value(self.0.clone())
}
}
impl Value {
fn from_str(key:&str) -> Value {
Value(key.to_string())
}
}
#[derive(Debug)]
#[derive(Eq, Hash, PartialEq)]
struct KVPair(Value, Value);
impl KVPair {
fn from_str(key:&str, val:&str) -> KVPair {
KVPair(Value::from_str(key), Value::from_str(val))
}
}
#[derive(Debug)]
struct GraphNode(Vec<KVPair>, Vec<usize>);
impl GraphNode {
fn has_kv_pair(&self, other:&KVPair) -> bool {
for pair in self.0.iter() {
if pair == other {
return true;
}
}
return false;
}
fn clear_data(&mut self) {
self.0.clear()
}
fn clear_children(&mut self) {
self.1.clear()
}
fn has_kv_pairs(&self, other:&Vec<KVPair>) -> bool {
for pair in other.iter() {
if !self.has_kv_pair(pair) {
return false;
}
}
return true;
}
fn add_pair_str(&mut self, key:&str, val:&str) {
self.0.push(KVPair::from_str(key, val))
}
fn add_child(&mut self, index:usize) {
self.1.push(index)
}
}
impl PartialEq for GraphNode {
fn eq(&self, other: &Self) -> bool {
self.has_kv_pairs(&other.0)
}
}
impl Eq for GraphNode {}
#[derive(Debug)]
struct Graph(Vec<GraphNode>);
impl Graph {
fn add(&mut self, node:GraphNode) -> usize {
self.0.push(node);
return self.0.len();
}
fn connect(&mut self, n1:usize, n2:usize) -> bool {
if n1 >= self.0.len() || n2 >= self.0.len() {
return false;
}
self.0[n1].1.push(n2);
return true;
}
fn get_nodes_with_child(&self, query:&Vec<KVPair>) -> Vec<usize> {
let mut nodes = Vec::new();
for i in 0..self.0.len() {
for child in self.0[i].1.iter() {
if self.0[*child].has_kv_pairs(query) {
nodes.push(i);
}
}
}
return nodes;
}
fn get_first_child(&self, query:&Vec<KVPair>) -> Option<usize> {
for node in self.0.iter() {
if node.has_kv_pairs(query) {
if node.1.len() > 0 {
return Some(node.1[0]);
}
}
}
return None;
}
}
fn main() {
let foo = Value::from_str("foo");
println!("{:?}", foo);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment