platform_value/lib.rs
1//! Platform value
2//! A dynamic Platform value
3//!
4//! A module that is used to represent values in Platform components
5//! Forked from ciborium value
6//!
7//!
8extern crate core;
9
10pub mod btreemap_extensions;
11pub mod converter;
12pub mod display;
13mod eq;
14mod error;
15mod index;
16mod inner_array_value;
17pub mod inner_value;
18mod inner_value_at_path;
19mod macros;
20pub mod patch;
21mod pointer;
22mod replace;
23pub mod string_encoding;
24pub mod system_bytes;
25mod types;
26mod value_map;
27mod value_serialization;
28
29pub use crate::value_map::{ValueMap, ValueMapHelper};
30pub use error::Error;
31use std::collections::BTreeMap;
32
33pub type Hash256 = [u8; 32];
34
35pub use btreemap_extensions::btreemap_field_replacement::{
36 IntegerReplacementType, ReplacementType,
37};
38pub use types::binary_data::BinaryData;
39pub use types::bytes_20::Bytes20;
40pub use types::bytes_32::Bytes32;
41pub use types::bytes_36::Bytes36;
42pub use types::identifier::{Identifier, IdentifierBytes32, IDENTIFIER_MEDIA_TYPE};
43
44pub use value_serialization::{from_value, to_value};
45
46use bincode::{Decode, Encode};
47pub use patch::{patch, Patch};
48
49/// A representation of a dynamic value that can handled dynamically
50#[non_exhaustive]
51#[derive(Clone, Debug, PartialEq, PartialOrd, Encode, Decode)]
52pub enum Value {
53 /// A u128 integer
54 U128(u128),
55
56 /// A i128 integer
57 I128(i128),
58
59 /// A u64 integer
60 U64(u64),
61
62 /// A i64 integer
63 I64(i64),
64
65 /// A u32 integer
66 U32(u32),
67
68 /// A i32 integer
69 I32(i32),
70
71 /// A u16 integer
72 U16(u16),
73
74 /// A i16 integer
75 I16(i16),
76
77 /// A u8 integer
78 U8(u8),
79
80 /// A i8 integer
81 I8(i8),
82
83 /// Bytes
84 Bytes(Vec<u8>),
85
86 /// Bytes 20
87 Bytes20([u8; 20]),
88
89 /// Bytes 32
90 Bytes32([u8; 32]),
91
92 /// Bytes 36 : Useful for outpoints
93 Bytes36([u8; 36]),
94
95 /// An enumeration of u8
96 EnumU8(Vec<u8>),
97
98 /// An enumeration of strings
99 EnumString(Vec<String>),
100
101 /// Identifier
102 /// The identifier is very similar to bytes, however it is serialized to Base58 when converted
103 /// to a JSON Value
104 Identifier(Hash256),
105
106 /// A float
107 Float(f64),
108
109 /// A string
110 Text(String),
111
112 /// A boolean
113 Bool(bool),
114
115 /// Null
116 Null,
117
118 /// An array
119 Array(Vec<Value>),
120
121 /// A map
122 Map(ValueMap),
123}
124
125impl Value {
126 /// Returns true if the `Value` is an `Integer`. Returns false otherwise.
127 ///
128 /// ```
129 /// # use platform_value::Value;
130 /// #
131 /// let value = Value::U64(17);
132 ///
133 /// assert!(value.is_integer());
134 /// ```
135 pub fn is_integer(&self) -> bool {
136 matches!(
137 self,
138 Value::U128(_)
139 | Value::I128(_)
140 | Value::U64(_)
141 | Value::I64(_)
142 | Value::U32(_)
143 | Value::I32(_)
144 | Value::U16(_)
145 | Value::I16(_)
146 | Value::U8(_)
147 | Value::I8(_)
148 )
149 }
150
151 /// Returns true if the `Value` is an integer that fits in 64 bits (u64/i64).
152 /// Returns false otherwise.
153 ///
154 /// ```
155 /// # use platform_value::Value;
156 /// #
157 /// let value = Value::U128(17);
158 ///
159 /// assert!(value.is_integer_can_fit_in_64_bits());
160 /// ```
161 pub fn is_integer_can_fit_in_64_bits(&self) -> bool {
162 match self {
163 // Already ≤ 64-bit widths
164 Value::U64(_)
165 | Value::I64(_)
166 | Value::U32(_)
167 | Value::I32(_)
168 | Value::U16(_)
169 | Value::I16(_)
170 | Value::U8(_)
171 | Value::I8(_) => true,
172
173 // 128-bit -> check if within 64-bit range
174 Value::U128(v) => *v <= u64::MAX as u128,
175 Value::I128(v) => (*v >= i64::MIN as i128) && (*v <= i64::MAX as i128),
176
177 // Non-integer variants
178 _ => false,
179 }
180 }
181
182 /// If the `Value` is a `Integer`, returns a reference to the associated `Integer` data.
183 /// Returns None otherwise.
184 ///
185 /// ```
186 /// # use platform_value::Value;
187 /// #
188 /// let value = Value::U64(17);
189 ///
190 /// // We can read the number
191 /// let r_value : u64 = value.as_integer().unwrap();
192 /// assert_eq!(17, r_value);
193 /// ```
194 pub fn as_integer<T>(&self) -> Option<T>
195 where
196 T: TryFrom<i128>
197 + TryFrom<u128>
198 + TryFrom<u64>
199 + TryFrom<i64>
200 + TryFrom<u32>
201 + TryFrom<i32>
202 + TryFrom<u16>
203 + TryFrom<i16>
204 + TryFrom<u8>
205 + TryFrom<i8>,
206 {
207 match self {
208 Value::U128(int) => (*int).try_into().ok(),
209 Value::I128(int) => (*int).try_into().ok(),
210 Value::U64(int) => (*int).try_into().ok(),
211 Value::I64(int) => (*int).try_into().ok(),
212 Value::U32(int) => (*int).try_into().ok(),
213 Value::I32(int) => (*int).try_into().ok(),
214 Value::U16(int) => (*int).try_into().ok(),
215 Value::I16(int) => (*int).try_into().ok(),
216 Value::U8(int) => (*int).try_into().ok(),
217 Value::I8(int) => (*int).try_into().ok(),
218 _ => None,
219 }
220 }
221
222 /// If the `Value` is a `Integer`, returns a the associated `Integer` data as `Ok`.
223 /// Returns `Err(Error::Structure("reason"))` otherwise.
224 ///
225 /// ```
226 /// # use platform_value::{Value, Error};
227 /// #
228 /// let value = Value::U64(17);
229 /// let r_value : Result<u64,Error> = value.into_integer();
230 /// assert_eq!(r_value, Ok(17));
231 ///
232 /// let value = Value::Bool(true);
233 /// let r_value : Result<u64,Error> = value.into_integer();
234 /// assert_eq!(r_value, Err(Error::StructureError("value is not an integer".to_string())));
235 /// ```
236 pub fn into_integer<T>(self) -> Result<T, Error>
237 where
238 T: TryFrom<i128>
239 + TryFrom<u128>
240 + TryFrom<u64>
241 + TryFrom<i64>
242 + TryFrom<u32>
243 + TryFrom<i32>
244 + TryFrom<u16>
245 + TryFrom<i16>
246 + TryFrom<u8>
247 + TryFrom<i8>,
248 {
249 match self {
250 Value::U128(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
251 Value::I128(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
252 Value::U64(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
253 Value::I64(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
254 Value::U32(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
255 Value::I32(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
256 Value::U16(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
257 Value::I16(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
258 Value::U8(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
259 Value::I8(int) => int.try_into().map_err(|_| Error::IntegerSizeError),
260 _other => Err(Error::StructureError("value is not an integer".to_string())),
261 }
262 }
263
264 /// If the `Value` is a `Integer`, returns a the associated `Integer` data as `Ok`.
265 /// Returns `Err(Error::Structure("reason"))` otherwise.
266 ///
267 /// ```
268 /// # use platform_value::{Value, Error};
269 /// #
270 /// let value = Value::U64(17);
271 /// let r_value : Result<u64,Error> = value.to_integer();
272 /// assert_eq!(r_value, Ok(17));
273 ///
274 /// let value = Value::Bool(true);
275 /// let r_value : Result<u64,Error> = value.to_integer();
276 /// assert_eq!(r_value, Err(Error::StructureError("value is not an integer, found bool true".to_string())));
277 /// ```
278 pub fn to_integer<T>(&self) -> Result<T, Error>
279 where
280 T: TryFrom<i128>
281 + TryFrom<u128>
282 + TryFrom<u64>
283 + TryFrom<i64>
284 + TryFrom<u32>
285 + TryFrom<i32>
286 + TryFrom<u16>
287 + TryFrom<i16>
288 + TryFrom<u8>
289 + TryFrom<i8>,
290 {
291 match self {
292 Value::U128(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
293 Value::I128(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
294 Value::U64(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
295 Value::I64(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
296 Value::U32(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
297 Value::I32(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
298 Value::U16(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
299 Value::I16(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
300 Value::U8(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
301 Value::I8(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
302 other => Err(Error::StructureError(format!(
303 "value is not an integer, found {}",
304 other
305 ))),
306 }
307 }
308
309 /// If the `Value` is an `Integer`, a `String` or a `Float` or even a `Bool`, returns the
310 /// associated `Integer` data as `Ok`.
311 /// Returns `Err(Error::Structure("reason"))` otherwise.
312 ///
313 /// ```
314 /// # use platform_value::{Value, Error};
315 /// #
316 /// let value = Value::U64(17);
317 /// let r_value : Result<u64,Error> = value.to_integer_broad_conversion();
318 /// assert_eq!(r_value, Ok(17));
319 ///
320 /// let value = Value::Text("17".to_string());
321 /// let r_value : Result<u64,Error> = value.to_integer_broad_conversion();
322 /// assert_eq!(r_value, Ok(17));
323 ///
324 /// let value = Value::Bool(true);
325 /// let r_value : Result<u64,Error> = value.to_integer_broad_conversion();
326 /// assert_eq!(r_value, Ok(1));
327 /// ```
328 pub fn to_integer_broad_conversion<T>(&self) -> Result<T, Error>
329 where
330 T: TryFrom<i128>
331 + TryFrom<u128>
332 + TryFrom<u64>
333 + TryFrom<i64>
334 + TryFrom<u32>
335 + TryFrom<i32>
336 + TryFrom<u16>
337 + TryFrom<i16>
338 + TryFrom<u8>
339 + TryFrom<i8>,
340 {
341 match self {
342 Value::U128(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
343 Value::I128(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
344 Value::U64(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
345 Value::I64(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
346 Value::U32(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
347 Value::I32(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
348 Value::U16(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
349 Value::I16(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
350 Value::U8(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
351 Value::I8(int) => (*int).try_into().map_err(|_| Error::IntegerSizeError),
352 Value::Float(float) => {
353 let max_f64 = u128::MAX as f64;
354 let min_f64 = i128::MIN as f64;
355 if *float > 0f64 && *float < max_f64 {
356 (*float as u128)
357 .try_into()
358 .map_err(|_| Error::IntegerSizeError)
359 } else if *float > min_f64 && *float < 0f64 {
360 (*float as i128)
361 .try_into()
362 .map_err(|_| Error::IntegerSizeError)
363 } else {
364 Err(Error::IntegerSizeError)
365 }
366 }
367 Value::Bool(bool) => {
368 let i: u8 = (*bool).into();
369 i.try_into().map_err(|_| Error::IntegerSizeError)
370 }
371 Value::Text(text) => text
372 .parse::<i128>()
373 .map_err(|_| Error::IntegerSizeError)?
374 .try_into()
375 .map_err(|_| Error::IntegerSizeError),
376 other => Err(Error::StructureError(format!(
377 "value can not be converted to an integer, found {}",
378 other
379 ))),
380 }
381 }
382
383 /// Returns true if the `Value` is a `Bytes`. Returns false otherwise.
384 ///
385 /// ```
386 /// # use platform_value::Value;
387 /// #
388 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
389 ///
390 /// assert!(value.is_bytes());
391 /// ```
392 pub fn is_bytes(&self) -> bool {
393 self.as_bytes().is_some()
394 }
395
396 /// Returns true if the `Value` is a `Bytes`. Returns false otherwise.
397 ///
398 /// ```
399 /// # use platform_value::Value;
400 /// #
401 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
402 ///
403 /// assert!(value.is_any_bytes_type());
404 ///
405 /// let value = Value::Identifier([1u8;32]);
406 ///
407 /// assert!(value.is_any_bytes_type());
408 ///
409 /// let value = Value::Bytes20([1u8;20]);
410 ///
411 /// assert!(value.is_any_bytes_type());
412 ///
413 /// let value = Value::Bytes32([1u8;32]);
414 ///
415 /// assert!(value.is_any_bytes_type());
416 ///
417 /// let value = Value::Bytes36([1u8;36]);
418 ///
419 /// assert!(value.is_any_bytes_type());
420 /// ```
421 pub fn is_any_bytes_type(&self) -> bool {
422 matches!(
423 self,
424 Value::Bytes(_)
425 | Value::Bytes20(_)
426 | Value::Bytes32(_)
427 | Value::Bytes36(_)
428 | Value::Identifier(_)
429 )
430 }
431
432 /// If the `Value` is a `Bytes`, returns a reference to the associated bytes vector.
433 /// Returns None otherwise.
434 ///
435 /// ```
436 /// # use platform_value::Value;
437 /// #
438 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
439 ///
440 /// assert_eq!(std::str::from_utf8(value.as_bytes().unwrap()).unwrap(), "hello");
441 /// ```
442 pub fn as_bytes(&self) -> Option<&Vec<u8>> {
443 match *self {
444 Value::Bytes(ref bytes) => Some(bytes),
445 _ => None,
446 }
447 }
448
449 /// If the `Value` is a `Bytes`, returns a mutable reference to the associated bytes vector.
450 /// Returns None otherwise.
451 ///
452 /// ```
453 /// # use platform_value::Value;
454 /// #
455 /// let mut value = Value::Bytes(vec![104, 101, 108, 108, 111]);
456 /// value.as_bytes_mut().unwrap().clear();
457 ///
458 /// assert_eq!(value, Value::Bytes(vec![]));
459 /// ```
460 pub fn as_bytes_mut(&mut self) -> Option<&mut Vec<u8>> {
461 match *self {
462 Value::Bytes(ref mut bytes) => Some(bytes),
463 _ => None,
464 }
465 }
466
467 /// If the `Value` is a `Bytes`, returns a the associated `Vec<u8>` data as `Ok`.
468 /// Returns `Err(Error::Structure("reason"))` otherwise.
469 ///
470 /// ```
471 /// # use platform_value::{Error, Value};
472 /// #
473 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
474 /// assert_eq!(value.into_bytes(), Ok(vec![104, 101, 108, 108, 111]));
475 ///
476 /// let value = Value::Bool(true);
477 /// assert_eq!(value.into_bytes(), Err(Error::StructureError("value are not bytes".to_string())));
478 /// ```
479 pub fn into_bytes(self) -> Result<Vec<u8>, Error> {
480 match self {
481 Value::Bytes(vec) => Ok(vec),
482 Value::Bytes20(vec) => Ok(vec.to_vec()),
483 Value::Bytes32(vec) => Ok(vec.to_vec()),
484 Value::Bytes36(vec) => Ok(vec.to_vec()),
485 Value::Identifier(vec) => Ok(vec.to_vec()),
486 Value::Array(array) => Ok(array
487 .into_iter()
488 .map(|byte| byte.into_integer())
489 .collect::<Result<Vec<u8>, Error>>()?),
490 _other => Err(Error::StructureError("value are not bytes".to_string())),
491 }
492 }
493
494 /// If the `Value` is a ref to `Bytes`, returns a the associated `Vec<u8>` data as `Ok`.
495 /// Returns `Err(Error::Structure("reason"))` otherwise.
496 ///
497 /// ```
498 /// # use platform_value::{Error, Value};
499 /// #
500 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
501 /// assert_eq!(value.to_bytes(), Ok(vec![104, 101, 108, 108, 111]));
502 ///
503 /// let value = Value::Bool(true);
504 /// assert_eq!(value.to_bytes(), Err(Error::StructureError("ref value are not bytes found bool true instead".to_string())));
505 /// ```
506 pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
507 match self {
508 Value::Bytes(vec) => Ok(vec.clone()),
509 Value::Bytes20(vec) => Ok(vec.to_vec()),
510 Value::Bytes32(vec) => Ok(vec.to_vec()),
511 Value::Bytes36(vec) => Ok(vec.to_vec()),
512 Value::Identifier(vec) => Ok(vec.to_vec()),
513 Value::Array(array) => Ok(array
514 .iter()
515 .map(|byte| byte.to_integer())
516 .collect::<Result<Vec<u8>, Error>>()?),
517 other => Err(Error::StructureError(format!(
518 "ref value are not bytes found {} instead",
519 other
520 ))),
521 }
522 }
523
524 /// If the `Value` is a ref to `Bytes`, returns a the associated `BinaryData` data as `Ok`.
525 /// BinaryData wraps Vec<u8>
526 /// Returns `Err(Error::Structure("reason"))` otherwise.
527 ///
528 /// ```
529 /// # use platform_value::{BinaryData, Error, Value};
530 /// #
531 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
532 /// assert_eq!(value.to_binary_data(), Ok(BinaryData::new(vec![104, 101, 108, 108, 111])));
533 ///
534 /// let value = Value::Bool(true);
535 /// assert_eq!(value.to_binary_data(), Err(Error::StructureError("ref value are not bytes found bool true instead".to_string())));
536 /// ```
537 pub fn to_binary_data(&self) -> Result<BinaryData, Error> {
538 match self {
539 Value::Bytes(vec) => Ok(BinaryData::new(vec.clone())),
540 Value::Bytes20(vec) => Ok(BinaryData::new(vec.to_vec())),
541 Value::Bytes32(vec) => Ok(BinaryData::new(vec.to_vec())),
542 Value::Bytes36(vec) => Ok(BinaryData::new(vec.to_vec())),
543 Value::Identifier(vec) => Ok(BinaryData::new(vec.to_vec())),
544 Value::Array(array) => Ok(BinaryData::new(
545 array
546 .iter()
547 .map(|byte| byte.to_integer())
548 .collect::<Result<Vec<u8>, Error>>()?,
549 )),
550 other => Err(Error::StructureError(format!(
551 "ref value are not bytes found {} instead",
552 other
553 ))),
554 }
555 }
556
557 /// If the `Value` is a ref to `Bytes`, returns a the associated `&[u8]` data as `Ok`.
558 /// Returns `Err(Error::Structure("reason"))` otherwise.
559 ///
560 /// ```
561 /// # use platform_value::{Error, Value};
562 /// #
563 /// let value = Value::Bytes(vec![104, 101, 108, 108, 111]);
564 /// assert_eq!(value.as_bytes_slice(), Ok(vec![104, 101, 108, 108, 111].as_slice()));
565 ///
566 /// let value = Value::Bool(true);
567 /// assert_eq!(value.as_bytes_slice(), Err(Error::StructureError("ref value are not bytes slice".to_string())));
568 /// ```
569 pub fn as_bytes_slice(&self) -> Result<&[u8], Error> {
570 match self {
571 Value::Bytes(vec) => Ok(vec),
572 Value::Bytes20(vec) => Ok(vec.as_slice()),
573 Value::Bytes32(vec) => Ok(vec.as_slice()),
574 Value::Bytes36(vec) => Ok(vec.as_slice()),
575 Value::Identifier(vec) => Ok(vec.as_slice()),
576 _other => Err(Error::StructureError(
577 "ref value are not bytes slice".to_string(),
578 )),
579 }
580 }
581
582 /// Returns true if the `Value` is a `Float`. Returns false otherwise.
583 ///
584 /// ```
585 /// # use platform_value::Value;
586 /// #
587 /// let value = Value::Float(17.0.into());
588 ///
589 /// assert!(value.is_float());
590 /// ```
591 pub fn is_float(&self) -> bool {
592 self.as_float().is_some()
593 }
594
595 /// If the `Value` is a `Float`, returns a reference to the associated float data.
596 /// Returns None otherwise.
597 ///
598 /// ```
599 /// # use platform_value::Value;
600 /// #
601 /// let value = Value::Float(17.0.into());
602 ///
603 /// // We can read the float number
604 /// assert_eq!(value.as_float().unwrap(), 17.0_f64);
605 /// ```
606 pub fn as_float(&self) -> Option<f64> {
607 match *self {
608 Value::U128(int) => Some(int as f64),
609 Value::I128(int) => Some(int as f64),
610 Value::U64(int) => Some(int as f64),
611 Value::I64(int) => Some(int as f64),
612 Value::U32(int) => Some(int as f64),
613 Value::I32(int) => Some(int as f64),
614 Value::U16(int) => Some(int as f64),
615 Value::I16(int) => Some(int as f64),
616 Value::U8(int) => Some(int as f64),
617 Value::I8(int) => Some(int as f64),
618 Value::Float(f) => Some(f),
619 _ => None,
620 }
621 }
622
623 /// If the `Value` is a `Float`, returns a the associated `f64` data as `Ok`.
624 /// Returns `Err(Error::Structure("reason"))` otherwise.
625 ///
626 /// ```
627 /// # use platform_value::{Error, Value};
628 /// #
629 /// let value = Value::Float(17.);
630 /// assert_eq!(value.into_float(), Ok(17.));
631 ///
632 /// let value = Value::Bool(true);
633 /// assert_eq!(value.into_float(), Err(Error::StructureError("value is not a float".to_string())));
634 /// ```
635 pub fn into_float(self) -> Result<f64, Error> {
636 match self {
637 Value::U128(int) => Ok(int as f64),
638 Value::I128(int) => Ok(int as f64),
639 Value::U64(int) => Ok(int as f64),
640 Value::I64(int) => Ok(int as f64),
641 Value::U32(int) => Ok(int as f64),
642 Value::I32(int) => Ok(int as f64),
643 Value::U16(int) => Ok(int as f64),
644 Value::I16(int) => Ok(int as f64),
645 Value::U8(int) => Ok(int as f64),
646 Value::I8(int) => Ok(int as f64),
647 Value::Float(f) => Ok(f),
648 _other => Err(Error::StructureError("value is not a float".to_string())),
649 }
650 }
651
652 /// If the `Value` is a `Float`, returns a the associated `f64` data as `Ok`.
653 /// Returns `Err(Error::Structure("reason"))` otherwise.
654 ///
655 /// ```
656 /// # use platform_value::{Error, Value};
657 /// #
658 /// let value = Value::Float(17.);
659 /// assert_eq!(value.to_float(), Ok(17.));
660 ///
661 /// let value = Value::Bool(true);
662 /// assert_eq!(value.to_float(), Err(Error::StructureError("value is not a float".to_string())));
663 /// ```
664 pub fn to_float(&self) -> Result<f64, Error> {
665 match self {
666 Value::U128(int) => Ok(*int as f64),
667 Value::I128(int) => Ok(*int as f64),
668 Value::U64(int) => Ok(*int as f64),
669 Value::I64(int) => Ok(*int as f64),
670 Value::U32(int) => Ok(*int as f64),
671 Value::I32(int) => Ok(*int as f64),
672 Value::U16(int) => Ok(*int as f64),
673 Value::I16(int) => Ok(*int as f64),
674 Value::U8(int) => Ok(*int as f64),
675 Value::I8(int) => Ok(*int as f64),
676 Value::Float(f) => Ok(*f),
677 _other => Err(Error::StructureError("value is not a float".to_string())),
678 }
679 }
680
681 /// Returns true if the `Value` is a `Text`. Returns false otherwise.
682 ///
683 /// ```
684 /// # use platform_value::Value;
685 /// #
686 /// let value = Value::Text(String::from("hello"));
687 ///
688 /// assert!(value.is_text());
689 /// ```
690 pub fn is_text(&self) -> bool {
691 self.as_text().is_some()
692 }
693
694 /// If the `Value` is a `Text`, returns a reference to the associated `String` data.
695 /// Returns None otherwise.
696 ///
697 /// ```
698 /// # use platform_value::Value;
699 /// #
700 /// let value = Value::Text(String::from("hello"));
701 ///
702 /// // We can read the String
703 /// assert_eq!(value.as_text().unwrap(), "hello");
704 /// ```
705 pub fn as_text(&self) -> Option<&str> {
706 match *self {
707 Value::Text(ref s) => Some(s),
708 _ => None,
709 }
710 }
711
712 /// If the `Value` is a `Text`, returns a mutable reference to the associated `String` data.
713 /// Returns None otherwise.
714 ///
715 /// ```
716 /// # use platform_value::Value;
717 /// #
718 /// let mut value = Value::Text(String::from("hello"));
719 /// value.as_text_mut().unwrap().clear();
720 ///
721 /// assert_eq!(value.as_text().unwrap(), &String::from(""));
722 /// ```
723 pub fn as_text_mut(&mut self) -> Option<&mut String> {
724 match *self {
725 Value::Text(ref mut s) => Some(s),
726 _ => None,
727 }
728 }
729
730 /// If the `Value` is a `String`, returns a the associated `String` data as `Ok`.
731 /// Returns `Err(Error::Structure("reason"))` otherwise.
732 ///
733 /// ```
734 /// # use platform_value::{Error, Value};
735 /// #
736 /// let value = Value::Text(String::from("hello"));
737 /// assert_eq!(value.into_text().as_deref(), Ok("hello"));
738 ///
739 /// let value = Value::Bool(true);
740 /// assert_eq!(value.into_text(), Err(Error::StructureError("value is not a string".to_string())));
741 /// ```
742 pub fn into_text(self) -> Result<String, Error> {
743 match self {
744 Value::Text(s) => Ok(s),
745 _other => Err(Error::StructureError("value is not a string".to_string())),
746 }
747 }
748
749 /// If the `Value` is a `String`, returns a the associated `String` data as `Ok`.
750 /// Returns `Err(Error::Structure("reason"))` otherwise.
751 ///
752 /// ```
753 /// # use platform_value::{Error, Value};
754 /// #
755 /// let value = Value::Text(String::from("hello"));
756 /// assert_eq!(value.to_text().as_deref(), Ok("hello"));
757 ///
758 /// let value = Value::Bool(true);
759 /// assert_eq!(value.to_text(), Err(Error::StructureError("value is not a string".to_string())));
760 /// ```
761 pub fn to_text(&self) -> Result<String, Error> {
762 match self {
763 Value::Text(s) => Ok(s.clone()),
764 _other => Err(Error::StructureError("value is not a string".to_string())),
765 }
766 }
767
768 /// If the `Value` is a `String`, returns a the associated `&str` data as `Ok`.
769 /// Returns `Err(Error::Structure("reason"))` otherwise.
770 ///
771 /// ```
772 /// # use platform_value::{Error, Value};
773 /// #
774 /// let value = Value::Text(String::from("hello"));
775 /// assert_eq!(value.to_str(), Ok("hello"));
776 ///
777 /// let value = Value::Bool(true);
778 /// assert_eq!(value.to_str(), Err(Error::StructureError("value is not a string".to_string())));
779 /// ```
780 pub fn to_str(&self) -> Result<&str, Error> {
781 match self {
782 Value::Text(s) => Ok(s),
783 _other => Err(Error::StructureError("value is not a string".to_string())),
784 }
785 }
786
787 /// If the `Value` is a `String`, returns a reference to the associated `String` data as `Ok`.
788 /// Returns `Err(Error::Structure("reason"))` otherwise.
789 ///
790 /// ```
791 /// # use platform_value::{Error, Value};
792 /// #
793 /// let value = Value::Text(String::from("hello"));
794 /// assert_eq!(value.as_str(), Some("hello"));
795 ///
796 /// let value = Value::Bool(true);
797 /// assert_eq!(value.as_str(), None);
798 /// ```
799 pub fn as_str(&self) -> Option<&str> {
800 match self {
801 Value::Text(s) => Some(s),
802 _ => None,
803 }
804 }
805
806 /// Returns true if the `Value` is a `Bool`. Returns false otherwise.
807 ///
808 /// ```
809 /// # use platform_value::Value;
810 /// #
811 /// let value = Value::Bool(false);
812 ///
813 /// assert!(value.is_bool());
814 /// ```
815 pub fn is_bool(&self) -> bool {
816 self.as_bool().is_some()
817 }
818
819 /// If the `Value` is a `Bool`, returns a copy of the associated boolean value. Returns None
820 /// otherwise.
821 ///
822 /// ```
823 /// # use platform_value::Value;
824 /// #
825 /// let value = Value::Bool(false);
826 ///
827 /// assert_eq!(value.as_bool().unwrap(), false);
828 /// ```
829 pub fn as_bool(&self) -> Option<bool> {
830 match *self {
831 Value::Bool(b) => Some(b),
832 _ => None,
833 }
834 }
835
836 /// If the `Value` is a `Bool`, returns a the associated `bool` data as `Ok`.
837 /// Returns `Err(Error::Structure("reason"))` otherwise.
838 ///
839 /// ```
840 /// # use platform_value::{Error, Value};
841 /// #
842 /// let value = Value::Bool(false);
843 /// assert_eq!(value.into_bool(), Ok(false));
844 ///
845 /// let value = Value::Float(17.);
846 /// assert_eq!(value.into_bool(), Err(Error::StructureError("value is not a bool".to_string())));
847 /// ```
848 pub fn into_bool(self) -> Result<bool, Error> {
849 match self {
850 Value::Bool(b) => Ok(b),
851 _other => Err(Error::StructureError("value is not a bool".to_string())),
852 }
853 }
854
855 /// If the `Value` is a `Bool`, returns a the associated `bool` data as `Ok`.
856 /// Returns `Err(Error::Structure("reason"))` otherwise.
857 ///
858 /// ```
859 /// # use platform_value::{Error, Value};
860 /// #
861 /// let value = Value::Bool(false);
862 /// assert_eq!(value.to_bool(), Ok(false));
863 ///
864 /// let value = Value::Float(17.);
865 /// assert_eq!(value.to_bool(), Err(Error::StructureError("value is not a bool".to_string())));
866 /// ```
867 pub fn to_bool(&self) -> Result<bool, Error> {
868 match self {
869 Value::Bool(b) => Ok(*b),
870 _other => Err(Error::StructureError("value is not a bool".to_string())),
871 }
872 }
873
874 /// Returns true if the `Value` is a `Null`. Returns false otherwise.
875 ///
876 /// ```
877 /// # use platform_value::Value;
878 /// #
879 /// let value = Value::Null;
880 ///
881 /// assert!(value.is_null());
882 /// ```
883 pub fn is_null(&self) -> bool {
884 matches!(self, Value::Null)
885 }
886
887 /// Returns true if the `Value` is an Array. Returns false otherwise.
888 ///
889 /// ```
890 /// # use platform_value::Value;
891 /// #
892 /// let value = Value::Array(
893 /// vec![
894 /// Value::Text(String::from("foo")),
895 /// Value::Text(String::from("bar"))
896 /// ]
897 /// );
898 ///
899 /// assert!(value.is_array());
900 /// ```
901 pub fn is_array(&self) -> bool {
902 self.as_array().is_some()
903 }
904
905 /// If the `Value` is an Array, returns a reference to the associated vector. Returns None
906 /// otherwise.
907 ///
908 /// ```
909 /// # use platform_value::Value;
910 /// #
911 /// let value = Value::Array(
912 /// vec![
913 /// Value::Text(String::from("foo")),
914 /// Value::Text(String::from("bar"))
915 /// ]
916 /// );
917 ///
918 /// // The length of `value` is 2 elements.
919 /// assert_eq!(value.as_array().unwrap().len(), 2);
920 /// ```
921 pub fn as_array(&self) -> Option<&Vec<Value>> {
922 match *self {
923 Value::Array(ref array) => Some(array),
924 _ => None,
925 }
926 }
927
928 /// If the `Value` is an Array, returns a mutable reference to the associated vector.
929 /// Returns None otherwise.
930 ///
931 /// ```
932 /// # use platform_value::Value;
933 /// #
934 /// let mut value = Value::Array(
935 /// vec![
936 /// Value::Text(String::from("foo")),
937 /// Value::Text(String::from("bar"))
938 /// ]
939 /// );
940 ///
941 /// value.as_array_mut().unwrap().clear();
942 /// assert_eq!(value, Value::Array(vec![]));
943 /// ```
944 pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
945 match *self {
946 Value::Array(ref mut list) => Some(list),
947 _ => None,
948 }
949 }
950
951 /// If the `Value` is an Array, returns a mutable reference to the associated vector.
952 /// Returns None otherwise.
953 ///
954 /// ```
955 /// # use platform_value::Value;
956 /// #
957 /// let mut value = Value::Array(
958 /// vec![
959 /// Value::Text(String::from("foo")),
960 /// Value::Text(String::from("bar"))
961 /// ]
962 /// );
963 ///
964 /// value.to_array_mut().unwrap().clear();
965 /// assert_eq!(value, Value::Array(vec![]));
966 /// ```
967 pub fn to_array_mut(&mut self) -> Result<&mut Vec<Value>, Error> {
968 match self {
969 Value::Array(vec) => Ok(vec),
970 other => Err(Error::StructureError(format!(
971 "value is not a mut array got {}",
972 other
973 ))),
974 }
975 }
976
977 /// If the `Value` is a `Array`, returns a the associated `&[Value]` slice as `Ok`.
978 /// Returns `Err(Error::Structure("reason"))` otherwise.
979 ///
980 /// ```
981 /// # use platform_value::{Value, Error};
982 /// #
983 /// let mut value = Value::Array(
984 /// vec![
985 /// Value::U64(17),
986 /// Value::Float(18.),
987 /// ]
988 /// );
989 /// assert_eq!(value.to_array_slice(), Ok(vec![Value::U64(17), Value::Float(18.)].as_slice()));
990 ///
991 /// let value = Value::Bool(true);
992 /// assert_eq!(value.to_array_slice(), Err(Error::StructureError("value is not an array got bool true".to_string())));
993 /// ```
994 pub fn to_array_slice(&self) -> Result<&[Value], Error> {
995 match self {
996 Value::Array(vec) => Ok(vec.as_slice()),
997 other => Err(Error::StructureError(format!(
998 "value is not an array got {}",
999 other
1000 ))),
1001 }
1002 }
1003
1004 /// If the `Value` is a `Array`, returns a the associated `Vec<&Value>` array as `Ok`.
1005 /// Returns `Err(Error::Structure("reason"))` otherwise.
1006 ///
1007 /// ```
1008 /// # use platform_value::{Value, Error};
1009 /// #
1010 /// let mut value = Value::Array(
1011 /// vec![
1012 /// Value::U64(17),
1013 /// Value::Float(18.),
1014 /// ]
1015 /// );
1016 /// assert_eq!(value.to_array_ref(), Ok(&vec![Value::U64(17), Value::Float(18.)]));
1017 ///
1018 /// let value = Value::Bool(true);
1019 /// assert_eq!(value.to_array_ref(), Err(Error::StructureError("value is not an array got bool true".to_string())));
1020 /// ```
1021 pub fn to_array_ref(&self) -> Result<&Vec<Value>, Error> {
1022 match self {
1023 Value::Array(vec) => Ok(vec),
1024 other => Err(Error::StructureError(format!(
1025 "value is not an array got {}",
1026 other
1027 ))),
1028 }
1029 }
1030
1031 /// If the `Value` is a `Array`, returns a the associated `Vec<Value>` data as `Ok`.
1032 /// Returns `Err(Error::Structure("reason"))` otherwise.
1033 ///
1034 /// ```
1035 /// # use platform_value::{Value, Error};
1036 /// #
1037 /// let mut value = Value::Array(
1038 /// vec![
1039 /// Value::U64(17),
1040 /// Value::Float(18.),
1041 /// ]
1042 /// );
1043 /// assert_eq!(value.to_array_owned(), Ok(vec![Value::U64(17), Value::Float(18.)]));
1044 ///
1045 /// let value = Value::Bool(true);
1046 /// assert_eq!(value.to_array_owned(), Err(Error::StructureError("value is not an owned array got bool true".to_string())));
1047 /// ```
1048 pub fn to_array_owned(&self) -> Result<Vec<Value>, Error> {
1049 match self {
1050 Value::Array(vec) => Ok(vec.clone()),
1051 other => Err(Error::StructureError(format!(
1052 "value is not an owned array got {}",
1053 other
1054 ))),
1055 }
1056 }
1057
1058 /// If the `Value` is a `Array`, returns a the associated `Vec<Value>` data as `Ok`.
1059 /// Returns `Err(Error::Structure("reason"))` otherwise.
1060 ///
1061 /// ```
1062 /// # use platform_value::{Value, Error};
1063 /// #
1064 /// let mut value = Value::Array(
1065 /// vec![
1066 /// Value::U64(17),
1067 /// Value::Float(18.),
1068 /// ]
1069 /// );
1070 /// assert_eq!(value.into_array(), Ok(vec![Value::U64(17), Value::Float(18.)]));
1071 ///
1072 /// let value = Value::Bool(true);
1073 /// assert_eq!(value.into_array(), Err(Error::StructureError("value is not an array (into) got bool true".to_string())));
1074 /// ```
1075 pub fn into_array(self) -> Result<Vec<Value>, Error> {
1076 match self {
1077 Value::Array(vec) => Ok(vec),
1078 other => Err(Error::StructureError(format!(
1079 "value is not an array (into) got {}",
1080 other
1081 ))),
1082 }
1083 }
1084
1085 /// If the `Value` is a `Array`, returns a the associated `Vec<Value>` data as `Ok`.
1086 /// Returns `Err(Error::Structure("reason"))` otherwise.
1087 ///
1088 /// ```
1089 /// # use platform_value::{Value, Error};
1090 /// #
1091 /// let mut value = Value::Array(
1092 /// vec![
1093 /// Value::U64(17),
1094 /// Value::Float(18.),
1095 /// ]
1096 /// );
1097 /// assert_eq!(value.as_slice(), Ok(vec![Value::U64(17), Value::Float(18.)].as_slice()));
1098 ///
1099 /// let value = Value::Bool(true);
1100 /// assert_eq!(value.as_slice(), Err(Error::StructureError("value is not a slice got bool true".to_string())));
1101 /// ```
1102 pub fn as_slice(&self) -> Result<&[Value], Error> {
1103 match self {
1104 Value::Array(vec) => Ok(vec),
1105 other => Err(Error::StructureError(format!(
1106 "value is not a slice got {}",
1107 other
1108 ))),
1109 }
1110 }
1111
1112 /// Returns true if the `Value` is a Map. Returns false otherwise.
1113 ///
1114 /// ```
1115 /// # use platform_value::Value;
1116 /// #
1117 /// let value = Value::Map(
1118 /// vec![
1119 /// (Value::Text(String::from("foo")), Value::Text(String::from("bar")))
1120 /// ]
1121 /// );
1122 ///
1123 /// assert!(value.is_map());
1124 /// ```
1125 pub fn is_map(&self) -> bool {
1126 self.as_map().is_some()
1127 }
1128
1129 /// If the `Value` is a Map, returns a reference to the associated Map data. Returns None
1130 /// otherwise.
1131 ///
1132 /// ```
1133 /// # use platform_value::Value;
1134 /// #
1135 /// let value = Value::Map(
1136 /// vec![
1137 /// (Value::Text(String::from("foo")), Value::Text(String::from("bar")))
1138 /// ]
1139 /// );
1140 ///
1141 /// // The length of data is 1 entry (1 key/value pair).
1142 /// assert_eq!(value.as_map().unwrap().len(), 1);
1143 ///
1144 /// // The content of the first element is what we expect
1145 /// assert_eq!(
1146 /// value.as_map().unwrap().get(0).unwrap(),
1147 /// &(Value::Text(String::from("foo")), Value::Text(String::from("bar")))
1148 /// );
1149 /// ```
1150 pub fn as_map(&self) -> Option<&Vec<(Value, Value)>> {
1151 match *self {
1152 Value::Map(ref map) => Some(map),
1153 _ => None,
1154 }
1155 }
1156
1157 /// If the `Value` is a Map, returns a mutable reference to the associated Map Data.
1158 /// Returns None otherwise.
1159 ///
1160 /// ```
1161 /// # use platform_value::Value;
1162 /// #
1163 /// let mut value = Value::Map(
1164 /// vec![
1165 /// (Value::Text(String::from("foo")), Value::Text(String::from("bar")))
1166 /// ]
1167 /// );
1168 ///
1169 /// value.as_map_mut().unwrap().clear();
1170 /// assert_eq!(value, Value::Map(vec![]));
1171 /// assert_eq!(value.as_map().unwrap().len(), 0);
1172 /// ```
1173 pub fn as_map_mut(&mut self) -> Option<&mut Vec<(Value, Value)>> {
1174 match *self {
1175 Value::Map(ref mut map) => Some(map),
1176 _ => None,
1177 }
1178 }
1179
1180 /// If the `Value` is a Map, returns a mutable reference to the associated Map Data.
1181 /// Returns Err otherwise.
1182 ///
1183 /// ```
1184 /// # use platform_value::Value;
1185 /// #
1186 /// let mut value = Value::Map(
1187 /// vec![
1188 /// (Value::Text(String::from("foo")), Value::Text(String::from("bar")))
1189 /// ]
1190 /// );
1191 ///
1192 /// value.to_map_mut().unwrap().clear();
1193 /// assert_eq!(value, Value::Map(vec![]));
1194 /// assert_eq!(value.as_map().unwrap().len(), 0);
1195 /// ```
1196 pub fn to_map_mut(&mut self) -> Result<&mut ValueMap, Error> {
1197 match *self {
1198 Value::Map(ref mut map) => Ok(map),
1199 _ => Err(Error::StructureError("value is not a map".to_string())),
1200 }
1201 }
1202
1203 /// If the `Value` is a `Map`, returns a the associated ValueMap which is a `Vec<(Value, Value)>`
1204 /// data as `Ok`.
1205 /// Returns `Err(Error::Structure("reason"))` otherwise.
1206 ///
1207 /// ```
1208 /// # use platform_value::{Error, Value};
1209 /// #
1210 /// let mut value = Value::Map(
1211 /// vec![
1212 /// (Value::Text(String::from("key")), Value::Float(18.)),
1213 /// ]
1214 /// );
1215 /// assert_eq!(value.into_map(), Ok(vec![(Value::Text(String::from("key")), Value::Float(18.))]));
1216 ///
1217 /// let value = Value::Bool(true);
1218 /// assert_eq!(value.into_map(), Err(Error::StructureError("value is not a map".to_string())))
1219 /// ```
1220 pub fn into_map(self) -> Result<ValueMap, Error> {
1221 match self {
1222 Value::Map(map) => Ok(map),
1223 _other => Err(Error::StructureError("value is not a map".to_string())),
1224 }
1225 }
1226
1227 /// If the `Value` is a `Map`, returns a the associated ValueMap which is a `Vec<(Value, Value)>`
1228 /// data as `Ok`.
1229 /// Returns `Err(Error::Structure("reason"))` otherwise.
1230 ///
1231 /// ```
1232 /// # use platform_value::{Error, Value};
1233 /// #
1234 /// let mut value = Value::Map(
1235 /// vec![
1236 /// (Value::Text(String::from("key")), Value::Float(18.)),
1237 /// ]
1238 /// );
1239 /// assert_eq!(value.to_map(), Ok(&vec![(Value::Text(String::from("key")), Value::Float(18.))]));
1240 ///
1241 /// let value = Value::Bool(true);
1242 /// assert_eq!(value.to_map(), Err(Error::StructureError("value is not a map".to_string())))
1243 /// ```
1244 pub fn to_map(&self) -> Result<&ValueMap, Error> {
1245 match self {
1246 Value::Map(map) => Ok(map),
1247 _other => Err(Error::StructureError("value is not a map".to_string())),
1248 }
1249 }
1250
1251 /// If the `Value` is a `Map`, returns the associated ValueMap ref which is a `&Vec<(Value, Value)>`
1252 /// data as `Ok`.
1253 /// Returns `Err(Error::Structure("reason"))` otherwise.
1254 ///
1255 /// ```
1256 /// # use platform_value::{Error, Value};
1257 /// #
1258 /// let mut value = Value::Map(
1259 /// vec![
1260 /// (Value::Text(String::from("key")), Value::Float(18.)),
1261 /// ]
1262 /// );
1263 /// assert_eq!(value.to_map_ref(), Ok(&vec![(Value::Text(String::from("key")), Value::Float(18.))]));
1264 ///
1265 /// let value = Value::Bool(true);
1266 /// assert_eq!(value.to_map_ref(), Err(Error::StructureError("value is not a map".to_string())))
1267 /// ```
1268 pub fn to_map_ref(&self) -> Result<&ValueMap, Error> {
1269 match self {
1270 Value::Map(map) => Ok(map),
1271 _other => Err(Error::StructureError("value is not a map".to_string())),
1272 }
1273 }
1274
1275 /// If the `Value` is a `Map`, returns the associated ValueMap ref which is a `&Vec<(Value, Value)>`
1276 /// data as `Ok`.
1277 /// Returns `Err(Error::Structure("reason"))` otherwise.
1278 ///
1279 /// ```
1280 /// # use platform_value::{Error, Value};
1281 /// #
1282 /// let mut value = Value::Map(
1283 /// vec![
1284 /// (Value::Text(String::from("key")), Value::Float(18.)),
1285 /// ]
1286 /// );
1287 /// assert_eq!(value.as_map_mut_ref(), Ok(&mut vec![(Value::Text(String::from("key")), Value::Float(18.))]));
1288 ///
1289 /// let mut value = Value::Bool(true);
1290 /// assert_eq!(value.as_map_mut_ref(), Err(Error::StructureError("value is not a map".to_string())))
1291 /// ```
1292 pub fn as_map_mut_ref(&mut self) -> Result<&mut ValueMap, Error> {
1293 match self {
1294 Value::Map(map) => Ok(map),
1295 _other => Err(Error::StructureError("value is not a map".to_string())),
1296 }
1297 }
1298
1299 /// Returns the numeric value as `i128` if this is any signed /
1300 /// unsigned integer variant **and** the conversion is loss-less.
1301 #[inline]
1302 fn as_i128_unified(&self) -> Option<i128> {
1303 use Value::*;
1304 match self {
1305 I128(v) => Some(*v),
1306 I64(v) => Some(*v as i128),
1307 I32(v) => Some(*v as i128),
1308 I16(v) => Some(*v as i128),
1309 I8(v) => Some(*v as i128),
1310
1311 U128(v) if *v <= i128::MAX as u128 => Some(*v as i128),
1312 U64(v) => Some(*v as i128),
1313 U32(v) => Some(*v as i128),
1314 U16(v) => Some(*v as i128),
1315 U8(v) => Some(*v as i128),
1316
1317 _ => None,
1318 }
1319 }
1320
1321 /// can determine if there is any very big data in a value
1322 pub fn has_data_larger_than(&self, size: u32) -> Option<(Option<Value>, u32)> {
1323 match self {
1324 Value::U128(_) => {
1325 if size < 16 {
1326 Some((None, 16))
1327 } else {
1328 None
1329 }
1330 }
1331 Value::I128(_) => {
1332 if size < 16 {
1333 Some((None, 16))
1334 } else {
1335 None
1336 }
1337 }
1338 Value::U64(_) => {
1339 if size < 8 {
1340 Some((None, 8))
1341 } else {
1342 None
1343 }
1344 }
1345 Value::I64(_) => {
1346 if size < 8 {
1347 Some((None, 8))
1348 } else {
1349 None
1350 }
1351 }
1352 Value::U32(_) => {
1353 if size < 4 {
1354 Some((None, 4))
1355 } else {
1356 None
1357 }
1358 }
1359 Value::I32(_) => {
1360 if size < 4 {
1361 Some((None, 4))
1362 } else {
1363 None
1364 }
1365 }
1366 Value::U16(_) => {
1367 if size < 2 {
1368 Some((None, 2))
1369 } else {
1370 None
1371 }
1372 }
1373 Value::I16(_) => {
1374 if size < 2 {
1375 Some((None, 2))
1376 } else {
1377 None
1378 }
1379 }
1380 Value::U8(_) => {
1381 if size < 1 {
1382 Some((None, 1))
1383 } else {
1384 None
1385 }
1386 }
1387 Value::I8(_) => {
1388 if size < 1 {
1389 Some((None, 1))
1390 } else {
1391 None
1392 }
1393 }
1394 Value::Bytes(bytes) => {
1395 if (size as usize) < bytes.len() {
1396 Some((None, bytes.len() as u32))
1397 } else {
1398 None
1399 }
1400 }
1401 Value::Bytes20(_) => {
1402 if size < 20 {
1403 Some((None, 20))
1404 } else {
1405 None
1406 }
1407 }
1408 Value::Bytes32(_) => {
1409 if size < 32 {
1410 Some((None, 32))
1411 } else {
1412 None
1413 }
1414 }
1415 Value::Bytes36(_) => {
1416 if size < 36 {
1417 Some((None, 36))
1418 } else {
1419 None
1420 }
1421 }
1422 Value::EnumU8(_) => {
1423 if size < 1 {
1424 Some((None, 1))
1425 } else {
1426 None
1427 }
1428 }
1429 Value::EnumString(strings) => {
1430 let max_len = strings.iter().map(|string| string.len()).max();
1431 if let Some(max) = max_len {
1432 if max > size as usize {
1433 Some((None, max as u32))
1434 } else {
1435 None
1436 }
1437 } else {
1438 None
1439 }
1440 }
1441 Value::Identifier(_) => {
1442 if size < 32 {
1443 Some((None, 32))
1444 } else {
1445 None
1446 }
1447 }
1448 Value::Float(_) => {
1449 if size < 8 {
1450 Some((None, 8))
1451 } else {
1452 None
1453 }
1454 }
1455 Value::Text(string) => {
1456 if string.len() > size as usize {
1457 Some((None, string.len() as u32))
1458 } else {
1459 None
1460 }
1461 }
1462 Value::Bool(_) => {
1463 if size < 1 {
1464 Some((None, 1))
1465 } else {
1466 None
1467 }
1468 }
1469 Value::Null => {
1470 if size < 1 {
1471 Some((None, 1))
1472 } else {
1473 None
1474 }
1475 }
1476 Value::Array(values) => {
1477 for value in values {
1478 if let Some(result) = value.has_data_larger_than(size) {
1479 return Some((Some(value.clone()), result.1));
1480 }
1481 }
1482 None
1483 }
1484 Value::Map(map) => {
1485 for (key, value) in map {
1486 if let Some(result) = value.has_data_larger_than(size) {
1487 return Some((Some(key.clone()), result.1));
1488 }
1489 }
1490 None
1491 }
1492 }
1493 }
1494}
1495
1496macro_rules! implfrom {
1497 ($($v:ident($t:ty)),+ $(,)?) => {
1498 $(
1499 impl From<$t> for Value {
1500 #[inline]
1501 fn from(value: $t) -> Self {
1502 Self::$v(value.into())
1503 }
1504 }
1505 )+
1506 };
1507}
1508
1509macro_rules! impltryinto {
1510 ($($t:ty),+ $(,)?) => {
1511 $(
1512 impl TryFrom<Value> for $t {
1513 type Error = Error;
1514 #[inline]
1515 fn try_from(value: Value) -> Result<Self, Self::Error> {
1516 value.to_integer()
1517 }
1518 }
1519 )+
1520 };
1521}
1522
1523impltryinto! {
1524 u128,
1525 i128,
1526 u64,
1527 i64,
1528 u32,
1529 i32,
1530 u16,
1531 i16,
1532 u8,
1533 i8,
1534}
1535
1536implfrom! {
1537 U128(u128),
1538 I128(i128),
1539 U64(u64),
1540 I64(i64),
1541 U32(u32),
1542 I32(i32),
1543 U16(u16),
1544 I16(i16),
1545 U8(u8),
1546 I8(i8),
1547
1548 Bytes(Vec<u8>),
1549 Bytes(&[u8]),
1550 Bytes32([u8;32]),
1551 Bytes20([u8;20]),
1552 Bytes36([u8;36]),
1553
1554 Float(f64),
1555 Float(f32),
1556
1557 Text(String),
1558 Text(&str),
1559
1560 Bool(bool),
1561
1562 Array(&[Value]),
1563 Array(Vec<Value>),
1564
1565 Map(&[(Value, Value)]),
1566 Map(Vec<(Value, Value)>),
1567}
1568
1569impl<const N: usize> From<[(Value, Value); N]> for Value {
1570 /// Converts a `[(Value, Value); N]` into a `Value`.
1571 ///
1572 /// ```
1573 /// use platform_value::Value;
1574 ///
1575 /// let map1 = Value::from([(Value::from(1), Value::from(2)), (Value::from(3), Value::from(4))]);
1576 /// let map2: Value = [(Value::from(1), Value::from(2)), (Value::from(3), Value::from(4))].into();
1577 /// assert_eq!(map1, map2);
1578 /// ```
1579 fn from(arr: [(Value, Value); N]) -> Self {
1580 if N == 0 {
1581 return Value::Map(vec![]);
1582 }
1583
1584 Value::Map(arr.into_iter().collect())
1585 }
1586}
1587
1588impl<const N: usize> From<[(String, Value); N]> for Value {
1589 /// Converts a `[(String, Value); N]` into a `Value`.
1590 ///
1591 /// ```
1592 /// use platform_value::Value;
1593 ///
1594 /// let map1 = Value::from([("1".to_string(), Value::from(2)), ("3".to_string(), Value::from(4))]);
1595 /// let map2: Value = [("1".to_string(), Value::from(2)), ("3".to_string(), Value::from(4))].into();
1596 /// assert_eq!(map1, map2);
1597 /// ```
1598 fn from(mut arr: [(String, Value); N]) -> Self {
1599 if N == 0 {
1600 return Value::Map(vec![]);
1601 }
1602
1603 // use stable sort to preserve the insertion order.
1604 arr.sort_by(|a, b| a.0.cmp(&b.0));
1605 Value::Map(arr.into_iter().map(|(k, v)| (k.into(), v)).collect())
1606 }
1607}
1608
1609impl<const N: usize> From<[(&str, Value); N]> for Value {
1610 /// Converts a `[($str, Value); N]` into a `Value`.
1611 ///
1612 /// ```
1613 /// use platform_value::Value;
1614 ///
1615 /// let map1 = Value::from([("1", Value::from(2)), ("3", Value::from(4))]);
1616 /// let map2: Value = [("1", Value::from(2)), ("3", Value::from(4))].into();
1617 /// assert_eq!(map1, map2);
1618 /// ```
1619 fn from(mut arr: [(&str, Value); N]) -> Self {
1620 if N == 0 {
1621 return Value::Map(vec![]);
1622 }
1623
1624 // use stable sort to preserve the insertion order.
1625 arr.sort_by(|a, b| a.0.cmp(b.0));
1626 Value::Map(arr.into_iter().map(|(k, v)| (k.into(), v)).collect())
1627 }
1628}
1629
1630impl<T> From<BTreeMap<T, &Value>> for Value
1631where
1632 T: Into<Value>,
1633{
1634 fn from(value: BTreeMap<T, &Value>) -> Self {
1635 Value::Map(
1636 value
1637 .into_iter()
1638 .map(|(key, value)| (key.into(), value.clone()))
1639 .collect(),
1640 )
1641 }
1642}
1643
1644impl From<&BTreeMap<String, Value>> for Value {
1645 fn from(value: &BTreeMap<String, Value>) -> Self {
1646 Value::Map(
1647 value
1648 .iter()
1649 .map(|(key, value)| (key.into(), value.clone()))
1650 .collect(),
1651 )
1652 }
1653}
1654
1655impl<T> From<BTreeMap<T, Value>> for Value
1656where
1657 T: Into<Value>,
1658{
1659 fn from(value: BTreeMap<T, Value>) -> Self {
1660 Value::Map(
1661 value
1662 .into_iter()
1663 .map(|(key, value)| (key.into(), value))
1664 .collect(),
1665 )
1666 }
1667}
1668
1669impl<T> From<BTreeMap<T, Option<T>>> for Value
1670where
1671 T: Into<Value>,
1672{
1673 fn from(value: BTreeMap<T, Option<T>>) -> Self {
1674 Value::Map(
1675 value
1676 .into_iter()
1677 .map(|(key, value)| (key.into(), value.map(|a| a.into()).into()))
1678 .collect(),
1679 )
1680 }
1681}
1682
1683impl From<Option<Value>> for Value {
1684 fn from(value: Option<Value>) -> Self {
1685 match value {
1686 None => Value::Null,
1687 Some(value) => value,
1688 }
1689 }
1690}
1691
1692impl From<&String> for Value {
1693 fn from(value: &String) -> Self {
1694 Value::Text(value.clone())
1695 }
1696}
1697
1698impl From<char> for Value {
1699 #[inline]
1700 fn from(value: char) -> Self {
1701 let mut v = String::with_capacity(1);
1702 v.push(value);
1703 Value::Text(v)
1704 }
1705}
1706
1707impl From<Vec<&str>> for Value {
1708 fn from(value: Vec<&str>) -> Self {
1709 Value::Array(value.into_iter().map(|string| string.into()).collect())
1710 }
1711}
1712
1713impl From<&[&str]> for Value {
1714 fn from(value: &[&str]) -> Self {
1715 Value::Array(
1716 value
1717 .iter()
1718 .map(|string| string.to_owned().into())
1719 .collect(),
1720 )
1721 }
1722}
1723impl TryFrom<Value> for Vec<u8> {
1724 type Error = Error;
1725
1726 fn try_from(value: Value) -> Result<Self, Self::Error> {
1727 value.into_bytes()
1728 }
1729}
1730
1731impl TryFrom<Value> for String {
1732 type Error = Error;
1733
1734 fn try_from(value: Value) -> Result<Self, Self::Error> {
1735 value.into_text()
1736 }
1737}