use serde::{Deserialize, Serialize};
pub const DECIMAL_SCALE: u32 = 6;
pub const DECIMAL_DEN: i128 = 1_000_000;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Value {
Null,
Int(i64),
Decimal(i128),
Text(String),
Blob(Vec<u8>),
}
pub type Row = Vec<Value>;
impl Value {
pub fn type_name(&self) -> &'static str {
match self {
Value::Null => "null",
Value::Int(_) => "int",
Value::Decimal(_) => "decimal",
Value::Text(_) => "text",
Value::Blob(_) => "blob",
}
}
pub fn as_int(&self) -> Option<i64> {
match self {
Value::Int(i) => Some(*i),
_ => None,
}
}
pub fn as_text(&self) -> Option<&str> {
match self {
Value::Text(s) => Some(s),
_ => None,
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::Null => f.write_str("NULL"),
Value::Int(i) => write!(f, "{i}"),
Value::Decimal(m) => {
let mag = m.unsigned_abs();
let sign = if *m < 0 { "-" } else { "" };
let den = DECIMAL_DEN as u128;
write!(
f,
"{sign}{}.{:0w$}",
mag / den,
mag % den,
w = DECIMAL_SCALE as usize
)
}
Value::Text(s) => write!(f, "{s}"),
Value::Blob(b) => write!(f, "<blob {} bytes>", b.len()),
}
}
}
impl From<i64> for Value {
fn from(v: i64) -> Self {
Value::Int(v)
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Value::Text(v.to_owned())
}
}
impl From<String> for Value {
fn from(v: String) -> Self {
Value::Text(v)
}
}
impl From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Self {
Value::Blob(v)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
#[test]
fn decimal_is_totally_ordered() {
assert!(Value::Null < Value::Int(0));
assert!(Value::Int(i64::MAX) < Value::Decimal(0));
assert!(Value::Decimal(i128::MAX) < Value::Text(String::new()));
assert!(Value::Text("z".into()) < Value::Blob(vec![]));
assert!(Value::Decimal(1_500_000) < Value::Decimal(1_500_001));
assert!(Value::Decimal(-1) < Value::Decimal(0));
assert_ne!(Value::Int(2), Value::Decimal(2_000_000));
let set: BTreeSet<Value> = [
Value::Decimal(2_500_000),
Value::Decimal(-500_000),
Value::Decimal(0),
]
.into_iter()
.collect();
let ordered: Vec<_> = set.into_iter().collect();
assert_eq!(
ordered,
vec![
Value::Decimal(-500_000),
Value::Decimal(0),
Value::Decimal(2_500_000),
]
);
}
#[test]
fn decimal_display_is_fixed_point() {
assert_eq!(Value::Decimal(1_500_000).to_string(), "1.500000");
assert_eq!(Value::Decimal(-1_500_000).to_string(), "-1.500000");
assert_eq!(Value::Decimal(0).to_string(), "0.000000");
assert_eq!(Value::Decimal(625_000).to_string(), "0.625000");
assert_eq!(Value::Decimal(2_000_000).to_string(), "2.000000");
assert_eq!(Value::Decimal(-1).to_string(), "-0.000001");
assert_eq!(Value::Decimal(7813).to_string(), "0.007813");
}
}