1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
// License: see LICENSE file at root directory of `master` branch //! # Value mod formatter; use { alloc::{ collections::BTreeMap, string::{String, ToString}, vec::Vec, }, core::{ convert::TryFrom, iter::FromIterator, }, crate::{Error, Number}, }; #[cfg(feature="std")] use { core::str::FromStr, std::io::Write, crate::IoResult, self::formatter::*, }; /// # Array /// /// ## Shortcuts /// /// [`array()`], [`array_with_capacity()`], [`push()`] /// /// [`array()`]: fn.array.html /// [`array_with_capacity()`]: fn.array_with_capacity.html /// [`push()`]: fn.push.html pub type Array = Vec<Value>; /// # Object /// /// ## Shortcuts /// /// [`object()`], [`insert()`] /// /// [`object()`]: fn.object.html /// [`insert()`]: fn.insert.html pub type Object = BTreeMap<String, Value>; /// # A value /// /// ## Formatting /// /// ### Formatting as JSON string /// /// - To format as compacted JSON string, you can use [`format()`] or [`format_as_bytes()`]. /// - To format as a nice JSON string, you can use [`format_nicely()`]. /// /// ### Writing as JSON string to [`Write`][std::io/Write] /// /// Can be done via [`write()`] or [`write_nicely()`]. /// /// ## Converting Rust types to `Value` and vice versa /// /// There are some implementations: /// /// ```ignore /// impl From<...> for Value; /// impl TryFrom<&Value> for ...; /// impl TryFrom<Value> for ...; /// ``` /// /// About [`TryFrom`][core::convert/TryFrom] implementations: /// /// - For primitives, since they're cheap, they have implementations on either a borrowed or an owned value. /// - For collections such as [`String`], [`Object`], [`Array`]..., they only have implementations on an owned value. So data is moved, not /// copied. /// /// ## Shortcuts /// /// A root JSON value can be either an object or an array. For your convenience, there are some shortcuts, like below examples. /// /// - Object: /// /// ``` /// # #[cfg(feature="std")] /// # fn test() -> sj::IoResult<()> { /// use core::convert::TryFrom; /// /// let mut object = sj::object(); /// object.insert("first", true)?; /// object.insert("second", <Option<u8>>::None)?; /// object.insert(String::from("third"), "...")?; /// /// assert!(bool::try_from(object.by(&["first"])?)?); /// assert!(object.take_by(&["second"])?.try_into_or(true)?); /// assert_eq!(object.format()?, r#"{"first":true,"third":"..."}"#); /// # Ok(()) } /// # #[cfg(feature="std")] /// # test().unwrap(); /// # Ok::<_, sj::Error>(()) /// ``` /// /// - Array: /// /// ``` /// # #[cfg(feature="std")] /// # fn test() -> sj::IoResult<()> { /// use core::convert::TryFrom; /// /// let mut array = sj::array(); /// array.push(false)?; /// array.push("a string")?; /// array.push(Some(sj::object()))?; /// /// assert!(bool::try_from(array.at(&[0])?)? == false); /// assert_eq!(array.format()?, r#"[false,"a string",{}]"#); /// # Ok(()) } /// # #[cfg(feature="std")] /// # test().unwrap(); /// # Ok::<_, sj::Error>(()) /// ``` /// /// [core::convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html /// [std::io/Write]: https://doc.rust-lang.org/std/io/trait.Write.html /// /// [`Array`]: #variant.Array /// [`Object`]: #variant.Object /// [`String`]: #variant.String /// [`format()`]: #method.format /// [`format_nicely()`]: #method.format_nicely /// [`format_as_bytes()`]: #method.format_as_bytes /// [`write()`]: #method.write /// [`write_nicely()`]: #method.write_nicely #[derive(Debug, Clone)] pub enum Value { /// ### Shortcuts /// /// <small>[`as_str()`]</small> /// /// [`as_str()`]: #method.as_str String(String), /// ### Shortcuts /// /// <small>[`TryFrom`][core::convert/TryFrom]</small> /// /// [core::convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html Number(Number), /// ### Shortcuts /// /// <small>[`TryFrom`][core::convert/TryFrom]</small> /// /// [core::convert/TryFrom]: https://doc.rust-lang.org/core/convert/trait.TryFrom.html Boolean(bool), /// ### Shortcuts /// /// <small>[`is_null()`], [`try_into_or()`], [`try_into_or_else()`], [`try_ref_into_or()`], [`try_ref_into_or_else()`]...</small> /// /// [`is_null()`]: #method.is_null /// [`try_into_or()`]: #method.try_into_or /// [`try_into_or_else()`]: #method.try_into_or_else /// [`try_ref_into_or()`]: #method.try_ref_into_or /// [`try_ref_into_or_else()`]: #method.try_ref_into_or_else Null, /// ### Shortcuts /// /// <small>[`insert()`], [`by()`], [`maybe_by()`], [`mut_by()`], [`maybe_mut_by()`], [`take_by()`], [`maybe_take_by()`], [`as_object()`], /// [`as_mut_object()`]...</small> /// /// [`insert()`]: #method.insert /// [`by()`]: #method.by /// [`maybe_by()`]: #method.maybe_by /// [`mut_by()`]: #method.mut_by /// [`maybe_mut_by()`]: #method.maybe_mut_by /// [`take_by()`]: #method.take_by /// [`maybe_take_by()`]: #method.maybe_take_by /// [`as_object()`]: #method.as_object /// [`as_mut_object()`]: #method.as_mut_object Object(Object), /// ### Shortcuts /// /// <small>[`push()`], [`at()`], [`mut_at()`], [`take_at()`], [`as_array()`], [`as_mut_array()`]...</small> /// /// [`push()`]: #method.push /// [`at()`]: #method.at /// [`mut_at()`]: #method.mut_at /// [`take_at()`]: #method.take_at /// [`as_array()`]: #method.as_array /// [`as_mut_array()`]: #method.as_mut_array Array(Array), } /// # Helper macro for Value::at()/mut_at() macro_rules! at_or_mut_at { ($self: ident, $indexes: ident, $code: tt) => {{ let mut value = Some($self); for (nth, idx) in $indexes.iter().enumerate() { match value { Some(Value::Array(array)) => { value = array.$code(*idx); if nth + 1 == $indexes.len() { return value.ok_or_else(|| Error::from(__!("Indexes are invalid: {:?}", $indexes))); } }, Some(_) => return Err(Error::from(match nth { 0 => __!("Value is not an Array"), _ => __!("Value at {:?} is not an Array", &$indexes[..nth]), })), None => return Err(Error::from(__!("There is no value at {:?}", &$indexes[..nth]))), }; } Err(Error::from(__!("Indexes must not be empty"))) }}} /// # Helper macro for Value::maybe_by()/maybe_mut_by() macro_rules! maybe_by_or_mut_by { ($self: ident, $keys: ident, $code: tt) => {{ if $keys.is_empty() { return Err(Error::from(__!("Keys must not be empty"))); } let mut value = Some($self); for (nth, key) in $keys.iter().enumerate() { match value { Some(Value::Object(object)) => value = object.$code(*key), Some(_) => return Err(Error::from(match nth { 0 => __!("Value is not an Object"), _ => __!("Value at {:?} is not an Object", &$keys[..nth]), })), None => return Err(Error::from(__!("There is no value at {:?}", &$keys[..nth]))), }; } Ok(value) }}} impl Value { /// # Formats this value as a compacted JSON string #[cfg(feature="std")] pub fn format_as_bytes(&self) -> IoResult<Vec<u8>> { let mut buf = Vec::with_capacity(formatter::estimate_format_size(self, None, None)); self.write(&mut buf)?; buf.flush().map(|()| buf) } /// # Nicely formats this value as JSON string /// /// If you don't provide tab size, default (`4`) will be used. #[cfg(feature="std")] pub fn format_nicely_as_bytes(&self, tab: Option<u8>) -> IoResult<Vec<u8>> { let mut buf = Vec::with_capacity(formatter::estimate_format_size(self, Some(tab.unwrap_or(formatter::DEFAULT_TAB_WIDTH)), None)); self.write_nicely(tab, &mut buf)?; buf.flush().map(|()| buf) } /// # Formats this value as a compacted JSON string #[cfg(feature="std")] pub fn format(&self) -> IoResult<String> { #[allow(unsafe_code)] Ok(unsafe { String::from_utf8_unchecked(self.format_as_bytes()?) }) } /// # Nicely formats this value as JSON string /// /// If you don't provide tab size, default (`4`) will be used. #[cfg(feature="std")] pub fn format_nicely(&self, tab: Option<u8>) -> IoResult<String> { #[allow(unsafe_code)] Ok(unsafe { String::from_utf8_unchecked(self.format_nicely_as_bytes(tab)?) }) } /// # Writes this value as compacted JSON string to a stream /// /// ## Notes /// /// - The stream is used as-is. For better performance, you _should_ wrap your stream inside a [`BufWriter`][std::io/BufWriter]. /// - This function does **not** flush the stream when done. /// /// [std::io/BufWriter]: https://doc.rust-lang.org/std/io/struct.BufWriter.html #[cfg(feature="std")] pub fn write<W>(&self, stream: &mut W) -> IoResult<()> where W: Write { Formatter::new(None).format(self, stream) } /// # Writes this value as nicely formatted JSON string to a stream /// /// ## Notes /// /// - If you don't provide tab size, default (`4`) will be used. /// - The stream is used as-is. For better performance, you _should_ wrap your stream inside a [`BufWriter`][std::io/BufWriter]. /// - This function does **not** flush the stream when done. /// /// [std::io/BufWriter]: https://doc.rust-lang.org/std/io/struct.BufWriter.html #[cfg(feature="std")] pub fn write_nicely<W>(&self, tab: Option<u8>, stream: &mut W) -> IoResult<()> where W: Write { let tab = match tab { Some(_) => tab, None => Some(formatter::DEFAULT_TAB_WIDTH), }; Formatter::new(tab).format(self, stream) } /// # Checks to see if this value is [`Null`][Null] /// /// [Null]: #variant.Null pub fn is_null(&self) -> bool { match self { Value::Null => true, _ => false, } } /// # Tries to convert this value into something /// /// If this is [`Null`][Null], returns `default`. /// /// If your default value would be a result of a function call, you should use [`try_into_or_else()`][try_into_or_else()]. /// /// ## Examples /// /// ``` /// # #[cfg(feature="std")] { /// let mut value = sj::parse_bytes("[null]")?; /// assert!(value.take_at(&[0])?.try_into_or(true)?); /// # } /// # Ok::<_, sj::Error>(()) /// ``` /// /// [Null]: #variant.Null /// [try_into_or_else()]: #method.try_into_or_else pub fn try_into_or<T>(self, default: T) -> crate::Result<T> where T: TryFrom<Self, Error=Error> { match self { Value::Null => Ok(default), _ => T::try_from(self), } } /// # Tries to convert this value into something /// /// If this is [`Null`][Null], calls `default()` and returns its result. /// /// ## See also /// /// [`try_into_or()`][try_into_or()] /// /// [Null]: #variant.Null /// [try_into_or()]: #method.try_into_or pub fn try_into_or_else<T, F>(self, default: F) -> crate::Result<T> where T: TryFrom<Self, Error=Error>, F: FnOnce() -> T { match self { Value::Null => Ok(default()), _ => T::try_from(self), } } /// # Tries to convert a reference of this value into something /// /// If this is [`Null`][Null], returns `default`. /// /// If your default value would be a result of a function call, you should use [`try_ref_into_or_else()`][try_ref_into_or_else()]. /// /// ## Examples /// /// ``` /// # #[cfg(feature="std")] { /// let value = sj::parse_bytes("[null]")?; /// assert_eq!(value.at(&[0])?.try_ref_into_or(0)?, 0); /// # } /// # Ok::<_, sj::Error>(()) /// ``` /// /// [Null]: #variant.Null /// [try_ref_into_or_else()]: #method.try_ref_into_or_else pub fn try_ref_into_or<'a, T>(&'a self, default: T) -> crate::Result<T> where T: TryFrom<&'a Self, Error=Error> { match self { Value::Null => Ok(default), _ => T::try_from(self), } } /// # Tries to convert a reference of this value into something /// /// If this is [`Null`][Null], calls `default()` and returns its result. /// /// ## See also /// /// [`try_ref_into_or()`][try_ref_into_or()] /// /// [Null]: #variant.Null /// [try_ref_into_or()]: #method.try_ref_into_or pub fn try_ref_into_or_else<'a, T, F>(&'a self, default: F) -> crate::Result<T> where T: TryFrom<&'a Self, Error=Error>, F: FnOnce() -> T { match self { Value::Null => Ok(default()), _ => T::try_from(self), } } /// # If the value is a string, returns an immutable reference of it /// /// Returns an error if the value is not a string. pub fn as_str(&self) -> crate::Result<&str> { match self { Value::String(s) => Ok(s), _ => Err(Error::from(__!("Value is not a String"))), } } /// # If the value is an array, pushes new item into it /// /// Returns an error if the value is not an array. pub fn push<T>(&mut self, value: T) -> crate::Result<()> where T: Into<Self> { match self { Value::Array(array) => Ok(push(array, value)), _ => Err(Error::from(__!("Value is not an Array"))), } } /// # Gets an immutable item from this array and its sub arrays /// /// The function returns an error on one of these conditions: /// /// - Indexes are empty or invalid. /// - The value or any of its sub items is not an array. /// /// ## Examples /// /// ``` /// let mut array = sj::array(); /// array.push("first")?; /// array.push(vec![false.into(), "second".into()])?; /// /// assert_eq!(array.at(&[0])?.as_str()?, "first"); /// assert_eq!(array.at(&[1, 1])?.as_str()?, "second"); /// /// assert!(array.at(&[]).is_err()); /// assert!(array.at(&[0, 1]).is_err()); /// assert!(array.at(&[1, 2]).is_err()); /// assert!(array.at(&[1, 0, 0]).is_err()); /// assert!(array.at(&[1, 1, 2]).is_err()); /// /// # Ok::<_, sj::Error>(()) /// ``` pub fn at(&self, indexes: &[usize]) -> crate::Result<&Self> { at_or_mut_at!(self, indexes, get) } /// # Gets a mutable item from this array and its sub arrays /// /// The function returns an error on one of these conditions: /// /// - Indexes are empty or invalid. /// - The value or any of its sub items is not an array. /// /// ## See also /// /// [`at()`][at()] /// /// [at()]: #method.at pub fn mut_at(&mut self, indexes: &[usize]) -> crate::Result<&mut Self> { at_or_mut_at!(self, indexes, get_mut) } /// # Takes an item from this array and its sub arrays /// /// The function returns an error on one of these conditions: /// /// - Indexes are empty or invalid. /// - The value or any of its sub items is not an array. /// /// ## Examples /// /// ``` /// let mut array = sj::array(); /// array.push("earth")?; /// array.push(vec![false.into(), "moon".into()])?; /// /// assert_eq!(array.take_at(&[0])?.as_str()?, "earth"); /// assert_eq!(array.take_at(&[0, 1])?.as_str()?, "moon"); /// /// assert!(array.take_at(&[]).is_err()); /// assert!(array.take_at(&[0, 1]).is_err()); /// /// # Ok::<_, sj::Error>(()) /// ``` pub fn take_at(&mut self, indexes: &[usize]) -> crate::Result<Self> { let mut value = Some(self); for (nth, idx) in indexes.iter().enumerate() { match value { Some(Value::Array(array)) => match nth + 1 == indexes.len() { true => return match idx >= &0 && idx < &array.len() { true => Ok(array.remove(*idx)), false => Err(Error::from(__!("Invalid indexes: {:?}", indexes))), }, false => value = array.get_mut(*idx), }, Some(_) => return Err(Error::from(match nth { 0 => __!("Value is not an Array"), _ => __!("Value at {:?} is not an Array", &indexes[..nth]), })), None => return Err(Error::from(__!("There is no value at {:?}", &indexes[..nth]))), }; } Err(Error::from(__!("Indexes must not be empty"))) } /// # If the value is an array, returns an immutable reference of it /// /// Returns an error if the value is not an array. pub fn as_array(&self) -> crate::Result<&Array> { match self { Value::Array(array) => Ok(array), _ => Err(Error::from(__!("Value is not an Array"))), } } /// # If the value is an array, returns a mutable reference of it /// /// Returns an error if the value is not an array. pub fn as_mut_array(&mut self) -> crate::Result<&mut Array> { match self { Value::Array(array) => Ok(array), _ => Err(Error::from(__!("Value is not an Array"))), } } /// # If the value is an object, inserts new item into it /// /// On success, returns previous value (if it existed). /// /// Returns an error if the value is not an object. pub fn insert<S, T>(&mut self, key: S, value: T) -> crate::Result<Option<Self>> where S: Into<String>, T: Into<Self> { match self { Value::Object(object) => Ok(insert(object, key, value)), _ => Err(Error::from(__!("Value is not an Object"))), } } /// # Gets an immutable item from this object and its sub objects /// /// The function returns an error on one of these conditions: /// /// - Keys are empty. /// - The value or any of its sub items is not an object. /// /// ## Examples /// /// ``` /// use core::convert::TryFrom; /// /// let mut object = sj::object(); /// object.insert("first", true)?; /// object.insert("second", { /// let mut map = sj::Object::new(); /// sj::insert(&mut map, "zero", 0); /// map /// })?; /// /// assert_eq!(bool::try_from(object.by(&["first"])?)?, true); /// assert_eq!(u8::try_from(object.by(&["second", "zero"])?)?, 0); /// /// assert!(object.by(&["something"]).is_err()); /// assert!(object.maybe_by(&["something"])?.is_none()); /// /// assert!(object.by(&[]).is_err()); /// assert!(object.by(&["first", "last"]).is_err()); /// assert!(object.by(&["second", "third", "fourth"]).is_err()); /// /// # Ok::<_, sj::Error>(()) /// ``` pub fn by(&self, keys: &[&str]) -> crate::Result<&Self> { self.maybe_by(keys)?.ok_or_else(|| Error::from(__!("There is no value at: {:?}", keys))) } /// # Gets an optional immutable item from this object and its sub objects /// /// The function returns an error on one of these conditions: /// /// - Keys are empty. /// - The value or any of its sub items is not an object. pub fn maybe_by(&self, keys: &[&str]) -> crate::Result<Option<&Self>> { maybe_by_or_mut_by!(self, keys, get) } /// # Gets a mutable item from this object and its sub objects /// /// The function returns an error on one of these conditions: /// /// - Keys are empty. /// - The value or any of its sub items is not an object. pub fn mut_by(&mut self, keys: &[&str]) -> crate::Result<&mut Self> { self.maybe_mut_by(keys)?.ok_or_else(|| Error::from(__!("There is no value at: {:?}", keys))) } /// # Gets an optional mutable item from this object and its sub objects /// /// The function returns an error on one of these conditions: /// /// - Keys are empty. /// - The value or any of its sub items is not an object. pub fn maybe_mut_by(&mut self, keys: &[&str]) -> crate::Result<Option<&mut Self>> { maybe_by_or_mut_by!(self, keys, get_mut) } /// # Takes an item from this object and its sub objects /// /// The function returns an error on one of these conditions: /// /// - Keys are empty. /// - The value or any of its sub items is not an object. /// /// ## Examples /// /// ``` /// let mut object = sj::object(); /// object.insert("earth", "moon")?; /// object.insert("solar-system", { /// let mut map = sj::Object::new(); /// sj::insert(&mut map, "sun", "earth"); /// map /// })?; /// /// assert_eq!(object.take_by(&["earth"])?.as_str()?, "moon"); /// assert_eq!(object.take_by(&["solar-system", "sun"])?.as_str()?, "earth"); /// /// assert!(object.take_by(&["milky-way"]).is_err()); /// assert!(object.maybe_take_by(&["milky-way"])?.is_none()); /// assert!(object.maybe_take_by(&["solar-system", "mars"])?.is_none()); /// /// assert!(object.take_by(&[]).is_err()); /// assert!(object.take_by(&["jupiter", "venus"]).is_err()); /// /// # Ok::<_, sj::Error>(()) /// ``` pub fn take_by(&mut self, keys: &[&str]) -> crate::Result<Self> { self.maybe_take_by(keys)?.ok_or_else(|| Error::from(__!("There is no value at: {:?}", keys))) } /// # Takes an optional item from this object and its sub objects /// /// The function returns an error on one of these conditions: /// /// - Keys are empty. /// - The value or any of its sub items is not an object. pub fn maybe_take_by(&mut self, keys: &[&str]) -> crate::Result<Option<Self>> { let mut value = Some(self); for (nth, key) in keys.iter().enumerate() { match value { Some(Value::Object(object)) => match nth + 1 == keys.len() { true => return Ok(object.remove(*key)), false => value = object.get_mut(*key), }, Some(_) => return Err(Error::from(match nth { 0 => __!("Value is not an Object"), _ => __!("Value at {:?} is not an Object", &keys[..nth]), })), None => return Err(Error::from(__!("There is no value at {:?}", &keys[..nth]))), }; } Err(Error::from(__!("Keys must not be empty"))) } /// # If the value is an object, returns an immutable reference of it /// /// Returns an error if the value is not an object. pub fn as_object(&self) -> crate::Result<&Object> { match self { Value::Object(object) => Ok(object), _ => Err(Error::from(__!("Value is not an Object"))), } } /// # If the value is an object, returns a mutable reference of it /// /// Returns an error if the value is not an object. pub fn as_mut_object(&mut self) -> crate::Result<&mut Object> { match self { Value::Object(object) => Ok(object), _ => Err(Error::from(__!("Value is not an Object"))), } } } impl From<String> for Value { fn from(s: String) -> Self { Value::String(s) } } impl From<&str> for Value { fn from(s: &str) -> Self { Value::String(s.to_string()) } } impl TryFrom<Value> for String { type Error = Error; fn try_from(value: Value) -> Result<Self, Self::Error> { match value { Value::String(s) => Ok(s), _ => Err(Error::from(__!("Value is not a String"))), } } } impl From<Number> for Value { fn from(n: Number) -> Self { Value::Number(n) } } impl From<bool> for Value { fn from(b: bool) -> Self { Value::Boolean(b) } } impl TryFrom<&Value> for bool { type Error = Error; fn try_from(value: &Value) -> Result<Self, Self::Error> { match value { Value::Boolean(b) => Ok(*b), _ => Err(Error::from(__!("Value is not a Boolean"))), } } } impl TryFrom<Value> for bool { type Error = Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Self::try_from(&value) } } impl From<Object> for Value { fn from(map: Object) -> Self { Value::Object(map) } } impl FromIterator<(String, Value)> for Value { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=(String, Value)> { Value::Object(iter.into_iter().collect()) } } impl TryFrom<Value> for Object { type Error = Error; fn try_from(value: Value) -> Result<Self, Self::Error> { match value { Value::Object(object) => Ok(object), _ => Err(Error::from(__!("Value is not an Object"))), } } } impl From<Array> for Value { fn from(values: Array) -> Self { Value::Array(values) } } impl FromIterator<Value> for Value { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=Value> { Value::Array(iter.into_iter().collect()) } } impl TryFrom<Value> for Array { type Error = Error; fn try_from(value: Value) -> Result<Self, Self::Error> { match value { Value::Array(array) => Ok(array), _ => Err(Error::from(__!("Value is not an Array"))), } } } impl<T> From<Option<T>> for Value where T: Into<Value> { fn from(t: Option<T>) -> Self { match t { Some(t) => t.into(), None => Value::Null, } } } #[cfg(feature="std")] impl FromStr for Value { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { crate::parse_bytes(s) } } macro_rules! impl_try_from_value_for_primitives { ($($ty: ty,)+) => { $( impl TryFrom<&Value> for $ty { type Error = Error; fn try_from(value: &Value) -> Result<Self, Self::Error> { match value { Value::Number(n) => Self::try_from(n), _ => Err(Error::from(__!("Value is not a Number"))), } } } impl TryFrom<Value> for $ty { type Error = Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Self::try_from(&value) } } )+ }} impl_try_from_value_for_primitives! { i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, } #[cfg(feature="std")] impl TryFrom<Vec<u8>> for Value { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { crate::parse_bytes(bytes) } } /// # Makes new object pub fn object() -> Value { Value::Object(Object::new()) } /// # Makes new array pub fn array() -> Value { Value::Array(Vec::new()) } /// # Makes new array with capacity pub fn array_with_capacity(capacity: usize) -> Value { Value::Array(Vec::with_capacity(capacity)) } /// # Pushes new item into an array pub fn push<T>(array: &mut Array, value: T) where T: Into<Value> { array.push(value.into()); } /// # Inserts new item into an object /// /// Returns previous value (if it existed). pub fn insert<S, T>(object: &mut Object, key: S, value: T) -> Option<Value> where S: Into<String>, T: Into<Value> { object.insert(key.into(), value.into()) }