tf_provider/
value.rs

1// This file is part of the tf-provider project
2//
3// Copyright (C) ANEO, 2024-2024. All rights reserved.
4//
5// Licensed under the Apache License, Version 2.0 (the "License")
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9//     http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! [`Value`] module
18
19use std::{
20    borrow::Cow,
21    collections::{BTreeMap, BTreeSet},
22    fmt::{Debug, Display},
23    iter::FusedIterator,
24    mem,
25    ops::{Deref, DerefMut},
26};
27
28use serde::{Deserialize, Serialize};
29
30use crate::utils::serde_unknown;
31
32/// Encode either a known value, a null value, or an unknown value as specified by the Terraform protocol.
33///
34/// [`Value`] is closely modeled after [`Option`] where:
35/// - [`Value::Value`] is equivalent to [`Option::Some`],
36/// - [`Value::Null`] is equivalent to [`Option::None`],
37/// - [`Value::Unknown`] has no option counterpart and represent a value that is currently unknown, but will be known later on.
38///
39/// [`Value::Unknown`] is *not* a [`Future`](std::future::Future), but merely a tag.
40#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default, Serialize, Deserialize)]
41#[serde(untagged)]
42pub enum Value<T> {
43    /// Value is present
44    Value(T),
45    /// No value is present
46    #[default]
47    Null,
48    /// Value is unknown
49    #[serde(with = "serde_unknown")]
50    Unknown,
51}
52
53#[derive(Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
54#[serde(untagged)]
55pub enum ValueAny {
56    String(String),
57    Number(i64),
58    Bool(bool),
59    List(Vec<ValueAny>),
60    Map(BTreeMap<String, ValueAny>),
61    #[default]
62    Null,
63    #[serde(with = "serde_unknown")]
64    Unknown,
65}
66
67impl ValueAny {
68    /// Dump the json representation of the value
69    pub fn json(&self) -> String {
70        serde_json::to_string(self).unwrap_or("<invalid>".into())
71    }
72    /// Dump the indented json representation of the value
73    pub fn json_pretty(&self) -> String {
74        serde_json::to_string_pretty(self).unwrap_or("<invalid>".into())
75    }
76}
77
78/// Struct without any field
79#[derive(
80    Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Default, Serialize, Deserialize,
81)]
82pub struct StructEmpty {}
83
84pub type ValueEmpty = Value<StructEmpty>;
85pub type ValueString<'a> = Value<Cow<'a, str>>;
86pub type ValueNumber = Value<i64>;
87pub type ValueBool = Value<bool>;
88pub type ValueList<T> = Value<Vec<T>>;
89pub type ValueSet<T> = Value<BTreeSet<T>>;
90pub type ValueMap<'a, T> = Value<BTreeMap<Cow<'a, str>, T>>;
91
92/// Serde codec to encode a nullable as a vec that has either zero or one element
93pub mod serde_as_vec {
94    use anyhow::anyhow;
95    use serde::{de::Error, ser::SerializeSeq, Deserialize, Serialize};
96
97    use super::Value;
98
99    /// Serialize a nullable Value into a Vec of Values with 0 or 1 element
100    pub fn serialize<T, S>(value: &Value<T>, serializer: S) -> Result<S::Ok, S::Error>
101    where
102        S: serde::Serializer,
103        T: Serialize,
104    {
105        let mut seq = serializer.serialize_seq(Some(value.is_value() as usize))?;
106        if let Value::Value(value) = value {
107            seq.serialize_element(value)?;
108        }
109        seq.end()
110    }
111
112    /// Deserialize a Vec of values into a single, nullable, Value
113    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Value<T>, D::Error>
114    where
115        D: serde::Deserializer<'de>,
116        T: Deserialize<'de>,
117    {
118        let vec: Vec<Value<T>> = Deserialize::deserialize(deserializer)?;
119        let mut iter = vec.into_iter();
120        if let Some(value) = iter.next() {
121            if iter.next().is_none() {
122                Ok(value)
123            } else {
124                Err(anyhow!("Try to store multiple elements in a single Value"))
125                    .map_err(D::Error::custom)
126            }
127        } else {
128            Ok(Value::Null)
129        }
130    }
131}
132
133impl<T> Value<T> {
134    /////////////////////////////////////////////////////////////////////////
135    // Querying the contained values
136    /////////////////////////////////////////////////////////////////////////
137
138    /// Check if the value is known and present
139    #[inline]
140    pub const fn is_value(&self) -> bool {
141        matches!(self, Self::Value(_))
142    }
143
144    /// Check if the value is null
145    #[inline]
146    pub const fn is_null(&self) -> bool {
147        matches!(self, Self::Null)
148    }
149
150    /// Check if the value is unknown
151    #[inline]
152    pub const fn is_unknown(&self) -> bool {
153        matches!(self, Self::Unknown)
154    }
155
156    /////////////////////////////////////////////////////////////////////////
157    // Adapter for working with references
158    /////////////////////////////////////////////////////////////////////////
159
160    /// Converts from `&Value<T>` to `Value<&T>`
161    ///
162    /// # Examples
163    ///
164    /// Calculates the length of a <code>Value<[String]></code> as a <code>Value<[usize]></code>
165    /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
166    /// consuming the original, so this technique uses `as_ref` to first take a `Value` to a
167    /// reference to the value inside the original.
168    ///
169    /// [`map`]: Value::map
170    ///
171    /// ```
172    /// # use tf_provider::value::Value;
173    /// let text: Value<String> = Value::Value("Hello, world!".to_string());
174    /// // First, cast `Value<String>` to `Value<&String>` with `as_ref`,
175    /// // then consume *that* with `map`, leaving `text` on the stack.
176    /// let text_length: Value<usize> = text.as_ref().map(|s| s.len());
177    /// println!("still can print text: {text:?}");
178    /// ```
179    #[inline]
180    pub const fn as_ref(&self) -> Value<&T> {
181        match *self {
182            Self::Value(ref x) => Value::Value(x),
183            Self::Null => Value::Null,
184            Self::Unknown => Value::Unknown,
185        }
186    }
187
188    /// Converts from `&mut Value<T>` to `Value<&mut T>`
189    ///
190    /// # Examples
191    ///
192    /// ```
193    /// # use tf_provider::value::Value;
194    /// let mut x = Value::Value(2);
195    /// match x.as_mut() {
196    ///     Value::Value(v) => *v = 42,
197    ///     _ => {},
198    /// }
199    /// assert_eq!(x, Value::Value(42));
200    /// ```
201    #[inline]
202    pub fn as_mut(&mut self) -> Value<&mut T> {
203        match *self {
204            Self::Value(ref mut x) => Value::Value(x),
205            Self::Null => Value::Null,
206            Self::Unknown => Value::Unknown,
207        }
208    }
209
210    /////////////////////////////////////////////////////////////////////////
211    // Getting to contained values
212    /////////////////////////////////////////////////////////////////////////
213
214    /// Returns the contained [`Value::Value`] value, consuming the self value.
215    ///
216    /// # Panics
217    ///
218    /// Panics if the value is [`Value::Null`] or [`Value::Unknown`] with a custom panic message provided by msg.
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// # use tf_provider::value::Value;
224    /// let x = Value::Value("value");
225    /// assert_eq!(x.expect("message"), "value");
226    /// ```
227    ///
228    /// ```should_panic
229    /// # use tf_provider::value::Value;
230    /// let x: Value<&str> = Value::Null;
231    /// x.expect("message"); // panics with `message`
232    /// ```
233    ///
234    /// ```should_panic
235    /// # use tf_provider::value::Value;
236    /// let x: Value<&str> = Value::Unknown;
237    /// x.expect("message"); // panics with `message`
238    /// ```
239    #[inline]
240    pub fn expect(self, msg: &str) -> T {
241        match self {
242            Self::Value(val) => val,
243            Self::Null => panic!("{} (Null)", msg),
244            Self::Unknown => panic!("{} (Unknown)", msg),
245        }
246    }
247
248    /// Returns the contained [`Value::Value`] value, consuming the self value.
249    ///
250    /// Because this function may panic, its use is generally discouraged.
251    /// Instead, prefer to use pattern matching and handle the [`Value::Null`] and [`Value::Unknown`] cases explicitly,
252    /// or call [`unwrap_or`], [`unwrap_or_else`], or [`unwrap_or_default`].
253    ///
254    /// [`unwrap_or`]: Value::unwrap_or
255    /// [`unwrap_or_else`]: Value::unwrap_or_else
256    /// [`unwrap_or_default`]: Value::unwrap_or_default
257    ///
258    /// # Panics
259    ///
260    /// Panics if the value is [`Value::Null`] or [`Value::Unknown`].
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// # use tf_provider::value::Value;
266    /// let x = Value::Value("value");
267    /// assert_eq!(x.unwrap(), "value");
268    /// ```
269    ///
270    /// ```should_panic
271    /// # use tf_provider::value::Value;
272    /// let x: Value<&str> = Value::Null;
273    /// assert_eq!(x.unwrap(), "value"); // panics
274    /// ```
275    ///
276    /// ```should_panic
277    /// # use tf_provider::value::Value;
278    /// let x: Value<&str> = Value::Unknown;
279    /// assert_eq!(x.unwrap(), "value"); // panics
280    /// ```
281    #[inline]
282    pub fn unwrap(self) -> T {
283        match self {
284            Self::Value(x) => x,
285            Self::Null => panic!("called `Value::unwrap()` on a `Null` value"),
286            Self::Unknown => panic!("called `Value::unwrap()` on an `Unknown` value"),
287        }
288    }
289
290    /// Returns the contained Some value or a provided default.
291    ///
292    /// Arguments passed to `unwrap_or` are eagerly evaluated;
293    /// if you are passing the result of a function call, it is recommended to use [`unwrap_or_else`], which is lazily evaluated.
294    ///
295    /// [`unwrap_or_else`]: Value::unwrap_or_else
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// # use tf_provider::value::Value;
301    /// assert_eq!(Value::Value("car").unwrap_or("bike"), "car");
302    /// assert_eq!(Value::Null.unwrap_or("bike"), "bike");
303    /// assert_eq!(Value::Unknown.unwrap_or("bike"), "bike");
304    /// ```
305    #[inline]
306    pub fn unwrap_or(self, default: T) -> T {
307        match self {
308            Self::Value(x) => x,
309            _ => default,
310        }
311    }
312
313    /// Returns the contained [`Value::Value`] value or computes it from a closure.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// # use tf_provider::value::Value;
319    /// let k = 10;
320    /// assert_eq!(Value::Value(4).unwrap_or_else(|| 2 * k), 4);
321    /// assert_eq!(Value::Null.unwrap_or_else(|| 2 * k), 20);
322    /// assert_eq!(Value::Unknown.unwrap_or_else(|| 2 * k), 20);
323    /// ```
324    #[inline]
325    pub fn unwrap_or_else<F>(self, f: F) -> T
326    where
327        F: FnOnce() -> T,
328    {
329        match self {
330            Self::Value(x) => x,
331            _ => f(),
332        }
333    }
334
335    /// Returns the contained [`Value::Value`] value or a default.
336    ///
337    /// Consumes the `self` argument then, if [`Value::Value`], returns the contained value,
338    /// otherwise if [`Value::Null`] or [`Value::Unknown`], returns the [default value] for that type.
339    ///
340    /// # Examples
341    ///
342    /// ```
343    /// # use tf_provider::value::Value;
344    /// let x: Value<u32> = Value::Value(12);
345    /// let y: Value<u32> = Value::Null;
346    /// let z: Value<u32> = Value::Unknown;
347    ///
348    /// assert_eq!(x.unwrap_or_default(), 12);
349    /// assert_eq!(y.unwrap_or_default(), 0);
350    /// assert_eq!(z.unwrap_or_default(), 0);
351    /// ```
352    ///
353    /// [default value]: Default::default
354    #[inline]
355    pub fn unwrap_or_default(self) -> T
356    where
357        T: Default,
358    {
359        match self {
360            Self::Value(x) => x,
361            _ => Default::default(),
362        }
363    }
364
365    /////////////////////////////////////////////////////////////////////////
366    // Transforming contained values
367    /////////////////////////////////////////////////////////////////////////
368
369    /// Maps a `Value<T>` to `Value<U>` by applying a function to a contained value (if `Value::Value`)
370    /// or returns `Value::Null` (if `Value::Null`) and `Value::Unknown` (if `Value::Unknown`).
371    ///
372    /// # Examples
373    ///
374    /// Calculates the length of a <code>Value<[String]></code> as a
375    /// <code>Value<[usize]></code>, consuming the original:
376    /// ```
377    /// # use tf_provider::value::Value;
378    /// let maybe_some_string = Value::Value(String::from("Hello, World!"));
379    /// // `Value::map` takes self *by value*, consuming `maybe_some_string`
380    /// let maybe_some_len = maybe_some_string.map(|s| s.len());
381    /// assert_eq!(maybe_some_len, Value::Value(13));
382    ///
383    /// let x: Value<&str> = Value::Null;
384    /// assert_eq!(x.map(|s| s.len()), Value::Null);
385    ///
386    /// let y: Value<&str> = Value::Unknown;
387    /// assert_eq!(y.map(|s| s.len()), Value::Unknown);
388    /// ```
389    #[inline]
390    pub fn map<U, F>(self, f: F) -> Value<U>
391    where
392        F: FnOnce(T) -> U,
393    {
394        match self {
395            Self::Value(x) => Value::Value(f(x)),
396            Self::Null => Value::Null,
397            Self::Unknown => Value::Unknown,
398        }
399    }
400
401    /// Calls a function with a reference to the contained value if [`Value::Value`].
402    ///
403    /// Returns the original value.
404    ///
405    /// # Examples
406    ///
407    /// ```
408    /// # use tf_provider::value::Value;
409    /// let x: Value<i32> = Value::Value(2);
410    /// // prints "got: 2"
411    /// x.inspect(|x| println!("got: {x}"));
412    ///
413    /// let x: Value<i32> = Value::Null;
414    /// // Does not print anything
415    /// x.inspect(|x| println!("got: {x}"));
416    ///
417    /// let x: Value<i32> = Value::Unknown;
418    /// // Does not print anything
419    /// x.inspect(|x| println!("got: {x}"));
420    /// ```
421    #[inline]
422    pub fn inspect<F>(self, f: F) -> Self
423    where
424        F: FnOnce(&T),
425    {
426        if let Self::Value(ref x) = self {
427            f(x);
428        }
429        self
430    }
431
432    /// Returns the provided default result (if null or unknown),
433    /// or applies a function to the contained value (if any).
434    ///
435    /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
436    /// the result of a function call, it is recommended to use [`map_or_else`],
437    /// which is lazily evaluated.
438    ///
439    /// [`map_or_else`]: Value::map_or_else
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// # use tf_provider::value::Value;
445    /// let x = Value::Value("foo");
446    /// assert_eq!(x.map_or(42, |v| v.len()), 3);
447    ///
448    /// let x: Value<&str> = Value::Null;
449    /// assert_eq!(x.map_or(42, |v| v.len()), 42);
450    ///
451    /// let x: Value<&str> = Value::Unknown;
452    /// assert_eq!(x.map_or(42, |v| v.len()), 42);
453    /// ```
454    #[inline]
455    pub fn map_or<U, F>(self, default: U, f: F) -> U
456    where
457        F: FnOnce(T) -> U,
458    {
459        match self {
460            Self::Value(x) => f(x),
461            _ => default,
462        }
463    }
464
465    /// Computes a default function result (if null or unknown), or
466    /// applies a different function to the contained value (if any).
467    ///
468    /// # Examples
469    ///
470    /// ```
471    /// # use tf_provider::value::Value;
472    /// let k = 21;
473    ///
474    /// let x = Value::Value("foo");
475    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
476    ///
477    /// let x: Value<&str> = Value::Null;
478    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
479    ///
480    /// let x: Value<&str> = Value::Unknown;
481    /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
482    /// ```
483    #[inline]
484    pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
485    where
486        F: FnOnce(T) -> U,
487        D: FnOnce() -> U,
488    {
489        match self {
490            Self::Value(x) => f(x),
491            _ => default(),
492        }
493    }
494
495    /// Transforms the `Value<T>` into a [`Result<T, E>`], mapping [`Value::Value(v)`] to
496    /// [`Ok(v)`], [`Value::Null`] to [`Err(err)`], and [`Value::Unknown`] to [`Err(err)`].
497    ///
498    /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
499    /// result of a function call, it is recommended to use [`ok_or_else`], which is
500    /// lazily evaluated.
501    ///
502    /// [`Ok(v)`]: Ok
503    /// [`Err(err)`]: Err
504    /// [`Value::Value(v)`]: Value::Value
505    /// [`ok_or_else`]: Value::ok_or_else
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// # use tf_provider::value::Value;
511    /// let x = Value::Value("foo");
512    /// assert_eq!(x.ok_or(0), Ok("foo"));
513    ///
514    /// let x: Value<&str> = Value::Null;
515    /// assert_eq!(x.ok_or(0), Err(0));
516    ///
517    /// let x: Value<&str> = Value::Unknown;
518    /// assert_eq!(x.ok_or(0), Err(0));
519    /// ```
520    #[inline]
521    pub fn ok_or<E>(self, err: E) -> Result<T, E> {
522        match self {
523            Self::Value(x) => Ok(x),
524            _ => Err(err),
525        }
526    }
527
528    /// Transforms the `Value<T>` into a [`Result<T, E>`], mapping [`Value::Value(v)`] to
529    /// [`Ok(v)`], [`Value::Null`] to [`Err(err())`], and [`Value::Unknown`] to [`Err(err())`].
530    ///
531    /// [`Ok(v)`]: Ok
532    /// [`Err(err())`]: Err
533    /// [`Value::Value(v)`]: Value::Value
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// # use tf_provider::value::Value;
539    /// let x = Value::Value("foo");
540    /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
541    ///
542    /// let x: Value<&str> = Value::Null;
543    /// assert_eq!(x.ok_or_else(|| 0), Err(0));
544    ///
545    /// let x: Value<&str> = Value::Unknown;
546    /// assert_eq!(x.ok_or_else(|| 0), Err(0));
547    /// ```
548    #[inline]
549    pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
550    where
551        F: FnOnce() -> E,
552    {
553        match self {
554            Self::Value(x) => Ok(x),
555            _ => Err(err()),
556        }
557    }
558
559    /// Converts from `Value<T>` (or `&Value<T>`) to `Value<&T::Target>`.
560    ///
561    /// Leaves the original Option in-place, creating a new one with a reference
562    /// to the original one, additionally coercing the contents via [`Deref`].
563    ///
564    /// # Examples
565    ///
566    /// ```
567    /// # use tf_provider::value::Value;
568    /// let x: Value<String> = Value::Value("hey".to_owned());
569    /// assert_eq!(x.as_deref(), Value::Value("hey"));
570    ///
571    /// let x: Value<String> = Value::Null;
572    /// assert_eq!(x.as_deref(), Value::Null);
573    ///
574    /// let x: Value<String> = Value::Unknown;
575    /// assert_eq!(x.as_deref(), Value::Unknown);
576    /// ```
577    #[inline]
578    pub fn as_deref(&self) -> Value<&T::Target>
579    where
580        T: Deref,
581    {
582        match self.as_ref() {
583            Value::Value(x) => Value::Value(x.deref()),
584            Value::Null => Value::Null,
585            Value::Unknown => Value::Unknown,
586        }
587    }
588
589    /// Converts from `Value<T>` (or `&mut Value<T>`) to `Value<&mut T::Target>`.
590    ///
591    /// Leaves the original `Value` in-place, creating a new one containing a mutable reference to
592    /// the inner type's [`Deref::Target`] type.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// # use tf_provider::value::Value;
598    /// let mut x: Value<String> = Value::Value("hey".to_owned());
599    /// assert_eq!(x.as_deref_mut().map(|x| {
600    ///     x.make_ascii_uppercase();
601    ///     x
602    /// }), Value::Value("HEY".to_owned().as_mut_str()));
603    ///
604    /// let mut x: Value<String> = Value::Null;
605    /// assert_eq!(x.as_deref_mut().map(|x| {
606    ///     x.make_ascii_uppercase();
607    ///     x
608    /// }), Value::Null);
609    ///
610    /// let mut x: Value<String> = Value::Unknown;
611    /// assert_eq!(x.as_deref_mut().map(|x| {
612    ///     x.make_ascii_uppercase();
613    ///     x
614    /// }), Value::Unknown);
615    /// ```
616    #[inline]
617    pub fn as_deref_mut(&mut self) -> Value<&mut T::Target>
618    where
619        T: DerefMut,
620    {
621        match self.as_mut() {
622            Value::Value(x) => Value::Value(x.deref_mut()),
623            Value::Null => Value::Null,
624            Value::Unknown => Value::Unknown,
625        }
626    }
627
628    /// Transforms the `Value<T>` into a [`Option<T>`], mapping [`Value::Value(v)`] to
629    /// [`Some(v)`], [`Value::Null`] to [`None`], and [`Value::Unknown`] to [`None`].
630    ///
631    /// [`Some(v)`]: Some
632    /// [`Value::Value(v)`]: Value::Value
633    ///
634    /// # Examples
635    ///
636    /// ```
637    /// # use tf_provider::value::Value;
638    /// let x = Value::Value("foo");
639    /// assert_eq!(x.as_option(), Some("foo"));
640    ///
641    /// let x: Value<&str> = Value::Null;
642    /// assert_eq!(x.as_option(), None);
643    ///
644    /// let x: Value<&str> = Value::Unknown;
645    /// assert_eq!(x.as_option(), None);
646    /// ```
647    #[inline]
648    pub fn as_option(self) -> Option<T> {
649        match self {
650            Self::Value(x) => Some(x),
651            _ => None,
652        }
653    }
654
655    /// Transforms the `&Value<T>` into a [`Option<&T>`], mapping [`Value::Value(v)`] to
656    /// [`Some(v)`], [`Value::Null`] to [`None`], and [`Value::Unknown`] to [`None`].
657    ///
658    /// [`Some(v)`]: Some
659    /// [`Value::Value(v)`]: Value::Value
660    ///
661    /// # Examples
662    ///
663    /// Calculates the length of a <code>Value<[String]></code> as an <code>Option<[usize]></code>
664    /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
665    /// consuming the original, so this technique uses `as_ref` to first take a `Value` to a
666    /// reference to the value inside the original.
667    ///
668    /// [`map`]: Option::map
669    ///
670    /// ```
671    /// # use tf_provider::value::Value;
672    /// let text: Value<String> = Value::Value("Hello, world!".to_string());
673    /// // First, cast `Value<String>` to `Option<&String>` with `as_ref_option`
674    /// let text_ref: Option<&String> = text.as_ref_option();
675    /// // then consume *that* with `map`, leaving `text` on the stack.
676    /// let text_length: Option<usize> = text_ref.map(|s| s.len());
677    /// println!("still can print text: {text:?}");
678    /// ```
679    #[inline]
680    pub fn as_ref_option(&self) -> Option<&T> {
681        match self {
682            Self::Value(x) => Some(x),
683            _ => None,
684        }
685    }
686
687    /// Transforms the `&mut Value<T>` into a [`Option<&mut T>`], mapping [`Value::Value(v)`] to
688    /// [`Some(v)`], [`Value::Null`] to [`None`], and [`Value::Unknown`] to [`None`].
689    ///
690    /// [`Some(v)`]: Some
691    /// [`Value::Value(v)`]: Value::Value
692    ///
693    /// # Examples
694    ///
695    /// Calculates the length of a <code>Value<[String]></code> as an <code>Option<[usize]></code>
696    /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
697    /// consuming the original, so this technique uses `as_ref` to first take a `Value` to a
698    /// reference to the value inside the original.
699    ///
700    /// [`map`]: Option::map
701    ///
702    /// ```
703    /// # use tf_provider::value::Value;
704    /// let mut x = Value::Value(2);
705    /// match x.as_mut_option() {
706    ///     Some(v) => *v = 42,
707    ///     None => {},
708    /// }
709    /// assert_eq!(x, Value::Value(42));
710    /// ```
711    #[inline]
712    pub fn as_mut_option(&mut self) -> Option<&mut T> {
713        match self {
714            Self::Value(x) => Some(x),
715            _ => None,
716        }
717    }
718
719    /// Converts from `Value<T>` (or `&Value<T>`) to `Option<&T::Target>`, mapping [`Value::Value(v)`] to
720    /// [`Some(v)`], [`Value::Null`] to [`None`], and [`Value::Unknown`] to [`None`].
721    ///
722    /// [`Some(v)`]: Some
723    /// [`Value::Value(v)`]: Value::Value
724    ///
725    /// Leaves the original Option in-place, creating a new one with a reference
726    /// to the original one, additionally coercing the contents via [`Deref`].
727    ///
728    /// # Examples
729    ///
730    /// ```
731    /// # use tf_provider::value::Value;
732    /// let x: Value<String> = Value::Value("hey".to_owned());
733    /// assert_eq!(x.as_deref_option(), Some("hey"));
734    ///
735    /// let x: Value<String> = Value::Null;
736    /// assert_eq!(x.as_deref_option(), None);
737    ///
738    /// let x: Value<String> = Value::Unknown;
739    /// assert_eq!(x.as_deref_option(), None);
740    /// ```
741    #[inline]
742    pub fn as_deref_option(&self) -> Option<&T::Target>
743    where
744        T: Deref,
745    {
746        match self {
747            Self::Value(x) => Some(x),
748            _ => None,
749        }
750    }
751
752    /// Converts from `Value<T>` (or `&mut Value<T>`) to `Option<&mut T::Target>`, mapping [`Value::Value(v)`] to
753    /// [`Some(v)`], [`Value::Null`] to [`None`], and [`Value::Unknown`] to [`None`].
754    ///
755    /// [`Some(v)`]: Some
756    /// [`Value::Value(v)`]: Value::Value
757    ///
758    /// Leaves the original `Value` in-place, creating a new one containing a mutable reference to
759    /// the inner type's [`Deref::Target`] type.
760    ///
761    /// # Examples
762    ///
763    /// ```
764    /// # use tf_provider::value::Value;
765    /// let mut x: Value<String> = Value::Value("hey".to_owned());
766    /// assert_eq!(x.as_deref_mut_option().map(|x| {
767    ///     x.make_ascii_uppercase();
768    ///     x
769    /// }), Some("HEY".to_owned().as_mut_str()));
770    ///
771    /// let mut x: Value<String> = Value::Null;
772    /// assert_eq!(x.as_deref_mut_option().map(|x| {
773    ///     x.make_ascii_uppercase();
774    ///     x
775    /// }), None);
776    ///
777    /// let mut x: Value<String> = Value::Unknown;
778    /// assert_eq!(x.as_deref_mut_option().map(|x| {
779    ///     x.make_ascii_uppercase();
780    ///     x
781    /// }), None);
782    /// ```
783    #[inline]
784    pub fn as_deref_mut_option(&mut self) -> Option<&mut T::Target>
785    where
786        T: DerefMut,
787    {
788        match self {
789            Self::Value(x) => Some(x),
790            _ => None,
791        }
792    }
793
794    /////////////////////////////////////////////////////////////////////////
795    // Iterator constructors
796    /////////////////////////////////////////////////////////////////////////
797
798    /// Returns an iterator over the possibly contained value.
799    ///
800    /// # Examples
801    ///
802    /// ```
803    /// # use tf_provider::value::Value;
804    /// let x = Value::Value(4);
805    /// assert_eq!(x.iter().next(), Some(&4));
806    ///
807    /// let x: Value<u32> = Value::Null;
808    /// assert_eq!(x.iter().next(), None);
809    ///
810    /// let x: Value<u32> = Value::Unknown;
811    /// assert_eq!(x.iter().next(), None);
812    /// ```
813    #[inline]
814    pub fn iter(&self) -> Iter<'_, T> {
815        Iter {
816            inner: Item { val: self.as_ref() },
817        }
818    }
819
820    /// Returns a mutable iterator over the possibly contained value.
821    ///
822    /// # Examples
823    ///
824    /// ```
825    /// # use tf_provider::value::Value;
826    /// let mut x = Value::Value(4);
827    /// match x.iter_mut().next() {
828    ///     Some(v) => *v = 42,
829    ///     None => {},
830    /// }
831    /// assert_eq!(x, Value::Value(42));
832    ///
833    /// let mut x: Value<u32> = Value::Null;
834    /// assert_eq!(x.iter_mut().next(), None);
835    ///
836    /// let mut x: Value<u32> = Value::Unknown;
837    /// assert_eq!(x.iter_mut().next(), None);
838    /// ```
839    #[inline]
840    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
841        IterMut {
842            inner: Item { val: self.as_mut() },
843        }
844    }
845
846    /////////////////////////////////////////////////////////////////////////
847    // Boolean operations on the values, eager and lazy
848    /////////////////////////////////////////////////////////////////////////
849
850    /// Returns [`Value::Null`] if it is [`Value::Null`],
851    /// returns [`Value::Unknown`] if it is [`Value::Unknown`],
852    /// otherwise returns `rhs`.
853    ///
854    /// Arguments passed to `and` are eagerly evaluated; if you are passing the
855    /// result of a function call, it is recommended to use [`and_then`], which is
856    /// lazily evaluated.
857    ///
858    /// [`and_then`]: Value::and_then
859    ///
860    /// # Examples
861    ///
862    /// ```
863    /// # use tf_provider::value::Value;
864    /// let x = Value::Value(2);
865    /// let y: Value<&str> = Value::Null;
866    /// assert_eq!(x.and(y), Value::Null);
867    ///
868    /// let x = Value::Value(2);
869    /// let y: Value<&str> = Value::Unknown;
870    /// assert_eq!(x.and(y), Value::Unknown);
871    ///
872    /// let x: Value<u32> = Value::Null;
873    /// let y = Value::Value("foo");
874    /// assert_eq!(x.and(y), Value::Null);
875    ///
876    /// let x: Value<u32> = Value::Unknown;
877    /// let y = Value::Value("foo");
878    /// assert_eq!(x.and(y), Value::Unknown);
879    ///
880    /// let x = Value::Value(2);
881    /// let y = Value::Value("foo");
882    /// assert_eq!(x.and(y), Value::Value("foo"));
883    ///
884    /// let x: Value<u32> = Value::Null;
885    /// let y: Value<&str> = Value::Null;
886    /// assert_eq!(x.and(y), Value::Null);
887    ///
888    /// let x: Value<u32> = Value::Null;
889    /// let y: Value<&str> = Value::Unknown;
890    /// assert_eq!(x.and(y), Value::Null);
891    ///
892    /// let x: Value<u32> = Value::Unknown;
893    /// let y: Value<&str> = Value::Null;
894    /// assert_eq!(x.and(y), Value::Unknown);
895    ///
896    /// let x: Value<u32> = Value::Unknown;
897    /// let y: Value<&str> = Value::Unknown;
898    /// assert_eq!(x.and(y), Value::Unknown);
899    /// ```
900    #[inline]
901    pub fn and<U>(self, rhs: Value<U>) -> Value<U> {
902        match self {
903            Self::Value(_) => rhs,
904            Self::Null => Value::Null,
905            Self::Unknown => Value::Unknown,
906        }
907    }
908
909    /// Returns [`Value::Null`] if it is [`Value::Null`],
910    /// returns [`Value::Unknown`] if it is [`Value::Unknown`],
911    /// otherwise calls `f` with the wrapped value and returns the result.
912    ///
913    /// Often used to chain fallible operations that may return [`Value::Null`] or [`Value::Unknown`].
914    ///
915    /// # Examples
916    ///
917    /// ```
918    /// # use tf_provider::value::Value;
919    /// let array = [Value::Value(10), Value::Null, Value::Unknown];
920    ///
921    /// let x: Value<&[Value<i32>]> = Value::Value(&array);
922    /// assert_eq!(x.and_then(|slice| slice[0]), Value::Value(10));
923    /// assert_eq!(x.and_then(|slice| slice[1]), Value::Null);
924    /// assert_eq!(x.and_then(|slice| slice[2]), Value::Unknown);
925    ///
926    /// let x: Value<&[Value<i32>]> = Value::Null;
927    /// assert_eq!(x.and_then(|slice| slice[0]), Value::Null);
928    /// assert_eq!(x.and_then(|slice| slice[1]), Value::Null);
929    ///
930    /// let x: Value<&[Value<i32>]> = Value::Unknown;
931    /// assert_eq!(x.and_then(|slice| slice[0]), Value::Unknown);
932    /// assert_eq!(x.and_then(|slice| slice[1]), Value::Unknown);
933    /// ```
934    #[inline]
935    pub fn and_then<U, F>(self, f: F) -> Value<U>
936    where
937        F: FnOnce(T) -> Value<U>,
938    {
939        match self {
940            Self::Value(x) => f(x),
941            Self::Null => Value::Null,
942            Self::Unknown => Value::Unknown,
943        }
944    }
945
946    /// Returns [`Value::Null`] if it is [`Value::Null`],
947    /// returns [`Value::Unknown`] if it is [`Value::Unknown`],
948    /// otherwise calls `predicate` with the wrapped value and returns:
949    ///
950    /// - [`Value::Value(t)`] if `predicate` returns `true` (where `t` is the wrapped
951    ///   value), and
952    /// - [`Value::Null`] if `predicate` returns `false`.
953    ///
954    /// This function works similar to [`Iterator::filter()`]. You can imagine
955    /// the `Value<T>` being an iterator over one or zero elements. `filter()`
956    /// lets you decide which elements to keep.
957    ///
958    /// # Examples
959    ///
960    /// ```rust
961    /// # use tf_provider::value::Value;
962    /// fn is_even(n: &i32) -> bool {
963    ///     n % 2 == 0
964    /// }
965    ///
966    /// assert_eq!(Value::Value(4).filter(is_even), Value::Value(4));
967    /// assert_eq!(Value::Value(3).filter(is_even), Value::Null);
968    /// assert_eq!(Value::Null.filter(is_even), Value::Null);
969    /// assert_eq!(Value::Unknown.filter(is_even), Value::Unknown);
970    /// ```
971    ///
972    /// [`Value::Value(t)`]: Value::Value
973    #[inline]
974    pub fn filter<P>(self, predicate: P) -> Self
975    where
976        P: FnOnce(&T) -> bool,
977    {
978        match self {
979            Self::Value(x) => {
980                if predicate(&x) {
981                    Value::Value(x)
982                } else {
983                    Value::Null
984                }
985            }
986            Self::Null => Value::Null,
987            Self::Unknown => Value::Unknown,
988        }
989    }
990
991    /// Returns the value if it contains a value or is unknown, otherwise returns `rhs`.
992    ///
993    /// Arguments passed to `or` are eagerly evaluated; if you are passing the
994    /// result of a function call, it is recommended to use [`or_else`], which is
995    /// lazily evaluated.
996    ///
997    /// [`or_else`]: Value::or_else
998    ///
999    /// # Examples
1000    ///
1001    /// ```
1002    /// # use tf_provider::value::Value;
1003    /// let x = Value::Value(2);
1004    /// let y = Value::Null;
1005    /// assert_eq!(x.or(y), Value::Value(2));
1006    ///
1007    /// let x = Value::Value(2);
1008    /// let y = Value::Unknown;
1009    /// assert_eq!(x.or(y), Value::Value(2));
1010    ///
1011    /// let x = Value::Value(2);
1012    /// let y = Value::Value(100);
1013    /// assert_eq!(x.or(y), Value::Value(2));
1014    ///
1015    /// let x = Value::Null;
1016    /// let y = Value::Value(100);
1017    /// assert_eq!(x.or(y), Value::Value(100));
1018    ///
1019    /// let x: Value<u32> = Value::Null;
1020    /// let y = Value::Null;
1021    /// assert_eq!(x.or(y), Value::Null);
1022    ///
1023    /// let x: Value<u32> = Value::Null;
1024    /// let y = Value::Unknown;
1025    /// assert_eq!(x.or(y), Value::Unknown);
1026    ///
1027    /// let x = Value::Unknown;
1028    /// let y = Value::Value(100);
1029    /// assert_eq!(x.or(y), Value::Unknown);
1030    ///
1031    /// let x: Value<u32> = Value::Unknown;
1032    /// let y = Value::Null;
1033    /// assert_eq!(x.or(y), Value::Unknown);
1034    ///
1035    /// let x: Value<u32> = Value::Unknown;
1036    /// let y = Value::Unknown;
1037    /// assert_eq!(x.or(y), Value::Unknown);
1038    /// ```
1039    #[inline]
1040    pub fn or(self, rhs: Self) -> Self {
1041        match self {
1042            Self::Value(x) => Value::Value(x),
1043            Self::Null => rhs,
1044            Self::Unknown => Value::Unknown,
1045        }
1046    }
1047
1048    /// Returns the value if it contains a value or is unknown, otherwise calls `f` and
1049    /// returns the result.
1050    ///
1051    /// # Examples
1052    ///
1053    /// ```
1054    /// # use tf_provider::value::Value;
1055    /// fn vikings() -> Value<&'static str> { Value::Value("vikings") }
1056    /// fn nobody() -> Value<&'static str> { Value::Null }
1057    /// fn unknown() -> Value<&'static str> { Value::Unknown }
1058    ///
1059    /// assert_eq!(Value::Value("barbarians").or_else(vikings), Value::Value("barbarians"));
1060    /// assert_eq!(Value::Value("barbarians").or_else(nobody), Value::Value("barbarians"));
1061    /// assert_eq!(Value::Value("barbarians").or_else(unknown), Value::Value("barbarians"));
1062    /// assert_eq!(Value::Null.or_else(vikings), Value::Value("vikings"));
1063    /// assert_eq!(Value::Null.or_else(nobody), Value::Null);
1064    /// assert_eq!(Value::Null.or_else(unknown), Value::Unknown);
1065    /// assert_eq!(Value::Unknown.or_else(vikings), Value::Unknown);
1066    /// assert_eq!(Value::Unknown.or_else(nobody), Value::Unknown);
1067    /// assert_eq!(Value::Unknown.or_else(unknown), Value::Unknown);
1068    /// ```
1069    #[inline]
1070    pub fn or_else<F>(self, f: F) -> Self
1071    where
1072        F: FnOnce() -> Self,
1073    {
1074        match self {
1075            Self::Value(x) => Value::Value(x),
1076            Self::Null => f(),
1077            Self::Unknown => Value::Unknown,
1078        }
1079    }
1080
1081    /////////////////////////////////////////////////////////////////////////
1082    // Misc
1083    /////////////////////////////////////////////////////////////////////////
1084
1085    /// Takes the value out, leaving a [`Value::Null`] in its place.
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// # use tf_provider::value::Value;
1091    /// let mut x = Value::Value(2);
1092    /// let y = x.take();
1093    /// assert_eq!(x, Value::Null);
1094    /// assert_eq!(y, Value::Value(2));
1095    ///
1096    /// let mut x: Value<u32> = Value::Null;
1097    /// let y = x.take();
1098    /// assert_eq!(x, Value::Null);
1099    /// assert_eq!(y, Value::Null);
1100    ///
1101    /// let mut x: Value<u32> = Value::Unknown;
1102    /// let y = x.take();
1103    /// assert_eq!(x, Value::Null);
1104    /// assert_eq!(y, Value::Unknown);
1105    /// ```
1106    pub fn take(&mut self) -> Self {
1107        mem::replace(self, Value::Null)
1108    }
1109
1110    /// Replaces the actual value by the value given in parameter,
1111    /// returning the old value if present,
1112    /// leaving a [`Value::Null`] in its place without deinitializing either one.
1113    ///
1114    /// # Examples
1115    ///
1116    /// ```
1117    /// # use tf_provider::value::Value;
1118    /// let mut x = Value::Value(2);
1119    /// let old = x.replace(5);
1120    /// assert_eq!(x, Value::Value(5));
1121    /// assert_eq!(old, Value::Value(2));
1122    ///
1123    /// let mut x = Value::Null;
1124    /// let old = x.replace(3);
1125    /// assert_eq!(x, Value::Value(3));
1126    /// assert_eq!(old, Value::Null);
1127    ///
1128    /// let mut x = Value::Unknown;
1129    /// let old = x.replace(3);
1130    /// assert_eq!(x, Value::Value(3));
1131    /// assert_eq!(old, Value::Unknown);
1132    /// ```
1133    pub fn replace(&mut self, val: T) -> Self {
1134        mem::replace(self, Value::Value(val))
1135    }
1136
1137    /// Check if the value contains `x`.
1138    ///
1139    /// # Examples
1140    ///
1141    /// ```
1142    /// # use tf_provider::value::Value;
1143    /// assert_eq!(Value::Value(3).contains(&3), true);
1144    /// assert_eq!(Value::Value(2).contains(&3), false);
1145    /// assert_eq!(Value::<i32>::Null.contains(&3), false);
1146    /// assert_eq!(Value::<i32>::Unknown.contains(&3), false);
1147    /// ```
1148    pub fn contains<U>(&self, x: &U) -> bool
1149    where
1150        U: PartialEq<T>,
1151    {
1152        match self {
1153            Self::Value(y) => x.eq(y),
1154            _ => false,
1155        }
1156    }
1157}
1158
1159impl<T> Value<&T> {
1160    /// Maps an `Value<&T>` to an `Value<T>` by copying the contents of the
1161    /// value.
1162    ///
1163    /// # Examples
1164    ///
1165    /// ```
1166    /// # use tf_provider::value::Value;
1167    /// let x = 12;
1168    /// let opt_x = Value::Value(&x);
1169    /// assert_eq!(opt_x, Value::Value(&12));
1170    /// let copied = opt_x.copied();
1171    /// assert_eq!(copied, Value::Value(12));
1172    ///
1173    /// assert_eq!(Value::<&i32>::Null.copied(), Value::Null);
1174    /// assert_eq!(Value::<&i32>::Unknown.copied(), Value::Unknown);
1175    /// ```
1176    pub fn copied(self) -> Value<T>
1177    where
1178        T: Copy,
1179    {
1180        match self {
1181            Self::Value(&x) => Value::Value(x),
1182            Self::Null => Value::Null,
1183            Self::Unknown => Value::Unknown,
1184        }
1185    }
1186
1187    /// Maps an `Value<&T>` to an `Value<T>` by cloning the contents of the
1188    /// value.
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```
1193    /// # use tf_provider::value::Value;
1194    /// let x = vec![1, 4];
1195    /// let opt_x = Value::Value(&x);
1196    /// assert_eq!(opt_x, Value::Value(&vec![1, 4]));
1197    /// let cloned = opt_x.cloned();
1198    /// assert_eq!(cloned, Value::Value(vec![1, 4]));
1199    ///
1200    /// assert_eq!(Value::<&Vec<i32>>::Null.cloned(), Value::Null);
1201    /// assert_eq!(Value::<&Vec<i32>>::Unknown.cloned(), Value::Unknown);
1202    /// ```
1203    pub fn cloned(self) -> Value<T>
1204    where
1205        T: Clone,
1206    {
1207        match self {
1208            Self::Value(x) => Value::Value(x.clone()),
1209            Self::Null => Value::Null,
1210            Self::Unknown => Value::Unknown,
1211        }
1212    }
1213}
1214impl<T> Value<&mut T> {
1215    /// Maps an `Value<&mut T>` to an `Value<T>` by copying the contents of the
1216    /// value.
1217    ///
1218    /// # Examples
1219    ///
1220    /// ```
1221    /// # use tf_provider::value::Value;
1222    /// let mut x = 12;
1223    /// let opt_x = Value::Value(&mut x);
1224    /// assert_eq!(opt_x, Value::Value(&mut 12));
1225    /// let copied = opt_x.copied();
1226    /// assert_eq!(copied, Value::Value(12));
1227    ///
1228    /// assert_eq!(Value::<&mut i32>::Null.copied(), Value::Null);
1229    /// assert_eq!(Value::<&mut i32>::Unknown.copied(), Value::Unknown);
1230    /// ```
1231    pub fn copied(self) -> Value<T>
1232    where
1233        T: Copy,
1234    {
1235        match self {
1236            Self::Value(&mut x) => Value::Value(x),
1237            Self::Null => Value::Null,
1238            Self::Unknown => Value::Unknown,
1239        }
1240    }
1241
1242    /// Maps an `Value<&mut T>` to an `Value<T>` by cloning the contents of the
1243    /// value.
1244    ///
1245    /// # Examples
1246    ///
1247    /// ```
1248    /// # use tf_provider::value::Value;
1249    /// let mut x = vec![1, 4];
1250    /// let opt_x = Value::Value(&mut x);
1251    /// assert_eq!(opt_x, Value::Value(&mut vec![1, 4]));
1252    /// let cloned = opt_x.cloned();
1253    /// assert_eq!(cloned, Value::Value(vec![1, 4]));
1254    ///
1255    /// assert_eq!(Value::<&mut Vec<i32>>::Null.cloned(), Value::Null);
1256    /// assert_eq!(Value::<&mut Vec<i32>>::Unknown.cloned(), Value::Unknown);
1257    /// ```
1258    pub fn cloned(self) -> Value<T>
1259    where
1260        T: Clone,
1261    {
1262        match self {
1263            Self::Value(x) => Value::Value(x.clone()),
1264            Self::Null => Value::Null,
1265            Self::Unknown => Value::Unknown,
1266        }
1267    }
1268}
1269
1270impl<'a> Value<Cow<'a, str>> {
1271    /// Maps a `&'a Value<Cow<'a, str>>` to `&'a str`
1272    ///
1273    /// If the value is null or unknown, returns "".
1274    #[inline]
1275    pub fn as_str(&'a self) -> &'a str {
1276        match self {
1277            Self::Value(x) => x.as_ref(),
1278            _ => "",
1279        }
1280    }
1281
1282    /// Maps a `&'a Value<Cow<'a, str>>` to `&'a [u8]`
1283    ///
1284    /// If the value is null or unknown, returns b"".
1285    #[inline]
1286    pub fn as_bytes(&'a self) -> &'a [u8] {
1287        match self {
1288            Self::Value(x) => x.as_bytes(),
1289            _ => b"",
1290        }
1291    }
1292
1293    /// Maps a `Value<Cow<'a, str>>` to `Value<Cow<'b, str>>`,
1294    /// extending the lifetime of the content.
1295    ///
1296    /// If the value is [`Value::Null`], returns [`Value::Null`].
1297    /// If the value is [`Value::Unknown`], returns [`Value::Unknown`].
1298    ///
1299    /// # Remarks
1300    ///
1301    /// If the value is owned, it is moved into the return value without cloning.
1302    /// If the value is borrowed, it is cloned to make it owned.
1303    #[inline]
1304    pub fn extend<'b>(self) -> Value<Cow<'b, str>> {
1305        match self {
1306            Value::Value(Cow::Borrowed(s)) => Value::Value(Cow::from(s.to_owned())),
1307            Value::Value(Cow::Owned(s)) => Value::Value(Cow::from(s)),
1308            Value::Null => Value::Null,
1309            Value::Unknown => Value::Unknown,
1310        }
1311    }
1312}
1313impl<'a> Value<&'a Cow<'a, str>> {
1314    /// Maps a `&Value<&'a Cow<'a, str>>` to `&'a str`
1315    ///
1316    /// If the value is null or unknown, returns "".
1317    #[inline]
1318    pub fn as_str(&self) -> &'a str {
1319        match *self {
1320            Self::Value(x) => x.as_ref(),
1321            _ => "",
1322        }
1323    }
1324
1325    /// Maps a `&Value<&'a Cow<'a, str>>` to `&'a [u8]`
1326    ///
1327    /// If the value is null or unknown, returns b"".
1328    #[inline]
1329    pub fn as_bytes(&self) -> &'a [u8] {
1330        match *self {
1331            Self::Value(x) => x.as_bytes(),
1332            _ => b"",
1333        }
1334    }
1335}
1336
1337impl<T> IntoIterator for Value<T> {
1338    type Item = T;
1339    type IntoIter = IntoIter<T>;
1340
1341    #[inline]
1342    fn into_iter(self) -> IntoIter<T> {
1343        IntoIter {
1344            inner: Item { val: self },
1345        }
1346    }
1347}
1348
1349impl<'a, T> IntoIterator for &'a Value<T> {
1350    type Item = &'a T;
1351    type IntoIter = Iter<'a, T>;
1352
1353    fn into_iter(self) -> Iter<'a, T> {
1354        self.iter()
1355    }
1356}
1357
1358impl<'a, T> IntoIterator for &'a mut Value<T> {
1359    type Item = &'a mut T;
1360    type IntoIter = IterMut<'a, T>;
1361
1362    fn into_iter(self) -> IterMut<'a, T> {
1363        self.iter_mut()
1364    }
1365}
1366
1367impl<T: Debug> Debug for Value<T> {
1368    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1369        match self {
1370            Self::Value(value) => Debug::fmt(value, f),
1371            Self::Null => f.write_str("Null"),
1372            Self::Unknown => f.write_str("Unknown"),
1373        }
1374    }
1375}
1376
1377impl Debug for ValueAny {
1378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1379        match self {
1380            Self::String(value) => Debug::fmt(value, f),
1381            Self::Number(value) => Debug::fmt(value, f),
1382            Self::Bool(value) => Debug::fmt(value, f),
1383            Self::List(value) => Debug::fmt(value, f),
1384            Self::Map(value) => Debug::fmt(value, f),
1385            Self::Null => f.write_str("Null"),
1386            Self::Unknown => f.write_str("Unknown"),
1387        }
1388    }
1389}
1390
1391impl<T> From<T> for Value<T> {
1392    #[inline]
1393    fn from(value: T) -> Self {
1394        Self::Value(value)
1395    }
1396}
1397impl<'a, T> From<&'a Value<T>> for Value<&'a T> {
1398    #[inline]
1399    fn from(value: &'a Value<T>) -> Self {
1400        value.as_ref()
1401    }
1402}
1403impl<'a, T> From<&'a mut Value<T>> for Value<&'a mut T> {
1404    #[inline]
1405    fn from(value: &'a mut Value<T>) -> Self {
1406        value.as_mut()
1407    }
1408}
1409impl<T> From<Option<T>> for Value<T> {
1410    #[inline]
1411    fn from(value: Option<T>) -> Self {
1412        match value {
1413            Some(x) => Self::Value(x),
1414            None => Self::Null,
1415        }
1416    }
1417}
1418
1419impl<'a> From<&'a str> for Value<Cow<'a, str>> {
1420    fn from(value: &'a str) -> Self {
1421        Self::Value(Cow::Borrowed(value))
1422    }
1423}
1424impl From<String> for Value<Cow<'_, str>> {
1425    fn from(value: String) -> Self {
1426        Self::Value(Cow::Owned(value))
1427    }
1428}
1429
1430impl<'a> Deref for Value<Cow<'a, str>> {
1431    type Target = str;
1432
1433    fn deref(&self) -> &Self::Target {
1434        self.as_str()
1435    }
1436}
1437
1438impl Display for Value<Cow<'_, str>> {
1439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1440        f.write_str(self.as_str())
1441    }
1442}
1443
1444#[derive(Clone, Debug)]
1445struct Item<A> {
1446    val: Value<A>,
1447}
1448
1449impl<A> Iterator for Item<A> {
1450    type Item = A;
1451
1452    #[inline]
1453    fn next(&mut self) -> Option<A> {
1454        self.val.take().as_option()
1455    }
1456
1457    #[inline]
1458    fn size_hint(&self) -> (usize, Option<usize>) {
1459        match self.val {
1460            Value::Value(_) => (1, Some(1)),
1461            _ => (0, Some(0)),
1462        }
1463    }
1464}
1465
1466impl<A> DoubleEndedIterator for Item<A> {
1467    #[inline]
1468    fn next_back(&mut self) -> Option<A> {
1469        self.val.take().as_option()
1470    }
1471}
1472
1473impl<A> ExactSizeIterator for Item<A> {}
1474impl<A> FusedIterator for Item<A> {}
1475
1476#[derive(Debug)]
1477pub struct Iter<'a, A: 'a> {
1478    inner: Item<&'a A>,
1479}
1480
1481impl<'a, A> Iterator for Iter<'a, A> {
1482    type Item = &'a A;
1483
1484    #[inline]
1485    fn next(&mut self) -> Option<&'a A> {
1486        self.inner.next()
1487    }
1488    #[inline]
1489    fn size_hint(&self) -> (usize, Option<usize>) {
1490        self.inner.size_hint()
1491    }
1492}
1493
1494impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1495    #[inline]
1496    fn next_back(&mut self) -> Option<&'a A> {
1497        self.inner.next_back()
1498    }
1499}
1500
1501impl<A> ExactSizeIterator for Iter<'_, A> {}
1502
1503impl<A> FusedIterator for Iter<'_, A> {}
1504
1505impl<A> Clone for Iter<'_, A> {
1506    #[inline]
1507    fn clone(&self) -> Self {
1508        Iter {
1509            inner: self.inner.clone(),
1510        }
1511    }
1512}
1513
1514#[derive(Debug)]
1515pub struct IterMut<'a, A: 'a> {
1516    inner: Item<&'a mut A>,
1517}
1518
1519impl<'a, A> Iterator for IterMut<'a, A> {
1520    type Item = &'a mut A;
1521
1522    #[inline]
1523    fn next(&mut self) -> Option<&'a mut A> {
1524        self.inner.next()
1525    }
1526    #[inline]
1527    fn size_hint(&self) -> (usize, Option<usize>) {
1528        self.inner.size_hint()
1529    }
1530}
1531
1532impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1533    #[inline]
1534    fn next_back(&mut self) -> Option<&'a mut A> {
1535        self.inner.next_back()
1536    }
1537}
1538
1539impl<A> ExactSizeIterator for IterMut<'_, A> {}
1540
1541impl<A> FusedIterator for IterMut<'_, A> {}
1542
1543pub struct IntoIter<A> {
1544    inner: Item<A>,
1545}
1546
1547impl<A> Iterator for IntoIter<A> {
1548    type Item = A;
1549
1550    #[inline]
1551    fn next(&mut self) -> Option<A> {
1552        self.inner.next()
1553    }
1554    #[inline]
1555    fn size_hint(&self) -> (usize, Option<usize>) {
1556        self.inner.size_hint()
1557    }
1558}
1559
1560impl<A> DoubleEndedIterator for IntoIter<A> {
1561    #[inline]
1562    fn next_back(&mut self) -> Option<A> {
1563        self.inner.next_back()
1564    }
1565}
1566
1567impl<A> ExactSizeIterator for IntoIter<A> {}
1568
1569impl<A> FusedIterator for IntoIter<A> {}