1use crate::{Date, Duration, Error, Instant};
2use serde_core::de::{
3 self, Deserialize, Deserializer, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor,
4};
5use serde_core::ser::{Serialize, Serializer};
6use std::collections::BTreeMap;
7use std::collections::btree_map::Entry;
8use std::fmt::{self, Display};
9use std::str::FromStr;
10
11pub type Object = BTreeMap<String, Value>;
17
18#[derive(Debug, Clone, PartialEq, Default)]
32pub enum Value {
33 #[default]
37 Null,
38 Bool(bool),
42 Int(i64),
46 Float(f64),
50 String(String),
54 Date(Date),
58 Instant(Instant),
62 Duration(Duration),
66 Array(Vec<Self>),
70 Object(Object),
74}
75
76pub trait Index: private::Sealed {
80 #[doc(hidden)]
81 fn index_into(self, value: &Value) -> Option<&Value>;
82
83 #[doc(hidden)]
84 fn index_into_mut(self, value: &mut Value) -> Option<&mut Value>;
85}
86
87impl Index for &str {
88 fn index_into(self, value: &Value) -> Option<&Value> {
89 value.as_object()?.get(self)
90 }
91
92 fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
93 value.as_object_mut()?.get_mut(self)
94 }
95}
96
97impl Index for &String {
98 fn index_into(self, value: &Value) -> Option<&Value> {
99 self.as_str().index_into(value)
100 }
101
102 fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
103 self.as_str().index_into_mut(value)
104 }
105}
106
107impl Index for usize {
108 fn index_into(self, value: &Value) -> Option<&Value> {
109 value.as_array()?.get(self)
110 }
111
112 fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
113 value.as_array_mut()?.get_mut(self)
114 }
115}
116
117mod private {
118 pub trait Sealed {}
119 impl Sealed for &str {}
120 impl Sealed for &String {}
121 impl Sealed for usize {}
122}
123
124impl Value {
125 pub(crate) fn check(&self, depth: usize) -> Result<(), Error> {
129 match self {
130 Self::Float(value) if value.is_nan() => Err(Error::write("NaN is not a SOML value")),
131 Self::String(text) => crate::write::check_representable(text, "string"),
132 Self::Array(items) => {
133 let depth = crate::ser::nested_depth(depth)?;
134 for item in items {
135 item.check(depth)?;
136 }
137 Ok(())
138 }
139 Self::Object(object) => {
140 let depth = crate::ser::nested_depth(depth)?;
141 for (key, value) in object {
142 value.check(depth)?;
143 crate::write::check_representable(key, "key")?;
144 }
145 Ok(())
146 }
147 _ => Ok(()),
148 }
149 }
150
151 #[must_use]
155 pub fn get(&self, index: impl Index) -> Option<&Self> {
156 index.index_into(self)
157 }
158
159 pub fn get_mut(&mut self, index: impl Index) -> Option<&mut Self> {
163 index.index_into_mut(self)
164 }
165
166 #[must_use]
170 pub const fn is_null(&self) -> bool {
171 matches!(self, Self::Null)
172 }
173
174 #[must_use]
178 pub const fn as_bool(&self) -> Option<bool> {
179 match self {
180 Self::Bool(value) => Some(*value),
181 _ => None,
182 }
183 }
184
185 #[must_use]
189 pub const fn as_i64(&self) -> Option<i64> {
190 match self {
191 Self::Int(value) => Some(*value),
192 _ => None,
193 }
194 }
195
196 #[must_use]
200 pub const fn as_f64(&self) -> Option<f64> {
201 match self {
202 Self::Float(value) => Some(*value),
203 _ => None,
204 }
205 }
206
207 #[must_use]
211 pub const fn as_str(&self) -> Option<&str> {
212 match self {
213 Self::String(value) => Some(value.as_str()),
214 _ => None,
215 }
216 }
217
218 #[must_use]
222 pub const fn as_date(&self) -> Option<Date> {
223 match self {
224 Self::Date(value) => Some(*value),
225 _ => None,
226 }
227 }
228
229 #[must_use]
233 pub const fn as_instant(&self) -> Option<Instant> {
234 match self {
235 Self::Instant(value) => Some(*value),
236 _ => None,
237 }
238 }
239
240 #[must_use]
244 pub const fn as_duration(&self) -> Option<Duration> {
245 match self {
246 Self::Duration(value) => Some(*value),
247 _ => None,
248 }
249 }
250
251 #[must_use]
255 pub const fn as_array(&self) -> Option<&Vec<Self>> {
256 match self {
257 Self::Array(value) => Some(value),
258 _ => None,
259 }
260 }
261
262 pub const fn as_array_mut(&mut self) -> Option<&mut Vec<Self>> {
266 match self {
267 Self::Array(value) => Some(value),
268 _ => None,
269 }
270 }
271
272 #[must_use]
276 pub const fn as_object(&self) -> Option<&Object> {
277 match self {
278 Self::Object(value) => Some(value),
279 _ => None,
280 }
281 }
282
283 pub const fn as_object_mut(&mut self) -> Option<&mut Object> {
287 match self {
288 Self::Object(value) => Some(value),
289 _ => None,
290 }
291 }
292}
293
294impl FromStr for Value {
298 type Err = Error;
299
300 fn from_str(text: &str) -> Result<Self, Error> {
301 crate::parse::parse(text).map(crate::parse::Node::into_value)
302 }
303}
304
305macro_rules! from_integer {
306 ($($type:ty),*) => {
307 $(
308 impl From<$type> for Value {
309 fn from(value: $type) -> Self {
310 Self::Int(value.into())
311 }
312 }
313 )*
314 };
315}
316
317from_integer!(i8, i16, i32, i64, u8, u16, u32);
319
320impl From<f64> for Value {
321 fn from(value: f64) -> Self {
322 Self::Float(value)
323 }
324}
325
326impl From<f32> for Value {
327 fn from(value: f32) -> Self {
331 Self::Float(crate::ser::widen(value))
332 }
333}
334
335impl From<bool> for Value {
336 fn from(value: bool) -> Self {
337 Self::Bool(value)
338 }
339}
340
341impl From<String> for Value {
342 fn from(value: String) -> Self {
343 Self::String(value)
344 }
345}
346
347impl From<&str> for Value {
348 fn from(value: &str) -> Self {
349 Self::String(value.to_owned())
350 }
351}
352
353impl From<Date> for Value {
354 fn from(value: Date) -> Self {
355 Self::Date(value)
356 }
357}
358
359impl From<Instant> for Value {
360 fn from(value: Instant) -> Self {
361 Self::Instant(value)
362 }
363}
364
365impl From<Duration> for Value {
366 fn from(value: Duration) -> Self {
367 Self::Duration(value)
368 }
369}
370
371impl<T: Into<Self>> From<Vec<T>> for Value {
372 fn from(value: Vec<T>) -> Self {
373 value.into_iter().collect()
374 }
375}
376
377impl<T: Into<Self>, const N: usize> From<[T; N]> for Value {
378 fn from(value: [T; N]) -> Self {
379 value.into_iter().collect()
380 }
381}
382
383impl From<Object> for Value {
384 fn from(value: Object) -> Self {
385 Self::Object(value)
386 }
387}
388
389impl<T: Into<Self>> From<Option<T>> for Value {
390 fn from(value: Option<T>) -> Self {
391 value.map_or(Self::Null, Into::into)
392 }
393}
394
395impl<T: Into<Self>> FromIterator<T> for Value {
396 fn from_iter<I: IntoIterator<Item = T>>(iterator: I) -> Self {
397 Self::Array(iterator.into_iter().map(Into::into).collect())
398 }
399}
400
401impl<K: Into<String>, V: Into<Self>> FromIterator<(K, V)> for Value {
402 fn from_iter<I: IntoIterator<Item = (K, V)>>(iterator: I) -> Self {
403 Self::Object(
404 iterator
405 .into_iter()
406 .map(|(key, value)| (key.into(), value.into()))
407 .collect(),
408 )
409 }
410}
411
412pub(crate) struct TextVisitor<F> {
416 pub expecting: &'static str,
420 pub parse: F,
421}
422
423impl<'de, T, F: FnOnce(&str) -> Result<T, String>> Visitor<'de> for TextVisitor<F> {
424 type Value = T;
425
426 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
427 formatter.write_str(self.expecting)
428 }
429
430 fn visit_str<E: de::Error>(self, text: &str) -> Result<T, E> {
431 (self.parse)(text).map_err(E::custom)
432 }
433
434 fn visit_newtype_struct<D: Deserializer<'de>>(self, deserializer: D) -> Result<T, D::Error> {
435 deserializer.deserialize_str(self)
436 }
437}
438
439pub(crate) struct CanonicalText<'a, T: Display>(pub &'a T);
443
444impl<T: Display> Serialize for CanonicalText<'_, T> {
445 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
446 serializer.collect_str(self.0)
447 }
448}
449
450impl Serialize for Value {
451 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
452 match self {
453 Self::Null => serializer.serialize_unit(),
454 Self::Bool(value) => serializer.serialize_bool(*value),
455 Self::Int(value) => serializer.serialize_i64(*value),
456 Self::Float(value) => serializer.serialize_f64(*value),
457 Self::String(value) => serializer.serialize_str(value),
458 Self::Date(value) => value.serialize(serializer),
459 Self::Instant(value) => value.serialize(serializer),
460 Self::Duration(value) => value.serialize(serializer),
461 Self::Array(value) => serializer.collect_seq(value),
462 Self::Object(value) => serializer.collect_map(value),
463 }
464 }
465}
466
467pub(crate) const TOKEN: &str = "$soml::Value";
471
472impl<'de> Deserialize<'de> for Value {
473 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
474 deserializer.deserialize_newtype_struct(TOKEN, ValueVisitor)
475 }
476}
477
478struct ValueVisitor;
479
480impl<'de> Visitor<'de> for ValueVisitor {
481 type Value = Value;
482
483 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
484 formatter.write_str("any SOML value")
485 }
486
487 fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
488 Ok(Value::from(value))
489 }
490
491 fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
492 Ok(Value::from(value))
493 }
494
495 fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
496 crate::ser::integer(value)
497 .map(Value::Int)
498 .map_err(E::custom)
499 }
500
501 fn visit_i128<E: de::Error>(self, value: i128) -> Result<Value, E> {
502 crate::ser::integer(value)
503 .map(Value::Int)
504 .map_err(E::custom)
505 }
506
507 fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
508 crate::ser::integer(value)
509 .map(Value::Int)
510 .map_err(E::custom)
511 }
512
513 fn visit_f32<E>(self, value: f32) -> Result<Value, E> {
515 Ok(Value::from(value))
516 }
517
518 fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
519 Ok(Value::from(value))
520 }
521
522 fn visit_str<E>(self, value: &str) -> Result<Value, E> {
523 Ok(Value::from(value))
524 }
525
526 fn visit_string<E>(self, value: String) -> Result<Value, E> {
527 Ok(Value::from(value))
528 }
529
530 fn visit_unit<E>(self) -> Result<Value, E> {
531 Ok(Value::Null)
532 }
533
534 fn visit_none<E: de::Error>(self) -> Result<Value, E> {
535 self.visit_unit()
536 }
537
538 fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
539 Value::deserialize(deserializer)
540 }
541
542 fn visit_newtype_struct<D: Deserializer<'de>>(
543 self,
544 deserializer: D,
545 ) -> Result<Value, D::Error> {
546 deserializer.deserialize_any(self)
548 }
549
550 fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Value, A::Error> {
551 let mut items = Vec::with_capacity(crate::ser::capacity::<Value>(sequence.size_hint()));
553
554 while let Some(item) = sequence.next_element()? {
556 items.push(item);
557 }
558
559 Ok(Value::Array(items))
560 }
561
562 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
563 let mut object = Object::new();
564
565 while let Some(key) = map.next_key::<String>()? {
566 match object.entry(key) {
567 Entry::Vacant(entry) => {
568 entry.insert(map.next_value()?);
569 }
570 Entry::Occupied(entry) => {
572 return Err(de::Error::custom(Error::data(format!(
573 "Duplicate key “{}”",
574 crate::abbreviate(entry.key(), 40)
575 ))));
576 }
577 }
578 }
579
580 Ok(Value::Object(object))
581 }
582
583 fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Value, A::Error> {
587 let (name, variant): (&str, _) = data.variant()?;
588
589 match name {
590 crate::date::TOKEN => variant.newtype_variant().map(Value::Date),
591 crate::instant::TOKEN => variant.newtype_variant().map(Value::Instant),
592 crate::duration::TOKEN => variant.newtype_variant().map(Value::Duration),
593 _ => Err(de::Error::custom("A SOML value cannot hold an enum")),
594 }
595 }
596}