1use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub struct Enumerator {
14 pub name: Option<String>,
16 pub value: Option<i128>,
18}
19
20impl Enumerator {
21 pub fn new(name: impl Into<String>, value: impl Into<i128>) -> Self {
23 Self { name: Some(name.into()), value: Some(value.into()) }
24 }
25
26 pub fn named(name: impl Into<String>) -> Self {
28 Self { name: Some(name.into()), value: None }
29 }
30
31 pub fn numbered(value: impl Into<i128>) -> Self {
33 Self { name: None, value: Some(value.into()) }
34 }
35}
36
37impl From<&str> for Enumerator {
38 fn from(name: &str) -> Self {
39 Self::named(name)
40 }
41}
42
43impl From<String> for Enumerator {
44 fn from(name: String) -> Self {
45 Self::named(name)
46 }
47}
48
49impl fmt::Display for Enumerator {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 match (&self.name, self.value) {
53 (Some(name), Some(value)) => write!(f, "{name}({value})"),
54 (Some(name), None) => f.write_str(name),
55 (None, Some(value)) => write!(f, "?({value})"),
56 (None, None) => f.write_str("?"),
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct VariantValue {
64 pub discriminant: Enumerator,
66 pub alternative: Option<String>,
69 pub value: Option<Value>,
72}
73
74#[derive(Debug, Clone, PartialEq)]
76pub enum Value {
77 Bool(bool),
79 Integer(i128),
82 Float(f64),
84 Octet(u8),
86 Char(char),
88 String(String),
90 Bytes(Vec<u8>),
92 Enum(Box<Enumerator>),
94 Array(Vec<Value>),
96 Record(Vec<(String, Value)>),
98 Variant(Box<VariantValue>),
100 Handle(Vec<u8>),
102 Raw(Vec<u8>),
104}
105
106impl Value {
107 pub fn integer(value: impl Into<i128>) -> Self {
109 Value::Integer(value.into())
110 }
111
112 pub fn string(text: impl Into<String>) -> Self {
114 Value::String(text.into())
115 }
116
117 pub fn bytes(octets: impl Into<Vec<u8>>) -> Self {
119 Value::Bytes(octets.into())
120 }
121
122 pub fn handle(octets: impl Into<Vec<u8>>) -> Self {
124 Value::Handle(octets.into())
125 }
126
127 pub fn raw(octets: impl Into<Vec<u8>>) -> Self {
129 Value::Raw(octets.into())
130 }
131
132 pub fn enumerator(name: impl Into<String>) -> Self {
134 Value::Enum(Box::new(Enumerator::named(name)))
135 }
136
137 pub fn enumerator_value(value: impl Into<i128>) -> Self {
139 Value::Enum(Box::new(Enumerator::numbered(value)))
140 }
141
142 pub fn enumerator_with(name: impl Into<String>, value: impl Into<i128>) -> Self {
144 Value::Enum(Box::new(Enumerator::new(name, value)))
145 }
146
147 pub fn array<T: Into<Value>>(items: impl IntoIterator<Item = T>) -> Self {
149 Value::Array(items.into_iter().map(Into::into).collect())
150 }
151
152 pub fn record<N: Into<String>, T: Into<Value>>(fields: impl IntoIterator<Item = (N, T)>) -> Self {
154 Value::Record(fields.into_iter().map(|(name, value)| (name.into(), value.into())).collect())
155 }
156
157 pub fn variant(discriminant: impl Into<Enumerator>, value: Option<Value>) -> Self {
160 Value::Variant(Box::new(VariantValue { discriminant: discriminant.into(), alternative: None, value }))
161 }
162
163 pub fn variant_named(
165 discriminant: impl Into<Enumerator>,
166 alternative: impl Into<String>,
167 value: impl Into<Value>,
168 ) -> Self {
169 Value::Variant(Box::new(VariantValue {
170 discriminant: discriminant.into(),
171 alternative: Some(alternative.into()),
172 value: Some(value.into()),
173 }))
174 }
175
176 pub fn kind(&self) -> &'static str {
178 match self {
179 Value::Bool(_) => "boolean",
180 Value::Integer(_) => "integer",
181 Value::Float(_) => "float",
182 Value::Octet(_) => "octet",
183 Value::Char(_) => "character",
184 Value::String(_) => "string",
185 Value::Bytes(_) => "bytes",
186 Value::Enum(_) => "enumerator",
187 Value::Array(_) => "array",
188 Value::Record(_) => "record",
189 Value::Variant(_) => "variant record",
190 Value::Handle(_) => "handle",
191 Value::Raw(_) => "raw bytes",
192 }
193 }
194
195 pub fn as_bool(&self) -> Option<bool> {
197 match self {
198 Value::Bool(value) => Some(*value),
199 _ => None,
200 }
201 }
202
203 pub fn as_integer(&self) -> Option<i128> {
205 match self {
206 Value::Integer(value) => Some(*value),
207 Value::Octet(value) => Some(i128::from(*value)),
208 Value::Enum(enumerator) => enumerator.value,
209 _ => None,
210 }
211 }
212
213 pub fn as_i64(&self) -> Option<i64> {
215 self.as_integer().and_then(|value| i64::try_from(value).ok())
216 }
217
218 pub fn as_u64(&self) -> Option<u64> {
220 self.as_integer().and_then(|value| u64::try_from(value).ok())
221 }
222
223 pub fn as_f64(&self) -> Option<f64> {
225 match self {
226 Value::Float(value) => Some(*value),
227 Value::Integer(value) => Some(*value as f64),
228 _ => None,
229 }
230 }
231
232 pub fn as_char(&self) -> Option<char> {
234 match self {
235 Value::Char(value) => Some(*value),
236 _ => None,
237 }
238 }
239
240 pub fn as_str(&self) -> Option<&str> {
242 match self {
243 Value::String(text) => Some(text),
244 Value::Enum(enumerator) => enumerator.name.as_deref(),
245 _ => None,
246 }
247 }
248
249 pub fn as_bytes(&self) -> Option<&[u8]> {
251 match self {
252 Value::Bytes(octets) | Value::Handle(octets) | Value::Raw(octets) => Some(octets),
253 _ => None,
254 }
255 }
256
257 pub fn as_enumerator(&self) -> Option<&Enumerator> {
259 match self {
260 Value::Enum(enumerator) => Some(enumerator),
261 _ => None,
262 }
263 }
264
265 pub fn as_variant(&self) -> Option<&VariantValue> {
267 match self {
268 Value::Variant(variant) => Some(variant),
269 _ => None,
270 }
271 }
272
273 pub fn items(&self) -> Option<&[Value]> {
275 match self {
276 Value::Array(items) => Some(items),
277 _ => None,
278 }
279 }
280
281 pub fn get(&self, index: usize) -> Option<&Value> {
283 self.items()?.get(index)
284 }
285
286 pub fn fields(&self) -> Option<&[(String, Value)]> {
288 match self {
289 Value::Record(fields) => Some(fields),
290 _ => None,
291 }
292 }
293
294 pub fn field(&self, name: &str) -> Option<&Value> {
297 match self {
298 Value::Record(fields) => fields.iter().find(|(field, _)| field == name).map(|(_, value)| value),
299 Value::Variant(variant) if variant.alternative.as_deref() == Some(name) => variant.value.as_ref(),
300 _ => None,
301 }
302 }
303}
304
305impl From<bool> for Value {
306 fn from(value: bool) -> Self {
307 Value::Bool(value)
308 }
309}
310
311macro_rules! integer_from {
312 ($($native:ty),+) => {$(
313 impl From<$native> for Value {
314 fn from(value: $native) -> Self {
315 Value::Integer(i128::from(value))
316 }
317 }
318 )+};
319}
320
321integer_from!(i8, i16, i32, i64, u8, u16, u32, u64);
322
323impl From<i128> for Value {
324 fn from(value: i128) -> Self {
325 Value::Integer(value)
326 }
327}
328
329impl From<f32> for Value {
330 fn from(value: f32) -> Self {
331 Value::Float(f64::from(value))
332 }
333}
334
335impl From<f64> for Value {
336 fn from(value: f64) -> Self {
337 Value::Float(value)
338 }
339}
340
341impl From<char> for Value {
342 fn from(value: char) -> Self {
343 Value::Char(value)
344 }
345}
346
347impl From<&str> for Value {
348 fn from(text: &str) -> Self {
349 Value::String(text.to_owned())
350 }
351}
352
353impl From<String> for Value {
354 fn from(text: String) -> Self {
355 Value::String(text)
356 }
357}
358
359impl From<Vec<u8>> for Value {
361 fn from(octets: Vec<u8>) -> Self {
362 Value::Bytes(octets)
363 }
364}
365
366impl From<&[u8]> for Value {
368 fn from(octets: &[u8]) -> Self {
369 Value::Bytes(octets.to_vec())
370 }
371}
372
373impl From<Vec<Value>> for Value {
374 fn from(items: Vec<Value>) -> Self {
375 Value::Array(items)
376 }
377}
378
379impl From<Enumerator> for Value {
380 fn from(enumerator: Enumerator) -> Self {
381 Value::Enum(Box::new(enumerator))
382 }
383}
384
385impl From<VariantValue> for Value {
386 fn from(variant: VariantValue) -> Self {
387 Value::Variant(Box::new(variant))
388 }
389}
390
391impl FromIterator<Value> for Value {
392 fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
393 Value::Array(items.into_iter().collect())
394 }
395}
396
397fn write_hex(f: &mut fmt::Formatter<'_>, octets: &[u8]) -> fmt::Result {
398 f.write_str("0x")?;
399 octets.iter().try_for_each(|octet| write!(f, "{octet:02x}"))
400}
401
402impl fmt::Display for Value {
408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409 match self {
410 Value::Bool(value) => write!(f, "{value}"),
411 Value::Integer(value) => write!(f, "{value}"),
412 Value::Float(value) => write!(f, "{value:?}"),
413 Value::Octet(value) => write!(f, "0x{value:02x}"),
414 Value::Char(value) => write!(f, "{value:?}"),
415 Value::String(text) => write!(f, "{text:?}"),
416 Value::Bytes(octets) => write_hex(f, octets),
417 Value::Enum(enumerator) => write!(f, "{enumerator}"),
418 Value::Array(items) => {
419 f.write_str("[")?;
420 for (index, item) in items.iter().enumerate() {
421 if index > 0 {
422 f.write_str(", ")?;
423 }
424 write!(f, "{item}")?;
425 }
426 f.write_str("]")
427 }
428 Value::Record(fields) => {
429 f.write_str("{")?;
430 for (index, (name, value)) in fields.iter().enumerate() {
431 if index > 0 {
432 f.write_str(", ")?;
433 }
434 write!(f, "{name}: {value}")?;
435 }
436 f.write_str("}")
437 }
438 Value::Variant(variant) => {
439 write!(f, "{}{{", variant.discriminant)?;
440 match (&variant.alternative, &variant.value) {
441 (Some(name), Some(value)) => write!(f, "{name}: {value}")?,
442 (Some(name), None) => f.write_str(name)?,
443 (None, Some(value)) => write!(f, "{value}")?,
444 (None, None) => {}
445 }
446 f.write_str("}")
447 }
448 Value::Handle(octets) => {
449 f.write_str("handle(")?;
450 write_hex(f, octets)?;
451 f.write_str(")")
452 }
453 Value::Raw(octets) => {
454 f.write_str("raw(")?;
455 write_hex(f, octets)?;
456 f.write_str(")")
457 }
458 }
459 }
460}