Skip to main content

noyalib/value/
convert.rs

1//! `From<T> for Value` conversions and `Index`/`IndexMut`.
2
3// SPDX-License-Identifier: MIT OR Apache-2.0
4// Copyright (c) 2026 Noyalib. All rights reserved.
5
6use super::{Mapping, Number, TaggedValue, Value};
7use crate::prelude::*;
8use core::ops::{Index, IndexMut};
9
10impl From<()> for Value {
11    fn from((): ()) -> Self {
12        Self::Null
13    }
14}
15
16impl From<bool> for Value {
17    fn from(v: bool) -> Self {
18        Self::Bool(v)
19    }
20}
21
22impl From<i8> for Value {
23    fn from(v: i8) -> Self {
24        Self::Number(Number::Integer(i64::from(v)))
25    }
26}
27
28impl From<i16> for Value {
29    fn from(v: i16) -> Self {
30        Self::Number(Number::Integer(i64::from(v)))
31    }
32}
33
34impl From<i32> for Value {
35    fn from(v: i32) -> Self {
36        Self::Number(Number::Integer(i64::from(v)))
37    }
38}
39
40impl From<i64> for Value {
41    fn from(v: i64) -> Self {
42        Self::Number(Number::Integer(v))
43    }
44}
45
46impl From<u8> for Value {
47    fn from(v: u8) -> Self {
48        Self::Number(Number::Integer(i64::from(v)))
49    }
50}
51
52impl From<u16> for Value {
53    fn from(v: u16) -> Self {
54        Self::Number(Number::Integer(i64::from(v)))
55    }
56}
57
58impl From<u32> for Value {
59    fn from(v: u32) -> Self {
60        Self::Number(Number::Integer(i64::from(v)))
61    }
62}
63
64impl From<f32> for Value {
65    fn from(v: f32) -> Self {
66        Self::Number(Number::Float(f64::from(v)))
67    }
68}
69
70impl From<f64> for Value {
71    fn from(v: f64) -> Self {
72        Self::Number(Number::Float(v))
73    }
74}
75
76impl From<String> for Value {
77    fn from(v: String) -> Self {
78        Self::String(v)
79    }
80}
81
82impl From<&str> for Value {
83    fn from(v: &str) -> Self {
84        Self::String(v.to_owned())
85    }
86}
87
88impl<T: Into<Self>> From<Vec<T>> for Value {
89    fn from(v: Vec<T>) -> Self {
90        Self::Sequence(v.into_iter().map(Into::into).collect())
91    }
92}
93
94impl<T: Into<Self>> From<Option<T>> for Value {
95    fn from(v: Option<T>) -> Self {
96        match v {
97            Some(v) => v.into(),
98            None => Self::Null,
99        }
100    }
101}
102
103impl From<Number> for Value {
104    fn from(v: Number) -> Self {
105        Self::Number(v)
106    }
107}
108
109impl From<Mapping> for Value {
110    fn from(v: Mapping) -> Self {
111        Self::Mapping(v)
112    }
113}
114
115// Note: From<Sequence> is covered by From<Vec<T>> since Sequence = Vec<Value>
116
117impl From<TaggedValue> for Value {
118    fn from(v: TaggedValue) -> Self {
119        Self::Tagged(Box::new(v))
120    }
121}
122
123impl From<u64> for Value {
124    fn from(v: u64) -> Self {
125        Self::Number(Number::from(v))
126    }
127}
128
129impl From<isize> for Value {
130    fn from(v: isize) -> Self {
131        Self::Number(Number::from(v))
132    }
133}
134
135impl From<usize> for Value {
136    fn from(v: usize) -> Self {
137        Self::Number(Number::from(v))
138    }
139}
140
141impl<'a> From<Cow<'a, str>> for Value {
142    fn from(v: Cow<'a, str>) -> Self {
143        Self::String(v.into_owned())
144    }
145}
146
147impl<T: Clone + Into<Self>> From<&[T]> for Value {
148    fn from(v: &[T]) -> Self {
149        Self::Sequence(v.iter().cloned().map(Into::into).collect())
150    }
151}
152
153impl<T: Into<Self>> FromIterator<T> for Value {
154    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
155        Self::Sequence(iter.into_iter().map(Into::into).collect())
156    }
157}
158
159// ============================================================================
160// Index trait implementations for Value
161// ============================================================================
162
163impl Index<usize> for Value {
164    type Output = Self;
165
166    /// Index into a YAML sequence.
167    ///
168    /// # Panics
169    ///
170    /// Panics if the value is not a sequence or if the index is out of bounds.
171    ///
172    /// # Examples
173    ///
174    /// ```rust
175    /// use noyalib::{from_str, Value};
176    ///
177    /// let yaml = "- a\n- b\n- c\n";
178    /// let value: Value = from_str(yaml).unwrap();
179    /// assert_eq!(value[0].as_str(), Some("a"));
180    /// assert_eq!(value[1].as_str(), Some("b"));
181    /// ```
182    #[track_caller]
183    fn index(&self, index: usize) -> &Self::Output {
184        self.get(index)
185            .expect("index out of bounds or not a sequence")
186    }
187}
188
189impl IndexMut<usize> for Value {
190    /// Mutably index into a YAML sequence.
191    ///
192    /// # Panics
193    ///
194    /// Panics if the value is not a sequence or if the index is out of bounds.
195    #[track_caller]
196    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
197        self.get_mut(index)
198            .expect("index out of bounds or not a sequence")
199    }
200}
201
202impl Index<&str> for Value {
203    type Output = Self;
204
205    /// Index into a YAML mapping by key.
206    ///
207    /// # Panics
208    ///
209    /// Panics if the value is not a mapping or if the key is not found.
210    ///
211    /// # Examples
212    ///
213    /// ```rust
214    /// use noyalib::{from_str, Value};
215    ///
216    /// let yaml = "name: test\nversion: 1\n";
217    /// let value: Value = from_str(yaml).unwrap();
218    /// assert_eq!(value["name"].as_str(), Some("test"));
219    /// assert_eq!(value["version"].as_i64(), Some(1));
220    /// ```
221    #[track_caller]
222    fn index(&self, key: &str) -> &Self::Output {
223        self.get(key).expect("key not found or not a mapping")
224    }
225}
226
227impl IndexMut<&str> for Value {
228    /// Mutably index into a YAML mapping by key.
229    ///
230    /// # Panics
231    ///
232    /// Panics if the value is not a mapping or if the key is not found.
233    #[track_caller]
234    fn index_mut(&mut self, key: &str) -> &mut Self::Output {
235        self.get_mut(key).expect("key not found or not a mapping")
236    }
237}