use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Enumerator {
pub name: Option<String>,
pub value: Option<i128>,
}
impl Enumerator {
pub fn new(name: impl Into<String>, value: impl Into<i128>) -> Self {
Self { name: Some(name.into()), value: Some(value.into()) }
}
pub fn named(name: impl Into<String>) -> Self {
Self { name: Some(name.into()), value: None }
}
pub fn numbered(value: impl Into<i128>) -> Self {
Self { name: None, value: Some(value.into()) }
}
}
impl From<&str> for Enumerator {
fn from(name: &str) -> Self {
Self::named(name)
}
}
impl From<String> for Enumerator {
fn from(name: String) -> Self {
Self::named(name)
}
}
impl fmt::Display for Enumerator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (&self.name, self.value) {
(Some(name), Some(value)) => write!(f, "{name}({value})"),
(Some(name), None) => f.write_str(name),
(None, Some(value)) => write!(f, "?({value})"),
(None, None) => f.write_str("?"),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VariantValue {
pub discriminant: Enumerator,
pub alternative: Option<String>,
pub value: Option<Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Bool(bool),
Integer(i128),
Float(f64),
Octet(u8),
Char(char),
String(String),
Bytes(Vec<u8>),
Enum(Box<Enumerator>),
Array(Vec<Value>),
Record(Vec<(String, Value)>),
Variant(Box<VariantValue>),
Handle(Vec<u8>),
Raw(Vec<u8>),
}
impl Value {
pub fn integer(value: impl Into<i128>) -> Self {
Value::Integer(value.into())
}
pub fn string(text: impl Into<String>) -> Self {
Value::String(text.into())
}
pub fn bytes(octets: impl Into<Vec<u8>>) -> Self {
Value::Bytes(octets.into())
}
pub fn handle(octets: impl Into<Vec<u8>>) -> Self {
Value::Handle(octets.into())
}
pub fn raw(octets: impl Into<Vec<u8>>) -> Self {
Value::Raw(octets.into())
}
pub fn enumerator(name: impl Into<String>) -> Self {
Value::Enum(Box::new(Enumerator::named(name)))
}
pub fn enumerator_value(value: impl Into<i128>) -> Self {
Value::Enum(Box::new(Enumerator::numbered(value)))
}
pub fn enumerator_with(name: impl Into<String>, value: impl Into<i128>) -> Self {
Value::Enum(Box::new(Enumerator::new(name, value)))
}
pub fn array<T: Into<Value>>(items: impl IntoIterator<Item = T>) -> Self {
Value::Array(items.into_iter().map(Into::into).collect())
}
pub fn record<N: Into<String>, T: Into<Value>>(fields: impl IntoIterator<Item = (N, T)>) -> Self {
Value::Record(fields.into_iter().map(|(name, value)| (name.into(), value.into())).collect())
}
pub fn variant(discriminant: impl Into<Enumerator>, value: Option<Value>) -> Self {
Value::Variant(Box::new(VariantValue { discriminant: discriminant.into(), alternative: None, value }))
}
pub fn variant_named(
discriminant: impl Into<Enumerator>,
alternative: impl Into<String>,
value: impl Into<Value>,
) -> Self {
Value::Variant(Box::new(VariantValue {
discriminant: discriminant.into(),
alternative: Some(alternative.into()),
value: Some(value.into()),
}))
}
pub fn kind(&self) -> &'static str {
match self {
Value::Bool(_) => "boolean",
Value::Integer(_) => "integer",
Value::Float(_) => "float",
Value::Octet(_) => "octet",
Value::Char(_) => "character",
Value::String(_) => "string",
Value::Bytes(_) => "bytes",
Value::Enum(_) => "enumerator",
Value::Array(_) => "array",
Value::Record(_) => "record",
Value::Variant(_) => "variant record",
Value::Handle(_) => "handle",
Value::Raw(_) => "raw bytes",
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(value) => Some(*value),
_ => None,
}
}
pub fn as_integer(&self) -> Option<i128> {
match self {
Value::Integer(value) => Some(*value),
Value::Octet(value) => Some(i128::from(*value)),
Value::Enum(enumerator) => enumerator.value,
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
self.as_integer().and_then(|value| i64::try_from(value).ok())
}
pub fn as_u64(&self) -> Option<u64> {
self.as_integer().and_then(|value| u64::try_from(value).ok())
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Float(value) => Some(*value),
Value::Integer(value) => Some(*value as f64),
_ => None,
}
}
pub fn as_char(&self) -> Option<char> {
match self {
Value::Char(value) => Some(*value),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(text) => Some(text),
Value::Enum(enumerator) => enumerator.name.as_deref(),
_ => None,
}
}
pub fn as_bytes(&self) -> Option<&[u8]> {
match self {
Value::Bytes(octets) | Value::Handle(octets) | Value::Raw(octets) => Some(octets),
_ => None,
}
}
pub fn as_enumerator(&self) -> Option<&Enumerator> {
match self {
Value::Enum(enumerator) => Some(enumerator),
_ => None,
}
}
pub fn as_variant(&self) -> Option<&VariantValue> {
match self {
Value::Variant(variant) => Some(variant),
_ => None,
}
}
pub fn items(&self) -> Option<&[Value]> {
match self {
Value::Array(items) => Some(items),
_ => None,
}
}
pub fn get(&self, index: usize) -> Option<&Value> {
self.items()?.get(index)
}
pub fn fields(&self) -> Option<&[(String, Value)]> {
match self {
Value::Record(fields) => Some(fields),
_ => None,
}
}
pub fn field(&self, name: &str) -> Option<&Value> {
match self {
Value::Record(fields) => fields.iter().find(|(field, _)| field == name).map(|(_, value)| value),
Value::Variant(variant) if variant.alternative.as_deref() == Some(name) => variant.value.as_ref(),
_ => None,
}
}
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Value::Bool(value)
}
}
macro_rules! integer_from {
($($native:ty),+) => {$(
impl From<$native> for Value {
fn from(value: $native) -> Self {
Value::Integer(i128::from(value))
}
}
)+};
}
integer_from!(i8, i16, i32, i64, u8, u16, u32, u64);
impl From<i128> for Value {
fn from(value: i128) -> Self {
Value::Integer(value)
}
}
impl From<f32> for Value {
fn from(value: f32) -> Self {
Value::Float(f64::from(value))
}
}
impl From<f64> for Value {
fn from(value: f64) -> Self {
Value::Float(value)
}
}
impl From<char> for Value {
fn from(value: char) -> Self {
Value::Char(value)
}
}
impl From<&str> for Value {
fn from(text: &str) -> Self {
Value::String(text.to_owned())
}
}
impl From<String> for Value {
fn from(text: String) -> Self {
Value::String(text)
}
}
impl From<Vec<u8>> for Value {
fn from(octets: Vec<u8>) -> Self {
Value::Bytes(octets)
}
}
impl From<&[u8]> for Value {
fn from(octets: &[u8]) -> Self {
Value::Bytes(octets.to_vec())
}
}
impl From<Vec<Value>> for Value {
fn from(items: Vec<Value>) -> Self {
Value::Array(items)
}
}
impl From<Enumerator> for Value {
fn from(enumerator: Enumerator) -> Self {
Value::Enum(Box::new(enumerator))
}
}
impl From<VariantValue> for Value {
fn from(variant: VariantValue) -> Self {
Value::Variant(Box::new(variant))
}
}
impl FromIterator<Value> for Value {
fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
Value::Array(items.into_iter().collect())
}
}
fn write_hex(f: &mut fmt::Formatter<'_>, octets: &[u8]) -> fmt::Result {
f.write_str("0x")?;
octets.iter().try_for_each(|octet| write!(f, "{octet:02x}"))
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Bool(value) => write!(f, "{value}"),
Value::Integer(value) => write!(f, "{value}"),
Value::Float(value) => write!(f, "{value:?}"),
Value::Octet(value) => write!(f, "0x{value:02x}"),
Value::Char(value) => write!(f, "{value:?}"),
Value::String(text) => write!(f, "{text:?}"),
Value::Bytes(octets) => write_hex(f, octets),
Value::Enum(enumerator) => write!(f, "{enumerator}"),
Value::Array(items) => {
f.write_str("[")?;
for (index, item) in items.iter().enumerate() {
if index > 0 {
f.write_str(", ")?;
}
write!(f, "{item}")?;
}
f.write_str("]")
}
Value::Record(fields) => {
f.write_str("{")?;
for (index, (name, value)) in fields.iter().enumerate() {
if index > 0 {
f.write_str(", ")?;
}
write!(f, "{name}: {value}")?;
}
f.write_str("}")
}
Value::Variant(variant) => {
write!(f, "{}{{", variant.discriminant)?;
match (&variant.alternative, &variant.value) {
(Some(name), Some(value)) => write!(f, "{name}: {value}")?,
(Some(name), None) => f.write_str(name)?,
(None, Some(value)) => write!(f, "{value}")?,
(None, None) => {}
}
f.write_str("}")
}
Value::Handle(octets) => {
f.write_str("handle(")?;
write_hex(f, octets)?;
f.write_str(")")
}
Value::Raw(octets) => {
f.write_str("raw(")?;
write_hex(f, octets)?;
f.write_str(")")
}
}
}
}