littlegraph-core 0.2.1

Embedded openCypher graph database backed by Neo4j record storage
Documentation
use std::collections::BTreeMap;

use crate::error::{Error, Result};

#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Value {
    Null,
    Boolean(bool),
    Integer(i64),
    Float(f64),
    String(String),
    List(Vec<Value>),
    Map(BTreeMap<String, Value>),
    Node(NodeValue),
    Relationship(RelationshipValue),
    Path(PathValue),
}

#[derive(Clone, Debug, PartialEq)]
pub struct NodeValue {
    /// Numeric Neo4j node record identity, when this value represents a stored node.
    pub record_id: Option<u64>,
    pub id: String,
    pub labels: Vec<String>,
    pub properties: Properties,
}

#[derive(Clone, Debug, PartialEq)]
pub struct RelationshipValue {
    /// Numeric Neo4j relationship record identity, when this value is stored.
    pub record_id: Option<u64>,
    /// Numeric Neo4j record identity of the stored start node.
    pub start_record_id: Option<u64>,
    /// Numeric Neo4j record identity of the stored end node.
    pub end_record_id: Option<u64>,
    pub id: String,
    pub start: String,
    pub end: String,
    pub r#type: String,
    pub properties: Properties,
}

#[derive(Clone, Debug, PartialEq)]
pub struct PathValue {
    pub nodes: Vec<NodeValue>,
    pub relationships: Vec<RelationshipValue>,
}

impl NodeValue {
    pub fn new(id: String, labels: Vec<String>, properties: Properties) -> Self {
        Self {
            record_id: None,
            id,
            labels,
            properties,
        }
    }

    pub fn stored(record_id: u64, id: String, labels: Vec<String>, properties: Properties) -> Self {
        Self {
            record_id: Some(record_id),
            id,
            labels,
            properties,
        }
    }
}

