matdb 0.1.0

An experimental embedded SQL-like DBMS
Documentation
use std::fmt::Display;

#[derive(Debug, Clone, Copy)]
pub enum Type {
    Any,
    Bool,
    Int,
    String,
}

impl Display for Type {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Type::Any => "ANY",
            Type::Bool => "BOOLEAN",
            Type::Int => "INT",
            Type::String => "TEXT",
        })
    }
}

/// A `matdb` scalar SQL value.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Value {
    /// null value, nothing
    Null,
    /// boolean
    Bool(bool),
    /// a 64 bit signed integer
    Int(i64),
    /// a UTF-8 string
    String(String),
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Null => f.write_str("NULL"),
            Self::Bool(b) => {
                if *b {
                    f.write_str("TRUE")
                } else {
                    f.write_str("FALSE")
                }
            }
            Self::Int(i) => f.write_fmt(format_args!("{i}")),
            Self::String(s) => f.write_fmt(format_args!("'{s}'")),
        }
    }
}

impl Value {
    /// Convenience function that returns true if the value is `Value::Null`.
    pub fn is_null(self) -> bool {
        match self {
            Value::Null => true,
            _ => false,
        }
    }

    /// Convenience function that returns the underlying value if the value is `Value::Bool`.
    pub fn into_bool(self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(b),
            _ => None,
        }
    }

    /// Convenience function that returns the underlying value if the value is `Value::Int`.
    pub fn into_i64(self) -> Option<i64> {
        match self {
            Value::Int(i) => Some(i),
            _ => None,
        }
    }

    /// Convenience function that returns the underlying value if the value is `Value::String`.
    pub fn into_string(self) -> Option<String> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }
}

impl From<()> for Value {
    fn from(_value: ()) -> Self {
        Self::Null
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<i64> for Value {
    fn from(value: i64) -> Self {
        Self::Int(value)
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}