Skip to main content

soml/
value.rs

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
11/**
12A SOML object: members by key.
13
14The order of members is not part of a value in SOML, so an object is a `BTreeMap`. It iterates in canonical order, and two objects with the same members are equal. Keys are compared byte for byte, with no Unicode normalization, as the spec requires.
15*/
16pub type Object = BTreeMap<String, Value>;
17
18/**
19Any SOML value.
20
21```rust
22let value: soml::Value = "port: 8080\nhosts: ['a', 'b']".parse()?;
23
24assert_eq!(value.get("port").and_then(soml::Value::as_i64), Some(8080));
25assert_eq!(value.get("hosts").and_then(|hosts| hosts.get(1)).and_then(soml::Value::as_str), Some("b"));
26# Ok::<(), soml::Error>(())
27```
28
29An int and a float are different types, as in the spec: `Value::Int(3)` and `Value::Float(3.0)` are not equal, and `as_f64()` does not convert an int.
30*/
31#[derive(Debug, Clone, PartialEq, Default)]
32pub enum Value {
33	/**
34	`null`.
35	*/
36	#[default]
37	Null,
38	/**
39	`true` or `false`.
40	*/
41	Bool(bool),
42	/**
43	An int.
44	*/
45	Int(i64),
46	/**
47	A float. A float that came from a document is never NaN, and it is never negative zero.
48	*/
49	Float(f64),
50	/**
51	A string.
52	*/
53	String(String),
54	/**
55	A Gregorian calendar date.
56	*/
57	Date(Date),
58	/**
59	An instant.
60	*/
61	Instant(Instant),
62	/**
63	A duration.
64	*/
65	Duration(Duration),
66	/**
67	An array.
68	*/
69	Array(Vec<Self>),
70	/**
71	An object.
72	*/
73	Object(Object),
74}
75
76/**
77Something that can index into a `Value`: a key for an object, or a position for an array.
78*/
79pub 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	/**
126	Checks representability without cloning a value or allocating a second tree. `depth` counts surrounding collections.
127	*/
128	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	/**
152	The member of an object with this key, or the item of an array at this position. `None` for a missing member or item, and for a value of another type.
153	*/
154	#[must_use]
155	pub fn get(&self, index: impl Index) -> Option<&Self> {
156		index.index_into(self)
157	}
158
159	/**
160	A mutable reference to the member of an object with this key, or the item of an array at this position.
161	*/
162	pub fn get_mut(&mut self, index: impl Index) -> Option<&mut Self> {
163		index.index_into_mut(self)
164	}
165
166	/**
167	Whether the value is `null`.
168	*/
169	#[must_use]
170	pub const fn is_null(&self) -> bool {
171		matches!(self, Self::Null)
172	}
173
174	/**
175	The bool, if the value is one.
176	*/
177	#[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	/**
186	The int, if the value is one.
187	*/
188	#[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	/**
197	The float, if the value is one. An int is not converted, because an int and a float are different types.
198	*/
199	#[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	/**
208	The string, if the value is one.
209	*/
210	#[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	/**
219	The date, if the value is one.
220	*/
221	#[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	/**
230	The instant, if the value is one.
231	*/
232	#[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	/**
241	The duration, if the value is one.
242	*/
243	#[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	/**
252	The items, if the value is an array.
253	*/
254	#[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	/**
263	The items, if the value is an array, to change.
264	*/
265	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	/**
273	The members, if the value is an object.
274	*/
275	#[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	/**
284	The members, if the value is an object, to change.
285	*/
286	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
294/**
295Reads a document, which is always an object or an array.
296*/
297impl 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
317// Only the types that always fit an `i64`. A `u64`, an `i128`, or a `usize` can be too large, and `From` cannot fail.
318from_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	/**
328	Uses the shortest decimal that reads back as the same `f32`, so `0.1f32` becomes `0.1`, not `0.10000000149011612`.
329	*/
330	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
412/**
413Reads a date, instant, or duration from its text, through a newtype struct named by its token, which the SOML deserializer gives only for a value of that type, and from a string for other formats.
414*/
415pub(crate) struct TextVisitor<F> {
416	/**
417	The type, with an article, for error messages: `an instant`.
418	*/
419	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
439/**
440Serializes a value's canonical text, with `collect_str`, so that it allocates nothing for a serializer that writes text directly.
441*/
442pub(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
467/**
468The name that tells the SOML deserializer that a `Value` is being read, so that it gives a date, instant, or duration as itself, through `visit_enum`, rather than as its text.
469*/
470pub(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	// An `f32` from another format, with its own shortest digits, as `From<f32>` makes it.
514	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		// `Value::deserialize` asks for a newtype struct named `TOKEN`. A format that does not know the token, such as JSON, calls this with its own deserializer, so the value is read as any other value.
547		deserializer.deserialize_any(self)
548	}
549
550	fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Value, A::Error> {
551		// The size hint of another format can come from its input, so it is capped to keep a false hint from allocating much memory.
552		let mut items = Vec::with_capacity(crate::ser::capacity::<Value>(sequence.size_hint()));
553
554		// Note: Not using Iterator::try_collect because it is unstable on the minimum Rust version.
555		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				// Another format, such as JSON, can give a key twice. SOML treats a duplicate key as an error, so a `Value` does not keep the last one.
571				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	/**
584	The SOML deserializer gives a date, instant, or duration as a variant named by its private token, which no other format produces.
585	*/
586	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}