use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Default)]
pub enum Value {
#[default]
Null,
Bool(bool),
Int(i64),
Float(f64),
String(Arc<str>),
Array(Arc<[Value]>),
Map(Arc<Attrs>),
}
impl Value {
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(value) => Some(value),
_ => None,
}
}
#[must_use]
pub fn as_int(&self) -> Option<i64> {
match self {
Self::Int(value) => Some(*value),
_ => None,
}
}
#[must_use]
pub fn as_map(&self) -> Option<&Attrs> {
match self {
Self::Map(map) => Some(map),
_ => None,
}
}
#[must_use]
pub fn as_array(&self) -> Option<&[Self]> {
match self {
Self::Array(items) => Some(items),
_ => None,
}
}
#[must_use]
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(value) => Some(*value),
_ => None,
}
}
}
impl From<Vec<Value>> for Value {
fn from(value: Vec<Value>) -> Self {
Self::Array(value.into())
}
}
impl From<Attrs> for Value {
fn from(value: Attrs) -> Self {
Self::Map(Arc::new(value))
}
}
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<f64> for Value {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Self::String(value.into())
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Self::String(value.into())
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Attrs(Vec<(Arc<str>, Value)>);
impl Attrs {
#[must_use]
pub const fn new() -> Self {
Self(Vec::new())
}
#[must_use]
pub fn with(mut self, key: &str, value: impl Into<Value>) -> Self {
self.set(key, value);
self
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&Value> {
let index = self.find(key).ok()?;
Some(&self.0[index].1)
}
pub fn set(&mut self, key: &str, value: impl Into<Value>) -> Option<Value> {
let value = value.into();
match self.find(key) {
Ok(index) => Some(std::mem::replace(&mut self.0[index].1, value)),
Err(index) => {
self.0.insert(index, (key.into(), value));
None
}
}
}
pub fn remove(&mut self, key: &str) -> Option<Value> {
let index = self.find(key).ok()?;
Some(self.0.remove(index).1)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
self.0.iter().map(|(key, value)| (&**key, value))
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
fn find(&self, key: &str) -> Result<usize, usize> {
self.0.binary_search_by(|(probe, _)| (**probe).cmp(key))
}
}
impl<K: AsRef<str>, V: Into<Value>> FromIterator<(K, V)> for Attrs {
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut attrs = Self::new();
for (key, value) in iter {
attrs.set(key.as_ref(), value);
}
attrs
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_keys_sorted_and_unique() {
let mut attrs = Attrs::new().with("level", 2).with("align", "center");
let previous = attrs.set("level", 3);
let keys: Vec<_> = attrs.iter().map(|(key, _)| key).collect();
assert_eq!(keys, ["align", "level"]);
assert_eq!(previous, Some(Value::Int(2)));
assert_eq!(attrs.get("level").and_then(Value::as_int), Some(3));
}
#[test]
fn remove_returns_the_old_value() {
let mut attrs: Attrs = [("href", "https://canvist.dev")].into_iter().collect();
assert_eq!(
attrs.remove("href").as_ref().and_then(Value::as_str),
Some("https://canvist.dev")
);
assert!(attrs.is_empty());
assert_eq!(attrs.remove("href"), None);
}
}