Skip to main content

cbor_core/
value.rs

1use std::collections::BTreeMap;
2use std::hash::{Hash, Hasher};
3use std::{cmp, io};
4
5use crate::{ArgLength, Array, CtrlByte, DataType, Error, Float, Integer, Major, Map, Result, SimpleValue, Tag};
6
7fn u128_from_bytes(bytes: &[u8]) -> Result<u128> {
8    let mut buf = [0_u8; 16];
9    let offset = buf.len().checked_sub(bytes.len()).ok_or(Error::Overflow)?;
10    buf[offset..].copy_from_slice(bytes);
11    Ok(u128::from_be_bytes(buf))
12}
13
14fn read_vec(reader: &mut impl io::Read, len: u64) -> Result<Vec<u8>> {
15    use io::Read;
16
17    let len_usize = usize::try_from(len).map_err(|_| Error::LengthTooLarge)?;
18
19    let mut buf = Vec::with_capacity(len_usize.min(100_000_000)); // Mitigate OOM
20    let bytes_read = reader.take(len).read_to_end(&mut buf)?;
21
22    if bytes_read == len_usize {
23        Ok(buf)
24    } else {
25        Err(Error::UnexpectedEof)
26    }
27}
28
29/// A single CBOR data item.
30///
31/// `Value` covers all CBOR major types: integers, floats, byte and text
32/// strings, arrays, maps, tagged values, and simple values (null, booleans).
33/// It encodes deterministically and decodes only canonical input.
34///
35/// # Creating values
36///
37/// Rust primitives convert via [`From`]:
38///
39/// ```
40/// use cbor_core::Value;
41///
42/// let n = Value::from(42_u32);
43/// let s = Value::from("hello");
44/// let b = Value::from(true);
45/// ```
46///
47/// For arrays and maps the `array!` and `map!` macros are convenient:
48///
49/// ```
50/// use cbor_core::{Value, array, map};
51///
52/// let a = array![1, 2, 3];
53/// let m = map! { "x" => 10, "y" => 20 };
54/// ```
55///
56/// Arrays and maps can also be built from standard Rust collections.
57/// Slices, `Vec`s, fixed-size arrays, `BTreeMap`s, `HashMap`s, and
58/// slices of key-value pairs all convert automatically:
59///
60/// ```
61/// use cbor_core::Value;
62/// use std::collections::HashMap;
63///
64/// // Array from a slice
65/// let a = Value::array([1_u32, 2, 3].as_slice());
66///
67/// // Map from a HashMap
68/// let mut hm = HashMap::new();
69/// hm.insert(1_u32, 2_u32);
70/// let m = Value::map(&hm);
71///
72/// // Map from key-value pairs
73/// let m = Value::map([("x", 10), ("y", 20)]);
74/// ```
75///
76/// Use `()` to create empty arrays or maps without spelling out a type:
77///
78/// ```
79/// use cbor_core::Value;
80///
81/// let empty_array = Value::array(());
82/// let empty_map = Value::map(());
83///
84/// assert_eq!(empty_array.as_array().unwrap().len(), 0);
85/// assert_eq!(empty_map.as_map().unwrap().len(), 0);
86/// ```
87///
88/// Named constructors are available for cases where `From` is ambiguous:
89///
90/// | Constructor | Builds |
91/// |---|---|
92/// | [`Value::null()`] | Null simple value |
93/// | [`Value::simple_value(v)`](Value::simple_value) | Arbitrary simple value |
94/// | [`Value::integer(v)`](Value::integer) | Integer (including big integers) |
95/// | [`Value::float(v)`](Value::float) | Float in shortest CBOR form |
96/// | [`Value::array(v)`](Value::array) | Array from slice, `Vec`, or fixed-size array |
97/// | [`Value::map(v)`](Value::map) | Map from `BTreeMap`, `HashMap`, slice of pairs, etc. |
98/// | [`Value::tag(n, v)`](Value::tag) | Tagged value |
99///
100/// # Encoding and decoding
101///
102/// ```
103/// use cbor_core::Value;
104///
105/// let original = Value::from(-1000_i32);
106/// let bytes = original.encode();
107/// let decoded = Value::decode(&bytes).unwrap();
108/// assert_eq!(original, decoded);
109/// ```
110///
111/// For streaming use, [`write_to`](Value::write_to) and
112/// [`read_from`](Value::read_from) operate on any `io::Write` / `io::Read`.
113///
114/// # Accessors
115///
116/// Accessor methods extract or borrow the inner data of each variant.
117/// All return `Result<T>`, yielding `Err(Error::IncompatibleType)` on a
118/// type mismatch. The naming follows Rust conventions:
119///
120/// | Prefix | Meaning | Returns |
121/// |---|---|---|
122/// | `as_*` | Borrow inner data | `&T` or `&mut T` (with `_mut`) |
123/// | `to_*` | Convert or narrow | Owned `Copy` type (`u8`, `f32`, ...) |
124/// | `into_*` | Consume self, extract | Owned `T` |
125/// | no prefix | Trivial property | `Copy` scalar |
126///
127/// ## Simple values
128///
129/// In CBOR, booleans and null are not distinct types but specific simple
130/// values: `false` is 20, `true` is 21, `null` is 22. This means a
131/// boolean value is always also a simple value. [`to_bool`](Self::to_bool)
132/// provides typed access to `true`/`false`, while
133/// [`to_simple_value`](Self::to_simple_value) works on any simple value
134/// including booleans and null.
135///
136/// | Method | Returns | Notes |
137/// |---|---|---|
138/// | [`to_simple_value`](Self::to_simple_value) | `Result<u8>` | Raw simple value number |
139/// | [`to_bool`](Self::to_bool) | `Result<bool>` | Only for `true`/`false` |
140///
141/// ```
142/// use cbor_core::Value;
143///
144/// let v = Value::from(true);
145/// assert_eq!(v.to_bool().unwrap(), true);
146/// assert_eq!(v.to_simple_value().unwrap(), 21); // CBOR true = simple(21)
147///
148/// // null is also a simple value
149/// let n = Value::null();
150/// assert!(n.to_bool().is_err());              // not a boolean
151/// assert_eq!(n.to_simple_value().unwrap(), 22); // but is simple(22)
152/// ```
153///
154/// ## Integers
155///
156/// CBOR has two integer types (unsigned and negative) with different
157/// internal representations. The `to_*` accessors perform checked
158/// narrowing into any Rust integer type, returning `Err(Overflow)` if
159/// the value does not fit, or `Err(NegativeUnsigned)` when extracting a
160/// negative value into an unsigned type. Big integers (tags 2 and 3)
161/// are handled transparently.
162///
163/// | Method | Returns |
164/// |---|---|
165/// | [`to_u8`](Self::to_u8) .. [`to_u128`](Self::to_u128), [`to_usize`](Self::to_usize) | `Result<uN>` |
166/// | [`to_i8`](Self::to_i8) .. [`to_i128`](Self::to_i128), [`to_isize`](Self::to_isize) | `Result<iN>` |
167///
168/// ```
169/// use cbor_core::Value;
170///
171/// let v = Value::from(1000_u32);
172/// assert_eq!(v.to_u32().unwrap(), 1000);
173/// assert_eq!(v.to_i64().unwrap(), 1000);
174/// assert!(v.to_u8().is_err()); // overflow
175///
176/// let neg = Value::from(-5_i32);
177/// assert_eq!(neg.to_i8().unwrap(), -5);
178/// assert!(neg.to_u32().is_err()); // negative unsigned
179/// ```
180///
181/// ## Floats
182///
183/// Floats are stored internally in their shortest CBOR encoding (f16,
184/// f32, or f64). [`to_f64`](Self::to_f64) always succeeds since every
185/// float can widen to f64. [`to_f32`](Self::to_f32) fails with
186/// `Err(Precision)` if the value is stored as f64.
187///
188/// | Method | Returns |
189/// |---|---|
190/// | [`to_f32`](Self::to_f32) | `Result<f32>` (fails for f64 values) |
191/// | [`to_f64`](Self::to_f64) | `Result<f64>` |
192///
193/// ```
194/// use cbor_core::Value;
195///
196/// let v = Value::from(2.5_f32);
197/// assert_eq!(v.to_f64().unwrap(), 2.5);
198/// assert_eq!(v.to_f32().unwrap(), 2.5);
199/// ```
200///
201/// ## Byte strings
202///
203/// Byte strings are stored as `Vec<u8>`. Use [`as_bytes`](Self::as_bytes)
204/// for a borrowed slice, or [`into_bytes`](Self::into_bytes) to take
205/// ownership without copying.
206///
207/// | Method | Returns |
208/// |---|---|
209/// | [`as_bytes`](Self::as_bytes) | `Result<&[u8]>` |
210/// | [`as_bytes_mut`](Self::as_bytes_mut) | `Result<&mut Vec<u8>>` |
211/// | [`into_bytes`](Self::into_bytes) | `Result<Vec<u8>>` |
212///
213/// ```
214/// use cbor_core::Value;
215///
216/// let mut v = Value::from(vec![1_u8, 2, 3]);
217/// v.as_bytes_mut().unwrap().push(4);
218/// assert_eq!(v.as_bytes().unwrap(), &[1, 2, 3, 4]);
219/// ```
220///
221/// ## Text strings
222///
223/// Text strings are stored as `String` (guaranteed valid UTF-8 by the
224/// decoder). Use [`as_str`](Self::as_str) for a borrowed `&str`, or
225/// [`into_string`](Self::into_string) to take ownership.
226///
227/// | Method | Returns |
228/// |---|---|
229/// | [`as_str`](Self::as_str) | `Result<&str>` |
230/// | [`as_string_mut`](Self::as_string_mut) | `Result<&mut String>` |
231/// | [`into_string`](Self::into_string) | `Result<String>` |
232///
233/// ```
234/// use cbor_core::Value;
235///
236/// let v = Value::from("hello");
237/// assert_eq!(v.as_str().unwrap(), "hello");
238///
239/// // Modify in place
240/// let mut v = Value::from("hello");
241/// v.as_string_mut().unwrap().push_str(" world");
242/// assert_eq!(v.as_str().unwrap(), "hello world");
243/// ```
244///
245/// ## Arrays
246///
247/// Arrays are stored as `Vec<Value>`. Use [`as_array`](Self::as_array)
248/// to borrow the elements as a slice, or [`as_array_mut`](Self::as_array_mut)
249/// to modify them in place.
250///
251/// | Method | Returns |
252/// |---|---|
253/// | [`as_array`](Self::as_array) | `Result<&[Value]>` |
254/// | [`as_array_mut`](Self::as_array_mut) | `Result<&mut Vec<Value>>` |
255/// | [`into_array`](Self::into_array) | `Result<Vec<Value>>` |
256///
257/// ```
258/// use cbor_core::{Value, array};
259///
260/// let v = array![10, 20, 30];
261/// let items = v.as_array().unwrap();
262/// assert_eq!(items[1].to_u32().unwrap(), 20);
263///
264/// // Modify in place
265/// let mut v = array![1, 2];
266/// v.as_array_mut().unwrap().push(Value::from(3));
267/// assert_eq!(v.as_array().unwrap().len(), 3);
268/// ```
269///
270/// ## Maps
271///
272/// Maps are stored as `BTreeMap<Value, Value>`, giving canonical key
273/// order. Use standard `BTreeMap` methods on the result of
274/// [`as_map`](Self::as_map) to look up entries.
275///
276/// | Method | Returns |
277/// |---|---|
278/// | [`as_map`](Self::as_map) | `Result<&BTreeMap<Value, Value>>` |
279/// | [`as_map_mut`](Self::as_map_mut) | `Result<&mut BTreeMap<Value, Value>>` |
280/// | [`into_map`](Self::into_map) | `Result<BTreeMap<Value, Value>>` |
281///
282/// ```
283/// use cbor_core::{Value, map};
284///
285/// let v = map! { "name" => "Alice", "age" => 30 };
286/// let name = &v.as_map().unwrap()[&Value::from("name")];
287/// assert_eq!(name.as_str().unwrap(), "Alice");
288///
289/// // Modify in place
290/// let mut v = map! { "count" => 1 };
291/// v.as_map_mut().unwrap().insert(Value::from("count"), Value::from(2));
292/// assert_eq!(v.as_map().unwrap()[&Value::from("count")].to_u32().unwrap(), 2);
293/// ```
294///
295/// ## Tags
296///
297/// A tag wraps another value with a numeric label (e.g. tag 1 for epoch
298/// timestamps, tag 32 for URIs). Tags can be nested.
299///
300/// | Method | Returns | Notes |
301/// |---|---|---|
302/// | [`tag_number`](Self::tag_number) | `Result<u64>` | Tag number |
303/// | [`tag_content`](Self::tag_content) | `Result<&Value>` | Borrowed content |
304/// | [`tag_content_mut`](Self::tag_content_mut) | `Result<&mut Value>` | Mutable content |
305/// | [`as_tag`](Self::as_tag) | `Result<(u64, &Value)>` | Both parts |
306/// | [`as_tag_mut`](Self::as_tag_mut) | `Result<(u64, &mut Value)>` | Mutable content |
307/// | [`into_tag`](Self::into_tag) | `Result<(u64, Value)>` | Consuming |
308///
309/// Use [`untagged`](Self::untagged) to look through tags without removing
310/// them, [`remove_tag`](Self::remove_tag) to strip the outermost tag, or
311/// [`remove_all_tags`](Self::remove_all_tags) to strip all layers at once.
312///
313/// ```
314/// use cbor_core::Value;
315///
316/// // Create a tagged value (tag 32 = URI)
317/// let mut uri = Value::tag(32, "https://example.com");
318///
319/// // Inspect
320/// let (tag_num, content) = uri.as_tag().unwrap();
321/// assert_eq!(tag_num, 32);
322/// assert_eq!(content.as_str().unwrap(), "https://example.com");
323///
324/// // Look through tags without removing them
325/// assert_eq!(uri.untagged().as_str().unwrap(), "https://example.com");
326///
327/// // Strip the tag in place
328/// let removed = uri.remove_tag();
329/// assert_eq!(removed, Some(32));
330/// assert_eq!(uri.as_str().unwrap(), "https://example.com");
331/// ```
332///
333/// Note that some CBOR types depend on their tag for interpretation.
334/// Big integers, for example, are tagged byte strings (tags 2 and 3).
335/// The integer accessors (`to_u128`, `to_i128`, etc.) recognise these
336/// tags and decode the bytes automatically. If the tag is removed —
337/// via `remove_tag`, `remove_all_tags`, or by consuming through
338/// `into_tag` — the value becomes a plain byte string and can no
339/// longer be read as an integer.
340///
341/// # Type introspection
342///
343/// [`data_type`](Self::data_type) returns a [`DataType`] enum for
344/// lightweight type checks without matching on the full enum.
345///
346/// ```
347/// use cbor_core::Value;
348///
349/// let v = Value::from(3.14_f64);
350/// assert!(v.data_type().is_float());
351/// ```
352#[derive(Debug, Clone)]
353pub enum Value {
354    /// Simple value such as `null`, `true`, or `false` (major type 7).
355    ///
356    /// In CBOR, booleans and null are simple values, not distinct types.
357    /// A `Value::from(true)` is stored as `SimpleValue(21)` and is
358    /// accessible through both [`to_bool`](Self::to_bool) and
359    /// [`to_simple_value`](Self::to_simple_value).
360    SimpleValue(SimpleValue),
361
362    /// Unsigned integer (major type 0). Stores values 0 through 2^64-1.
363    Unsigned(u64),
364    /// Negative integer (major type 1). The actual value is -1 - n,
365    /// covering -1 through -2^64.
366    Negative(u64),
367
368    /// IEEE 754 floating-point number (major type 7, additional info 25-27).
369    Float(Float),
370
371    /// Byte string (major type 2).
372    ByteString(Vec<u8>),
373    /// UTF-8 text string (major type 3).
374    TextString(String),
375
376    /// Array of data items (major type 4).
377    Array(Vec<Value>),
378    /// Map of key-value pairs in canonical order (major type 5).
379    Map(BTreeMap<Value, Value>),
380
381    /// Tagged data item (major type 6). The first field is the tag number,
382    /// the second is the enclosed content.
383    Tag(u64, Box<Value>),
384}
385
386impl Default for Value {
387    fn default() -> Self {
388        Self::null()
389    }
390}
391
392impl PartialEq for Value {
393    fn eq(&self, other: &Self) -> bool {
394        self.cmp(other) == cmp::Ordering::Equal
395    }
396}
397
398impl Eq for Value {}
399
400impl Ord for Value {
401    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
402        self.cbor_major()
403            .cmp(&other.cbor_major())
404            .then_with(|| self.cbor_argument().cmp(&other.cbor_argument()))
405            .then_with(|| match (self, other) {
406                (Self::TextString(a), Self::TextString(b)) => a.cmp(b),
407                (Self::ByteString(a), Self::ByteString(b)) => a.cmp(b),
408                (Self::Array(a), Self::Array(b)) => a.cmp(b),
409                (Self::Map(a), Self::Map(b)) => a.cmp(b),
410                (Self::Tag(_, a), Self::Tag(_, b)) => a.cmp(b),
411                _ => std::cmp::Ordering::Equal,
412            })
413    }
414}
415
416impl PartialOrd for Value {
417    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
418        Some(self.cmp(other))
419    }
420}
421
422impl Hash for Value {
423    fn hash<H: Hasher>(&self, state: &mut H) {
424        self.cbor_major().hash(state);
425        self.cbor_argument().hash(state);
426        match self {
427            Self::TextString(s) => s.hash(state),
428            Self::ByteString(b) => b.hash(state),
429            Self::Array(a) => a.hash(state),
430            Self::Map(m) => {
431                for (k, v) in m {
432                    k.hash(state);
433                    v.hash(state);
434                }
435            }
436            Self::Tag(_, v) => v.hash(state),
437            _ => {}
438        }
439    }
440}
441
442impl Value {
443    /// Encode this value to CBOR bytes.
444    ///
445    /// ```
446    /// use cbor_core::Value;
447    /// let bytes = Value::from(42_u32).encode();
448    /// assert_eq!(bytes, [0x18, 42]);
449    /// ```
450    #[must_use]
451    pub fn encode(&self) -> Vec<u8> {
452        let mut bytes = Vec::new();
453        self.write_to(&mut bytes).unwrap();
454        bytes
455    }
456
457    /// Decode a CBOR data item from a byte slice.
458    ///
459    /// Returns `Err` if the encoding is not canonical.
460    ///
461    /// ```
462    /// use cbor_core::Value;
463    /// let v = Value::decode(&[0x18, 42]).unwrap();
464    /// assert_eq!(v.to_u32().unwrap(), 42);
465    /// ```
466    pub fn decode(mut bytes: &[u8]) -> Result<Self> {
467        Self::read_from(&mut bytes)
468    }
469
470    /// Read a single CBOR data item from a stream.
471    pub fn read_from(reader: &mut impl io::Read) -> Result<Self> {
472        let ctrl_byte = {
473            let mut buf = [0];
474            reader.read_exact(&mut buf)?;
475            buf[0]
476        };
477
478        let is_float = matches!(ctrl_byte, CtrlByte::F16 | CtrlByte::F32 | CtrlByte::F64);
479
480        let major = ctrl_byte >> 5;
481        let info = ctrl_byte & 0x1f;
482
483        let argument = {
484            let mut buf = [0; 8];
485
486            if info < ArgLength::U8 {
487                buf[7] = info;
488            } else {
489                match info {
490                    ArgLength::U8 => reader.read_exact(&mut buf[7..])?,
491                    ArgLength::U16 => reader.read_exact(&mut buf[6..])?,
492                    ArgLength::U32 => reader.read_exact(&mut buf[4..])?,
493                    ArgLength::U64 => reader.read_exact(&mut buf)?,
494                    _ => return Err(Error::InvalidEncoding),
495                }
496            }
497
498            u64::from_be_bytes(buf)
499        };
500
501        if !is_float {
502            let non_deterministic = match info {
503                ArgLength::U8 => argument < ArgLength::U8.into(),
504                ArgLength::U16 => argument <= u8::MAX.into(),
505                ArgLength::U32 => argument <= u16::MAX.into(),
506                ArgLength::U64 => argument <= u32::MAX.into(),
507                _ => false,
508            };
509
510            if non_deterministic {
511                return Err(Error::InvalidEncoding);
512            }
513        }
514
515        let this = match major {
516            Major::UNSIGNED => Self::Unsigned(argument),
517            Major::NEGATIVE => Self::Negative(argument),
518
519            Major::BYTE_STRING => Self::ByteString(read_vec(reader, argument)?),
520
521            Major::TEXT_STRING => {
522                let bytes = read_vec(reader, argument)?;
523                let string = String::from_utf8(bytes).map_err(|_| Error::InvalidUtf8)?;
524                Self::TextString(string)
525            }
526
527            Major::ARRAY => {
528                let mut vec = Vec::with_capacity(argument.try_into().unwrap());
529                for _ in 0..argument {
530                    vec.push(Self::read_from(reader)?);
531                }
532                Self::Array(vec)
533            }
534
535            Major::MAP => {
536                let mut map = BTreeMap::new();
537                let mut prev = None;
538
539                for _ in 0..argument {
540                    let key = Self::read_from(reader)?;
541                    let value = Self::read_from(reader)?;
542
543                    if let Some((prev_key, prev_value)) = prev.take() {
544                        if prev_key >= key {
545                            return Err(Error::InvalidEncoding);
546                        }
547                        map.insert(prev_key, prev_value);
548                    }
549
550                    prev = Some((key, value));
551                }
552
553                if let Some((key, value)) = prev.take() {
554                    map.insert(key, value);
555                }
556
557                Self::Map(map)
558            }
559
560            Major::TAG => {
561                let content = Box::new(Self::read_from(reader)?);
562
563                if matches!(argument, Tag::POS_BIG_INT | Tag::NEG_BIG_INT)
564                    && let Ok(bigint) = content.as_bytes()
565                {
566                    let valid = bigint.len() >= 8 && bigint[0] != 0;
567                    if !valid {
568                        return Err(Error::InvalidEncoding);
569                    }
570                }
571
572                Self::Tag(argument, content)
573            }
574
575            Major::SIMPLE_VALUE => match info {
576                0..=ArgLength::U8 => SimpleValue::from_u8(argument as u8)
577                    .map(Self::SimpleValue)
578                    .map_err(|_| Error::InvalidEncoding)?,
579
580                ArgLength::U16 => Self::Float(Float::from_u16(argument as u16)),
581                ArgLength::U32 => Self::Float(Float::from_u32(argument as u32)?),
582                ArgLength::U64 => Self::Float(Float::from_u64(argument)?),
583
584                _ => return Err(Error::InvalidEncoding),
585            },
586
587            _ => unreachable!(),
588        };
589
590        Ok(this)
591    }
592
593    /// Write this value as CBOR to a stream.
594    pub fn write_to(&self, writer: &mut impl io::Write) -> Result<()> {
595        let major = self.cbor_major();
596        let (info, argument) = self.cbor_argument();
597
598        let ctrl_byte = major << 5 | info;
599        writer.write_all(&[ctrl_byte])?;
600
601        let buf = argument.to_be_bytes();
602        match info {
603            ArgLength::U8 => writer.write_all(&buf[7..])?,
604            ArgLength::U16 => writer.write_all(&buf[6..])?,
605            ArgLength::U32 => writer.write_all(&buf[4..])?,
606            ArgLength::U64 => writer.write_all(&buf)?,
607            _ => (), // argument embedded in ctrl byte
608        }
609
610        match self {
611            Value::ByteString(bytes) => writer.write_all(bytes)?,
612            Value::TextString(string) => writer.write_all(string.as_bytes())?,
613
614            Value::Tag(_number, content) => content.write_to(writer)?,
615
616            Value::Array(values) => {
617                for value in values {
618                    value.write_to(writer)?;
619                }
620            }
621
622            Value::Map(map) => {
623                for (key, value) in map {
624                    key.write_to(writer)?;
625                    value.write_to(writer)?;
626                }
627            }
628
629            _ => (),
630        }
631
632        Ok(())
633    }
634
635    fn cbor_major(&self) -> u8 {
636        match self {
637            Value::Unsigned(_) => Major::UNSIGNED,
638            Value::Negative(_) => Major::NEGATIVE,
639            Value::ByteString(_) => Major::BYTE_STRING,
640            Value::TextString(_) => Major::TEXT_STRING,
641            Value::Array(_) => Major::ARRAY,
642            Value::Map(_) => Major::MAP,
643            Value::Tag(_, _) => Major::TAG,
644            Value::SimpleValue(_) => Major::SIMPLE_VALUE,
645            Value::Float(_) => Major::SIMPLE_VALUE,
646        }
647    }
648
649    fn cbor_argument(&self) -> (u8, u64) {
650        fn arg(value: u64) -> (u8, u64) {
651            if value < ArgLength::U8.into() {
652                (value as u8, value)
653            } else {
654                let info = match value {
655                    0x00..=0xFF => ArgLength::U8,
656                    0x100..=0xFFFF => ArgLength::U16,
657                    0x10000..=0xFFFF_FFFF => ArgLength::U32,
658                    _ => ArgLength::U64,
659                };
660                (info, value)
661            }
662        }
663
664        match self {
665            Value::Unsigned(value) => arg(*value),
666            Value::Negative(value) => arg(*value),
667            Value::ByteString(vec) => arg(vec.len().try_into().unwrap()),
668            Value::TextString(str) => arg(str.len().try_into().unwrap()),
669            Value::Array(vec) => arg(vec.len().try_into().unwrap()),
670            Value::Map(map) => arg(map.len().try_into().unwrap()),
671            Value::Tag(number, _) => arg(*number),
672            Value::SimpleValue(value) => arg(value.0.into()),
673            Value::Float(float) => float.cbor_argument(),
674        }
675    }
676
677    // ------------------- constructors -------------------
678
679    /// Create a CBOR null value.
680    #[must_use]
681    pub const fn null() -> Self {
682        Self::SimpleValue(SimpleValue::NULL)
683    }
684
685    /// Create a CBOR simple value.
686    ///
687    /// # Panics
688    ///
689    /// Panics if the value is in the reserved range 24-31.
690    /// Use [`SimpleValue::from_u8`] for a fallible alternative.
691    pub fn simple_value(value: impl TryInto<SimpleValue>) -> Self {
692        match value.try_into() {
693            Ok(sv) => Self::SimpleValue(sv),
694            Err(_) => panic!("Invalid simple value"),
695        }
696    }
697
698    /// Create a CBOR integer. Accepts any Rust integer type.
699    /// Values beyond the u64/i64 range are encoded as big integers (tags 2/3).
700    pub fn integer(value: impl Into<Integer>) -> Self {
701        value.into().into_value()
702    }
703
704    /// Create a CBOR float. The value is stored in the shortest
705    /// IEEE 754 form (f16, f32, or f64) that preserves it exactly.
706    pub fn float(value: impl Into<Float>) -> Self {
707        Self::Float(value.into())
708    }
709
710    /// Create a CBOR array from a `Vec`, slice, or fixed-size array.
711    pub fn array(array: impl Into<Array>) -> Self {
712        Self::Array(array.into().0)
713    }
714
715    /// Create a CBOR map. Keys are stored in canonical order.
716    pub fn map(map: impl Into<Map>) -> Self {
717        Self::Map(map.into().0)
718    }
719
720    /// Wrap a value with a CBOR tag.
721    ///
722    /// ```
723    /// use cbor_core::Value;
724    /// let uri = Value::tag(32, "https://example.com");
725    /// assert_eq!(uri.tag_number().unwrap(), 32);
726    /// ```
727    pub fn tag(number: u64, content: impl Into<Value>) -> Self {
728        Self::Tag(number, Box::new(content.into()))
729    }
730
731    /// Return the [`DataType`] of this value for type-level dispatch.
732    #[must_use]
733    pub const fn data_type(&self) -> DataType {
734        match self {
735            Self::SimpleValue(sv) => sv.data_type(),
736
737            Self::Unsigned(_) | Self::Negative(_) => DataType::Int,
738
739            Self::Float(float) => float.data_type(),
740
741            Self::TextString(_) => DataType::Text,
742            Self::ByteString(_) => DataType::Bytes,
743
744            Self::Array(_) => DataType::Array,
745            Self::Map(_) => DataType::Map,
746
747            Self::Tag(Tag::POS_BIG_INT | Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => {
748                DataType::BigInt
749            }
750            Self::Tag(_, _) => DataType::Tag,
751        }
752    }
753
754    /// Extract a boolean. Returns `Err` for non-boolean values.
755    pub const fn to_bool(&self) -> Result<bool> {
756        match self {
757            Self::SimpleValue(sv) => sv.to_bool(),
758            _ => Err(Error::IncompatibleType),
759        }
760    }
761
762    /// Extract the raw simple value number (0-255, excluding 24-31).
763    pub const fn to_simple_value(&self) -> Result<u8> {
764        match self {
765            Self::SimpleValue(sv) => Ok(sv.0),
766            _ => Err(Error::IncompatibleType),
767        }
768    }
769
770    /// Narrow to `u8`. Returns `Err(Overflow)` or `Err(NegativeUnsigned)` on mismatch.
771    pub const fn to_u8(&self) -> Result<u8> {
772        match self {
773            Self::Unsigned(x) if *x <= u8::MAX as u64 => Ok(*x as u8),
774            Self::Unsigned(_) => Err(Error::Overflow),
775            Self::Negative(_) => Err(Error::NegativeUnsigned),
776            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
777            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
778            _ => Err(Error::IncompatibleType),
779        }
780    }
781
782    /// Narrow to `u16`.
783    pub const fn to_u16(&self) -> Result<u16> {
784        match self {
785            Self::Unsigned(x) if *x <= u16::MAX as u64 => Ok(*x as u16),
786            Self::Unsigned(_) => Err(Error::Overflow),
787            Self::Negative(_) => Err(Error::NegativeUnsigned),
788            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
789            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
790            _ => Err(Error::IncompatibleType),
791        }
792    }
793
794    /// Narrow to `u32`.
795    pub const fn to_u32(&self) -> Result<u32> {
796        match self {
797            Self::Unsigned(x) if *x <= u32::MAX as u64 => Ok(*x as u32),
798            Self::Unsigned(_) => Err(Error::Overflow),
799            Self::Negative(_) => Err(Error::NegativeUnsigned),
800            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
801            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
802            _ => Err(Error::IncompatibleType),
803        }
804    }
805
806    /// Narrow to `u64`.
807    pub const fn to_u64(&self) -> Result<u64> {
808        match self {
809            Self::Unsigned(x) => Ok(*x),
810            Self::Negative(_) => Err(Error::NegativeUnsigned),
811            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
812            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
813            _ => Err(Error::IncompatibleType),
814        }
815    }
816
817    /// Narrow to `u128`. Handles big integers (tag 2) transparently.
818    pub fn to_u128(&self) -> Result<u128> {
819        match self {
820            Self::Unsigned(x) => Ok(*x as u128),
821            Self::Negative(_) => Err(Error::NegativeUnsigned),
822            Self::Tag(Tag::POS_BIG_INT, content) => u128_from_bytes(content.as_bytes()?),
823            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
824            _ => Err(Error::IncompatibleType),
825        }
826    }
827
828    /// Narrow to `usize`.
829    #[cfg(target_pointer_width = "32")]
830    pub const fn to_usize(&self) -> Result<usize> {
831        match self {
832            Self::Unsigned(x) if *x <= u32::MAX as u64 => Ok(*x as usize),
833            Self::Unsigned(_) => Err(Error::Overflow),
834            Self::Negative(_) => Err(Error::NegativeUnsigned),
835            Self::Tag(TAG_POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
836            Self::Tag(TAG_NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
837            _ => Err(Error::IncompatibleType),
838        }
839    }
840
841    /// Narrow to `usize`.
842    #[cfg(target_pointer_width = "64")]
843    pub const fn to_usize(&self) -> Result<usize> {
844        match self {
845            Self::Unsigned(x) => Ok(*x as usize),
846            Self::Negative(_) => Err(Error::NegativeUnsigned),
847            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
848            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::NegativeUnsigned),
849            _ => Err(Error::IncompatibleType),
850        }
851    }
852
853    /// Narrow to `i8`.
854    pub const fn to_i8(&self) -> Result<i8> {
855        match self {
856            Self::Unsigned(x) if *x <= i8::MAX as u64 => Ok(*x as i8),
857            Self::Unsigned(_) => Err(Error::Overflow),
858            Self::Negative(x) if *x <= i8::MAX as u64 => Ok((!*x) as i8),
859            Self::Negative(_) => Err(Error::Overflow),
860            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
861            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
862            _ => Err(Error::IncompatibleType),
863        }
864    }
865
866    /// Narrow to `i16`.
867    pub const fn to_i16(&self) -> Result<i16> {
868        match self {
869            Self::Unsigned(x) if *x <= i16::MAX as u64 => Ok(*x as i16),
870            Self::Unsigned(_) => Err(Error::Overflow),
871            Self::Negative(x) if *x <= i16::MAX as u64 => Ok((!*x) as i16),
872            Self::Negative(_) => Err(Error::Overflow),
873            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
874            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
875            _ => Err(Error::IncompatibleType),
876        }
877    }
878
879    /// Narrow to `i32`.
880    pub const fn to_i32(&self) -> Result<i32> {
881        match self {
882            Self::Unsigned(x) if *x <= i32::MAX as u64 => Ok(*x as i32),
883            Self::Unsigned(_) => Err(Error::Overflow),
884            Self::Negative(x) if *x <= i32::MAX as u64 => Ok((!*x) as i32),
885            Self::Negative(_) => Err(Error::Overflow),
886            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
887            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
888            _ => Err(Error::IncompatibleType),
889        }
890    }
891
892    /// Narrow to `i64`.
893    pub const fn to_i64(&self) -> Result<i64> {
894        match self {
895            Self::Unsigned(x) if *x <= i64::MAX as u64 => Ok(*x as i64),
896            Self::Unsigned(_) => Err(Error::Overflow),
897            Self::Negative(x) if *x <= i64::MAX as u64 => Ok((!*x) as i64),
898            Self::Negative(_) => Err(Error::Overflow),
899            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
900            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
901            _ => Err(Error::IncompatibleType),
902        }
903    }
904
905    /// Narrow to `i128`. Handles big integers (tags 2 and 3) transparently.
906    pub fn to_i128(&self) -> Result<i128> {
907        match self {
908            Self::Unsigned(x) => Ok(*x as i128),
909            Self::Negative(x) => Ok(!(*x as i128)),
910
911            Self::Tag(Tag::POS_BIG_INT, content) => match u128_from_bytes(content.as_bytes()?)? {
912                value if value <= i128::MAX as u128 => Ok(value as i128),
913                _ => Err(Error::Overflow),
914            },
915
916            Self::Tag(Tag::NEG_BIG_INT, content) => match u128_from_bytes(content.as_bytes()?)? {
917                value if value <= i128::MAX as u128 => Ok((!value) as i128),
918                _ => Err(Error::Overflow),
919            },
920
921            _ => Err(Error::IncompatibleType),
922        }
923    }
924
925    /// Narrow to `isize`.
926    #[cfg(target_pointer_width = "32")]
927    pub const fn to_isize(&self) -> Result<isize> {
928        match self {
929            Self::Unsigned(x) if *x <= i32::MAX as u64 => Ok(*x as isize),
930            Self::Unsigned(_) => Err(Error::Overflow),
931            Self::Negative(x) if *x <= i32::MAX as u64 => Ok((!*x) as isize),
932            Self::Negative(_) => Err(Error::Overflow),
933            Self::Tag(TAG_POS_BIG_INT, content) if content.is_bytes() => Err(Error::Overflow),
934            Self::Tag(TAG_NEG_BIG_INT, content) if content.is_bytes() => Err(Error::Overflow),
935            _ => Err(Error::IncompatibleType),
936        }
937    }
938
939    /// Narrow to `isize`.
940    #[cfg(target_pointer_width = "64")]
941    pub const fn to_isize(&self) -> Result<isize> {
942        match self {
943            Self::Unsigned(x) if *x <= i64::MAX as u64 => Ok(*x as isize),
944            Self::Unsigned(_) => Err(Error::Overflow),
945            Self::Negative(x) if *x <= i64::MAX as u64 => Ok((!*x) as isize),
946            Self::Negative(_) => Err(Error::Overflow),
947            Self::Tag(Tag::POS_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
948            Self::Tag(Tag::NEG_BIG_INT, content) if content.data_type().is_bytes() => Err(Error::Overflow),
949            _ => Err(Error::IncompatibleType),
950        }
951    }
952
953    /// Convert to `f32`. Returns `Err(Precision)` for f64-width values.
954    pub fn to_f32(&self) -> Result<f32> {
955        match self {
956            Self::Float(float) => float.to_f32(),
957            _ => Err(Error::IncompatibleType),
958        }
959    }
960
961    /// Convert to `f64`. Always succeeds for float values.
962    pub fn to_f64(&self) -> Result<f64> {
963        match self {
964            Self::Float(float) => Ok(float.to_f64()),
965            _ => Err(Error::IncompatibleType),
966        }
967    }
968
969    /// Borrow the byte string as a slice.
970    pub fn as_bytes(&self) -> Result<&[u8]> {
971        match self {
972            Self::ByteString(vec) => Ok(vec.as_slice()),
973            _ => Err(Error::IncompatibleType),
974        }
975    }
976
977    /// Borrow the byte string as a mutable `Vec`.
978    pub const fn as_bytes_mut(&mut self) -> Result<&mut Vec<u8>> {
979        match self {
980            Self::ByteString(vec) => Ok(vec),
981            _ => Err(Error::IncompatibleType),
982        }
983    }
984
985    /// Take ownership of the byte string.
986    pub fn into_bytes(self) -> Result<Vec<u8>> {
987        match self {
988            Self::ByteString(vec) => Ok(vec),
989            _ => Err(Error::IncompatibleType),
990        }
991    }
992
993    /// Borrow the text string as a `&str`.
994    pub fn as_str(&self) -> Result<&str> {
995        match self {
996            Self::TextString(s) => Ok(s.as_str()),
997            _ => Err(Error::IncompatibleType),
998        }
999    }
1000
1001    /// Borrow the text string as a mutable `String`.
1002    pub const fn as_string_mut(&mut self) -> Result<&mut String> {
1003        match self {
1004            Self::TextString(s) => Ok(s),
1005            _ => Err(Error::IncompatibleType),
1006        }
1007    }
1008
1009    /// Take ownership of the text string.
1010    pub fn into_string(self) -> Result<String> {
1011        match self {
1012            Self::TextString(s) => Ok(s),
1013            _ => Err(Error::IncompatibleType),
1014        }
1015    }
1016
1017    /// Borrow the array elements as a slice.
1018    pub fn as_array(&self) -> Result<&[Value]> {
1019        match self {
1020            Self::Array(v) => Ok(v.as_slice()),
1021            _ => Err(Error::IncompatibleType),
1022        }
1023    }
1024
1025    /// Borrow the array as a mutable `Vec`.
1026    pub const fn as_array_mut(&mut self) -> Result<&mut Vec<Value>> {
1027        match self {
1028            Self::Array(v) => Ok(v),
1029            _ => Err(Error::IncompatibleType),
1030        }
1031    }
1032
1033    /// Take ownership of the array.
1034    pub fn into_array(self) -> Result<Vec<Value>> {
1035        match self {
1036            Self::Array(v) => Ok(v),
1037            _ => Err(Error::IncompatibleType),
1038        }
1039    }
1040
1041    /// Borrow the map.
1042    pub const fn as_map(&self) -> Result<&BTreeMap<Value, Value>> {
1043        match self {
1044            Self::Map(m) => Ok(m),
1045            _ => Err(Error::IncompatibleType),
1046        }
1047    }
1048
1049    /// Borrow the map mutably.
1050    pub const fn as_map_mut(&mut self) -> Result<&mut BTreeMap<Value, Value>> {
1051        match self {
1052            Self::Map(m) => Ok(m),
1053            _ => Err(Error::IncompatibleType),
1054        }
1055    }
1056
1057    /// Take ownership of the map.
1058    pub fn into_map(self) -> Result<BTreeMap<Value, Value>> {
1059        match self {
1060            Self::Map(m) => Ok(m),
1061            _ => Err(Error::IncompatibleType),
1062        }
1063    }
1064
1065    /// Return the tag number.
1066    pub const fn tag_number(&self) -> Result<u64> {
1067        match self {
1068            Self::Tag(number, _content) => Ok(*number),
1069            _ => Err(Error::IncompatibleType),
1070        }
1071    }
1072
1073    /// Borrow the tag content.
1074    pub const fn tag_content(&self) -> Result<&Self> {
1075        match self {
1076            Self::Tag(_tag, content) => Ok(content),
1077            _ => Err(Error::IncompatibleType),
1078        }
1079    }
1080
1081    /// Mutably borrow the tag content.
1082    pub const fn tag_content_mut(&mut self) -> Result<&mut Self> {
1083        match self {
1084            Self::Tag(_, value) => Ok(value),
1085            _ => Err(Error::IncompatibleType),
1086        }
1087    }
1088
1089    /// Borrow tag number and content together.
1090    pub fn as_tag(&self) -> Result<(u64, &Value)> {
1091        match self {
1092            Self::Tag(number, content) => Ok((*number, content)),
1093            _ => Err(Error::IncompatibleType),
1094        }
1095    }
1096
1097    /// Borrow tag number and mutable content together.
1098    pub fn as_tag_mut(&mut self) -> Result<(u64, &mut Value)> {
1099        match self {
1100            Self::Tag(number, content) => Ok((*number, content)),
1101            _ => Err(Error::IncompatibleType),
1102        }
1103    }
1104
1105    /// Consume self and return tag number and content.
1106    pub fn into_tag(self) -> Result<(u64, Value)> {
1107        match self {
1108            Self::Tag(number, content) => Ok((number, *content)),
1109            _ => Err(Error::IncompatibleType),
1110        }
1111    }
1112
1113    /// Remove the outermost tag, returning its number. Returns `None` if
1114    /// the value is not tagged.
1115    pub fn remove_tag(&mut self) -> Option<u64> {
1116        let mut result = None;
1117        if let Self::Tag(number, content) = self {
1118            result = Some(*number);
1119            *self = std::mem::take(content);
1120        }
1121        result
1122    }
1123
1124    /// Remove all nested tags, returning their numbers from outermost to
1125    /// innermost.
1126    pub fn remove_all_tags(&mut self) -> Vec<u64> {
1127        let mut tags = Vec::new();
1128        while let Self::Tag(number, content) = self {
1129            tags.push(*number);
1130            *self = std::mem::take(content);
1131        }
1132        tags
1133    }
1134
1135    /// Borrow the innermost non-tag value, skipping all tag wrappers.
1136    #[must_use]
1137    pub const fn untagged(&self) -> &Self {
1138        let mut result = self;
1139        while let Self::Tag(_, data_item) = result {
1140            result = data_item;
1141        }
1142        result
1143    }
1144
1145    /// Mutable version of [`untagged`](Self::untagged).
1146    pub const fn untagged_mut(&mut self) -> &mut Self {
1147        let mut result = self;
1148        while let Self::Tag(_, data_item) = result {
1149            result = data_item;
1150        }
1151        result
1152    }
1153
1154    /// Consuming version of [`untagged`](Self::untagged).
1155    #[must_use]
1156    pub fn into_untagged(mut self) -> Self {
1157        while let Self::Tag(_number, content) = self {
1158            self = *content;
1159        }
1160        self
1161    }
1162}
1163
1164// --------- From-traits for Value ---------
1165
1166impl From<SimpleValue> for Value {
1167    fn from(value: SimpleValue) -> Self {
1168        Self::SimpleValue(value)
1169    }
1170}
1171
1172impl From<bool> for Value {
1173    fn from(value: bool) -> Self {
1174        Self::SimpleValue(SimpleValue::from_bool(value))
1175    }
1176}
1177
1178impl From<Integer> for Value {
1179    fn from(value: Integer) -> Self {
1180        value.into_value()
1181    }
1182}
1183
1184impl From<u8> for Value {
1185    fn from(value: u8) -> Self {
1186        Integer::from(value).into_value()
1187    }
1188}
1189
1190impl From<u16> for Value {
1191    fn from(value: u16) -> Self {
1192        Integer::from(value).into_value()
1193    }
1194}
1195
1196impl From<u32> for Value {
1197    fn from(value: u32) -> Self {
1198        Integer::from(value).into_value()
1199    }
1200}
1201
1202impl From<u64> for Value {
1203    fn from(value: u64) -> Self {
1204        Integer::from(value).into_value()
1205    }
1206}
1207
1208impl From<u128> for Value {
1209    fn from(value: u128) -> Self {
1210        Integer::from(value).into_value()
1211    }
1212}
1213
1214impl From<usize> for Value {
1215    fn from(value: usize) -> Self {
1216        Integer::from(value).into_value()
1217    }
1218}
1219
1220impl From<i8> for Value {
1221    fn from(value: i8) -> Self {
1222        Integer::from(value).into_value()
1223    }
1224}
1225
1226impl From<i16> for Value {
1227    fn from(value: i16) -> Self {
1228        Integer::from(value).into_value()
1229    }
1230}
1231
1232impl From<i32> for Value {
1233    fn from(value: i32) -> Self {
1234        Integer::from(value).into_value()
1235    }
1236}
1237
1238impl From<i64> for Value {
1239    fn from(value: i64) -> Self {
1240        Integer::from(value).into_value()
1241    }
1242}
1243
1244impl From<i128> for Value {
1245    fn from(value: i128) -> Self {
1246        Integer::from(value).into_value()
1247    }
1248}
1249
1250impl From<isize> for Value {
1251    fn from(value: isize) -> Self {
1252        Integer::from(value).into_value()
1253    }
1254}
1255
1256// --- Floats ---
1257
1258impl From<Float> for Value {
1259    fn from(value: Float) -> Self {
1260        Self::Float(value)
1261    }
1262}
1263
1264impl From<f32> for Value {
1265    fn from(value: f32) -> Self {
1266        Self::Float(value.into())
1267    }
1268}
1269
1270impl From<f64> for Value {
1271    fn from(value: f64) -> Self {
1272        Self::Float(value.into())
1273    }
1274}
1275
1276// --- Strings: String, str, Box ---
1277
1278impl From<&str> for Value {
1279    fn from(value: &str) -> Self {
1280        Self::TextString(value.into())
1281    }
1282}
1283
1284impl From<String> for Value {
1285    fn from(value: String) -> Self {
1286        Self::TextString(value)
1287    }
1288}
1289
1290impl From<&String> for Value {
1291    fn from(value: &String) -> Self {
1292        Self::TextString(value.clone())
1293    }
1294}
1295
1296impl From<Box<str>> for Value {
1297    fn from(value: Box<str>) -> Self {
1298        Self::TextString(value.into())
1299    }
1300}
1301
1302// --- ByteString: Vec, slice, array, Box ---
1303
1304impl From<Vec<u8>> for Value {
1305    fn from(value: Vec<u8>) -> Self {
1306        Self::ByteString(value)
1307    }
1308}
1309
1310impl From<&[u8]> for Value {
1311    fn from(value: &[u8]) -> Self {
1312        Self::ByteString(value.to_vec())
1313    }
1314}
1315
1316impl<const N: usize> From<[u8; N]> for Value {
1317    fn from(value: [u8; N]) -> Self {
1318        Self::ByteString(value.to_vec())
1319    }
1320}
1321
1322impl<const N: usize> From<&[u8; N]> for Value {
1323    fn from(value: &[u8; N]) -> Self {
1324        Self::ByteString(value.to_vec())
1325    }
1326}
1327
1328impl From<Box<[u8]>> for Value {
1329    fn from(value: Box<[u8]>) -> Self {
1330        Self::ByteString(Vec::from(value))
1331    }
1332}
1333
1334// --- Array of values: Vec, array, Box ---
1335
1336impl From<Vec<Value>> for Value {
1337    fn from(value: Vec<Value>) -> Self {
1338        Self::Array(value)
1339    }
1340}
1341
1342impl<const N: usize> From<[Value; N]> for Value {
1343    fn from(value: [Value; N]) -> Self {
1344        Self::Array(value.to_vec())
1345    }
1346}
1347
1348impl From<Box<[Value]>> for Value {
1349    fn from(value: Box<[Value]>) -> Self {
1350        Self::Array(value.to_vec())
1351    }
1352}
1353
1354// --- Array, Map, BTreeMap ---
1355
1356impl From<Array> for Value {
1357    fn from(value: Array) -> Self {
1358        Self::Array(value.into_inner())
1359    }
1360}
1361
1362impl From<Map> for Value {
1363    fn from(value: Map) -> Self {
1364        Self::Map(value.into_inner())
1365    }
1366}
1367
1368impl From<BTreeMap<Value, Value>> for Value {
1369    fn from(value: BTreeMap<Value, Value>) -> Self {
1370        Self::Map(value)
1371    }
1372}
1373
1374// --------- TryFrom Value ---------
1375
1376impl TryFrom<Value> for bool {
1377    type Error = Error;
1378    fn try_from(value: Value) -> Result<Self> {
1379        value.to_bool()
1380    }
1381}
1382
1383impl TryFrom<Value> for SimpleValue {
1384    type Error = Error;
1385    fn try_from(value: Value) -> Result<Self> {
1386        match value {
1387            Value::SimpleValue(sv) => Ok(sv),
1388            _ => Err(Error::IncompatibleType),
1389        }
1390    }
1391}
1392
1393impl TryFrom<Value> for u8 {
1394    type Error = Error;
1395    fn try_from(value: Value) -> Result<Self> {
1396        value.to_u8()
1397    }
1398}
1399
1400impl TryFrom<Value> for u16 {
1401    type Error = Error;
1402    fn try_from(value: Value) -> Result<Self> {
1403        value.to_u16()
1404    }
1405}
1406
1407impl TryFrom<Value> for u32 {
1408    type Error = Error;
1409    fn try_from(value: Value) -> Result<Self> {
1410        value.to_u32()
1411    }
1412}
1413
1414impl TryFrom<Value> for u64 {
1415    type Error = Error;
1416    fn try_from(value: Value) -> Result<Self> {
1417        value.to_u64()
1418    }
1419}
1420
1421impl TryFrom<Value> for u128 {
1422    type Error = Error;
1423    fn try_from(value: Value) -> Result<Self> {
1424        value.to_u128()
1425    }
1426}
1427
1428impl TryFrom<Value> for usize {
1429    type Error = Error;
1430    fn try_from(value: Value) -> Result<Self> {
1431        value.to_usize()
1432    }
1433}
1434
1435impl TryFrom<Value> for i8 {
1436    type Error = Error;
1437    fn try_from(value: Value) -> Result<Self> {
1438        value.to_i8()
1439    }
1440}
1441
1442impl TryFrom<Value> for i16 {
1443    type Error = Error;
1444    fn try_from(value: Value) -> Result<Self> {
1445        value.to_i16()
1446    }
1447}
1448
1449impl TryFrom<Value> for i32 {
1450    type Error = Error;
1451    fn try_from(value: Value) -> Result<Self> {
1452        value.to_i32()
1453    }
1454}
1455
1456impl TryFrom<Value> for i64 {
1457    type Error = Error;
1458    fn try_from(value: Value) -> Result<Self> {
1459        value.to_i64()
1460    }
1461}
1462
1463impl TryFrom<Value> for i128 {
1464    type Error = Error;
1465    fn try_from(value: Value) -> Result<Self> {
1466        value.to_i128()
1467    }
1468}
1469
1470impl TryFrom<Value> for isize {
1471    type Error = Error;
1472    fn try_from(value: Value) -> Result<Self> {
1473        value.to_isize()
1474    }
1475}
1476
1477impl TryFrom<Value> for f32 {
1478    type Error = Error;
1479    fn try_from(value: Value) -> Result<Self> {
1480        value.to_f32()
1481    }
1482}
1483
1484impl TryFrom<Value> for f64 {
1485    type Error = Error;
1486    fn try_from(value: Value) -> Result<Self> {
1487        value.to_f64()
1488    }
1489}
1490
1491impl TryFrom<Value> for Float {
1492    type Error = Error;
1493    fn try_from(value: Value) -> Result<Self> {
1494        match value {
1495            Value::Float(f) => Ok(f),
1496            _ => Err(Error::IncompatibleType),
1497        }
1498    }
1499}
1500
1501impl TryFrom<Value> for Integer {
1502    type Error = Error;
1503    fn try_from(value: Value) -> Result<Self> {
1504        Integer::from_value(value)
1505    }
1506}
1507
1508impl TryFrom<Value> for String {
1509    type Error = Error;
1510    fn try_from(value: Value) -> Result<Self> {
1511        value.into_string()
1512    }
1513}
1514
1515impl TryFrom<Value> for Vec<u8> {
1516    type Error = Error;
1517    fn try_from(value: Value) -> Result<Self> {
1518        value.into_bytes()
1519    }
1520}
1521
1522impl TryFrom<Value> for Vec<Value> {
1523    type Error = Error;
1524    fn try_from(value: Value) -> Result<Self> {
1525        value.into_array()
1526    }
1527}
1528
1529impl TryFrom<Value> for BTreeMap<Value, Value> {
1530    type Error = Error;
1531    fn try_from(value: Value) -> Result<Self> {
1532        value.into_map()
1533    }
1534}
1535
1536impl TryFrom<Value> for Array {
1537    type Error = Error;
1538    fn try_from(value: Value) -> Result<Self> {
1539        value.into_array().map(Array::from)
1540    }
1541}
1542
1543impl TryFrom<Value> for Map {
1544    type Error = Error;
1545    fn try_from(value: Value) -> Result<Self> {
1546        value.into_map().map(Map::from)
1547    }
1548}