use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
use crate::varint::{write_string, write_uvarint};
use crate::{Cursor, FormatError};
#[derive(Debug, Clone)]
pub enum Value {
Null,
Bool(bool),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
I32(i32),
I64(i64),
F32(f32),
F64(f64),
Utf8(String),
Bytes(Vec<u8>),
Array(Vec<Value>),
Map(BTreeMap<String, Value>),
}
impl Value {
pub fn bit_eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Null, Self::Null) => true,
(Self::Bool(a), Self::Bool(b)) => a == b,
(Self::U8(a), Self::U8(b)) => a == b,
(Self::U16(a), Self::U16(b)) => a == b,
(Self::U32(a), Self::U32(b)) => a == b,
(Self::U64(a), Self::U64(b)) => a == b,
(Self::U128(a), Self::U128(b)) => a == b,
(Self::I32(a), Self::I32(b)) => a == b,
(Self::I64(a), Self::I64(b)) => a == b,
(Self::F32(a), Self::F32(b)) => a.to_bits() == b.to_bits(),
(Self::F64(a), Self::F64(b)) => a.to_bits() == b.to_bits(),
(Self::Utf8(a), Self::Utf8(b)) => a == b,
(Self::Bytes(a), Self::Bytes(b)) => a == b,
(Self::Array(a), Self::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.bit_eq(y))
}
(Self::Map(a), Self::Map(b)) => {
a.len() == b.len()
&& a.iter()
.zip(b)
.all(|((ka, va), (kb, vb))| ka == kb && va.bit_eq(vb))
}
_ => false,
}
}
pub fn as_map(&self) -> Option<&BTreeMap<String, Value>> {
match self {
Self::Map(m) => Some(m),
_ => None,
}
}
pub fn as_array(&self) -> Option<&[Value]> {
match self {
Self::Array(a) => Some(a),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Utf8(s) => Some(s),
_ => None,
}
}
fn tag_order(&self) -> u8 {
match self {
Self::Null => 0,
Self::Bool(_) => 1,
Self::U8(_) => 2,
Self::U16(_) => 3,
Self::U32(_) => 4,
Self::U64(_) => 5,
Self::U128(_) => 6,
Self::I32(_) => 7,
Self::I64(_) => 8,
Self::F32(_) => 9,
Self::F64(_) => 10,
Self::Utf8(_) => 11,
Self::Bytes(_) => 12,
Self::Array(_) => 13,
Self::Map(_) => 14,
}
}
pub fn bit_cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Self::Null, Self::Null) => Ordering::Equal,
(Self::Bool(a), Self::Bool(b)) => a.cmp(b),
(Self::U8(a), Self::U8(b)) => a.cmp(b),
(Self::U16(a), Self::U16(b)) => a.cmp(b),
(Self::U32(a), Self::U32(b)) => a.cmp(b),
(Self::U64(a), Self::U64(b)) => a.cmp(b),
(Self::U128(a), Self::U128(b)) => a.cmp(b),
(Self::I32(a), Self::I32(b)) => a.cmp(b),
(Self::I64(a), Self::I64(b)) => a.cmp(b),
(Self::F32(a), Self::F32(b)) => a.to_bits().cmp(&b.to_bits()),
(Self::F64(a), Self::F64(b)) => a.to_bits().cmp(&b.to_bits()),
(Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
(Self::Bytes(a), Self::Bytes(b)) => a.cmp(b),
(Self::Array(a), Self::Array(b)) => {
for (x, y) in a.iter().zip(b.iter()) {
let c = x.bit_cmp(y);
if c != Ordering::Equal {
return c;
}
}
a.len().cmp(&b.len())
}
(Self::Map(a), Self::Map(b)) => {
for ((ka, va), (kb, vb)) in a.iter().zip(b.iter()) {
let c = ka.cmp(kb);
if c != Ordering::Equal {
return c;
}
let c = va.bit_cmp(vb);
if c != Ordering::Equal {
return c;
}
}
a.len().cmp(&b.len())
}
_ => self.tag_order().cmp(&other.tag_order()),
}
}
pub fn bit_hash<H: Hasher>(&self, state: &mut H) {
self.tag_order().hash(state);
match self {
Self::Null => {}
Self::Bool(v) => v.hash(state),
Self::U8(v) => v.hash(state),
Self::U16(v) => v.hash(state),
Self::U32(v) => v.hash(state),
Self::U64(v) => v.hash(state),
Self::U128(v) => v.hash(state),
Self::I32(v) => v.hash(state),
Self::I64(v) => v.hash(state),
Self::F32(v) => v.to_bits().hash(state),
Self::F64(v) => v.to_bits().hash(state),
Self::Utf8(v) => v.hash(state),
Self::Bytes(v) => v.hash(state),
Self::Array(v) => {
v.len().hash(state);
for x in v {
x.bit_hash(state);
}
}
Self::Map(m) => {
m.len().hash(state);
for (k, v) in m {
k.hash(state);
v.bit_hash(state);
}
}
}
}
pub fn encode(&self, out: &mut Vec<u8>) {
match self {
Self::Null => out.push(0),
Self::Bool(false) => out.push(1),
Self::Bool(true) => out.push(2),
Self::U8(v) => {
out.push(3);
out.push(*v);
}
Self::U16(v) => {
out.push(4);
out.extend_from_slice(&v.to_le_bytes());
}
Self::U32(v) => {
out.push(5);
out.extend_from_slice(&v.to_le_bytes());
}
Self::U64(v) => {
out.push(6);
out.extend_from_slice(&v.to_le_bytes());
}
Self::U128(v) => {
out.push(7);
out.extend_from_slice(&v.to_le_bytes());
}
Self::I32(v) => {
out.push(8);
out.extend_from_slice(&v.to_le_bytes());
}
Self::I64(v) => {
out.push(9);
out.extend_from_slice(&v.to_le_bytes());
}
Self::F32(v) => {
out.push(10);
out.extend_from_slice(&v.to_bits().to_le_bytes());
}
Self::F64(v) => {
out.push(11);
out.extend_from_slice(&v.to_bits().to_le_bytes());
}
Self::Utf8(s) => {
out.push(12);
write_string(out, s);
}
Self::Bytes(b) => {
out.push(13);
write_uvarint(out, b.len() as u64);
out.extend_from_slice(b);
}
Self::Array(arr) => {
out.push(14);
write_uvarint(out, arr.len() as u64);
for item in arr {
item.encode(out);
}
}
Self::Map(map) => {
out.push(15);
write_uvarint(out, map.len() as u64);
for (k, v) in map {
write_string(out, k);
v.encode(out);
}
}
}
}
pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
let tag = c.read_u8()?;
match tag {
0 => Ok(Self::Null),
1 => Ok(Self::Bool(false)),
2 => Ok(Self::Bool(true)),
3 => Ok(Self::U8(c.read_u8()?)),
4 => Ok(Self::U16(c.read_u16()?)),
5 => Ok(Self::U32(c.read_u32()?)),
6 => Ok(Self::U64(c.read_u64()?)),
7 => Ok(Self::U128(c.read_u128()?)),
8 => Ok(Self::I32(c.read_i32()?)),
9 => Ok(Self::I64(c.read_i64()?)),
10 => Ok(Self::F32(c.read_f32()?)),
11 => Ok(Self::F64(c.read_f64()?)),
12 => Ok(Self::Utf8(c.read_string()?)),
13 => {
let len =
usize::try_from(c.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
Ok(Self::Bytes(c.read_bytes(len)?.to_vec()))
}
14 => {
let count =
usize::try_from(c.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
let mut arr = Vec::with_capacity(count);
for _ in 0..count {
arr.push(Self::decode(c)?);
}
Ok(Self::Array(arr))
}
15 => {
let count =
usize::try_from(c.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
let mut map = BTreeMap::new();
for _ in 0..count {
let k = c.read_string()?;
let v = Self::decode(c)?;
map.insert(k, v);
}
Ok(Self::Map(map))
}
_ => Err(FormatError::InvalidValueTag(tag)),
}
}
pub fn decode_exact(buf: &[u8]) -> Result<Self, FormatError> {
let mut c = Cursor::new(buf);
Self::decode(&mut c)
}
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
self.bit_eq(other)
}
}
impl Eq for Value {}
impl Hash for Value {
fn hash<H: Hasher>(&self, state: &mut H) {
self.bit_hash(state);
}
}
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Value {
fn cmp(&self, other: &Self) -> Ordering {
self.bit_cmp(other)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_value_roundtrip_and_bit_eq() {
let mut m = BTreeMap::new();
m.insert(String::from("neg_zero"), Value::F64(-0.0));
m.insert(String::from("lat"), Value::F64(37.7510123));
m.insert(String::from("flag"), Value::Bool(false));
m.insert(String::from("big"), Value::U128(u128::MAX));
m.insert(
String::from("arr"),
Value::Array(alloc::vec![Value::U16(1), Value::Utf8(String::from("ok"))]),
);
let val = Value::Map(m);
let mut buf = Vec::new();
val.encode(&mut buf);
let decoded = Value::decode_exact(&buf).unwrap();
assert_eq!(val, decoded);
assert_ne!(Value::F64(-0.0), Value::F64(0.0));
}
}