impl RelationshipValue {
    pub fn new(
        id: String,
        start: String,
        end: String,
        r#type: String,
        properties: Properties,
    ) -> Self {
        Self {
            record_id: None,
            start_record_id: None,
            end_record_id: None,
            id,
            start,
            end,
            r#type,
            properties,
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn stored(
        record_id: u64,
        start_record_id: u64,
        end_record_id: u64,
        id: String,
        start: String,
        end: String,
        r#type: String,
        properties: Properties,
    ) -> Self {
        Self {
            record_id: Some(record_id),
            start_record_id: Some(start_record_id),
            end_record_id: Some(end_record_id),
            id,
            start,
            end,
            r#type,
            properties,
        }
    }
}

impl Value {
    pub fn from_json(value: serde_json::Value) -> Result<Self> {
        match value {
            serde_json::Value::Null => Ok(Value::Null),
            serde_json::Value::Bool(value) => Ok(Value::Boolean(value)),
            serde_json::Value::Number(value) => number_from_json(value),
            serde_json::Value::String(value) => Ok(Value::String(value)),
            serde_json::Value::Array(values) => values
                .into_iter()
                .map(Value::from_json)
                .collect::<Result<Vec<_>>>()
                .map(Value::List),
            serde_json::Value::Object(values) => values
                .into_iter()
                .map(|(key, value)| Value::from_json(value).map(|value| (key, value)))
                .collect::<Result<BTreeMap<_, _>>>()
                .map(Value::Map),
        }
    }
}

fn number_from_json(value: serde_json::Number) -> Result<Value> {
    if let Some(integer) = value.as_i64() {
        return Ok(Value::Integer(integer));
    }

    let raw = value.to_string();
    if value.as_u64().is_some() || !raw.contains(['.', 'e', 'E']) {
        return Err(Error::DataLoad(format!("unsupported JSON number {value}")));
    }

    value
        .as_f64()
        .map(Value::Float)
        .ok_or_else(|| Error::DataLoad(format!("unsupported JSON number {value}")))
}

pub type Properties = BTreeMap<String, Value>;

const BTREE_ENTRY_OVERHEAD: usize = 3 * std::mem::size_of::<usize>();

pub(crate) fn estimated_properties_heap_bytes(properties: &Properties) -> Option<usize> {
    let mut bytes = 0_usize;
    for (key, value) in properties {
        bytes = bytes
            .checked_add(std::mem::size_of::<String>())?
            .checked_add(std::mem::size_of::<Value>())?
            .checked_add(BTREE_ENTRY_OVERHEAD)?
            .checked_add(key.len())?
            .checked_add(value.estimated_heap_bytes()?)?;
    }
    Some(bytes)
}

impl Value {
    pub(crate) fn estimated_heap_bytes(&self) -> Option<usize> {
        match self {
            Self::Null | Self::Boolean(_) | Self::Integer(_) | Self::Float(_) => Some(0),
            Self::String(value) => Some(value.len()),
            Self::List(values) => {
                let mut bytes = values.len().checked_mul(std::mem::size_of::<Value>())?;
                for value in values {
                    bytes = bytes.checked_add(value.estimated_heap_bytes()?)?;
                }
                Some(bytes)
            }
            Self::Map(values) => estimated_properties_heap_bytes(values),
            Self::Node(node) => estimated_node_value_heap_bytes(node),
            Self::Relationship(relationship) => {
                estimated_relationship_value_heap_bytes(relationship)
            }
            Self::Path(path) => {
                let mut bytes = path
                    .nodes
                    .len()
                    .checked_mul(std::mem::size_of::<NodeValue>())?
                    .checked_add(
                        path.relationships
                            .len()
                            .checked_mul(std::mem::size_of::<RelationshipValue>())?,
                    )?;
                for node in &path.nodes {
                    bytes = bytes.checked_add(estimated_node_value_heap_bytes(node)?)?;
                }
                for relationship in &path.relationships {
                    bytes = bytes
                        .checked_add(estimated_relationship_value_heap_bytes(relationship)?)?;
                }
                Some(bytes)
            }
        }
    }
}

fn estimated_node_value_heap_bytes(node: &NodeValue) -> Option<usize> {
    let mut bytes = node.id.len().checked_add(
        node.labels
            .len()
            .checked_mul(std::mem::size_of::<String>())?,
    )?;
    for label in &node.labels {
        bytes = bytes.checked_add(label.len())?;
    }
    bytes.checked_add(estimated_properties_heap_bytes(&node.properties)?)
}

fn estimated_relationship_value_heap_bytes(relationship: &RelationshipValue) -> Option<usize> {
    relationship
        .id
        .len()
        .checked_add(relationship.start.len())?
        .checked_add(relationship.end.len())?
        .checked_add(relationship.r#type.len())?
        .checked_add(estimated_properties_heap_bytes(&relationship.properties)?)
}

#[cfg(test)]
mod tests {
    use super::Value;

    #[test]
    fn converts_json_scalars_and_collections() {
        let json = serde_json::json!({
            "none": null,
            "active": true,
            "age": 42,
            "score": 9.5,
            "name": "Alice",
            "tags": ["a", "b"],
            "nested": {"x": 1}
        });

        let value = Value::from_json(json).expect("convert JSON value");

        match value {
            Value::Map(map) => {
                assert_eq!(map["none"], Value::Null);
                assert_eq!(map["active"], Value::Boolean(true));
                assert_eq!(map["age"], Value::Integer(42));
                assert_eq!(map["score"], Value::Float(9.5));
                assert_eq!(map["name"], Value::String("Alice".to_string()));
                assert_eq!(
                    map["tags"],
                    Value::List(vec![
                        Value::String("a".to_string()),
                        Value::String("b".to_string())
                    ])
                );
            }
            other => panic!("expected map, got {other:?}"),
        }
    }

    #[test]
    fn rejects_unsigned_integers_outside_i64_range() {
        let json = serde_json::json!(9223372036854775808u64);

        let error = Value::from_json(json).expect_err("out of range unsigned integer");

        assert!(error.to_string().contains("unsupported JSON number"));
    }

    #[test]
    fn rejects_integer_literals_larger_than_u64_range() {
        let json: serde_json::Value =
            serde_json::from_str("18446744073709551616").expect("parse JSON number");

        let error = Value::from_json(json).expect_err("out of range integer literal");

        assert!(error.to_string().contains("unsupported JSON number"));
    }
}