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)); 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#[derive(Debug, Clone)]
353pub enum Value {
354 SimpleValue(SimpleValue),
361
362 Unsigned(u64),
364 Negative(u64),
367
368 Float(Float),
370
371 ByteString(Vec<u8>),
373 TextString(String),
375
376 Array(Vec<Value>),
378 Map(BTreeMap<Value, Value>),
380
381 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 #[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 pub fn decode(mut bytes: &[u8]) -> Result<Self> {
467 Self::read_from(&mut bytes)
468 }
469
470 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 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 _ => (), }
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 #[must_use]
681 pub const fn null() -> Self {
682 Self::SimpleValue(SimpleValue::NULL)
683 }
684
685 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 pub fn integer(value: impl Into<Integer>) -> Self {
701 value.into().into_value()
702 }
703
704 pub fn float(value: impl Into<Float>) -> Self {
707 Self::Float(value.into())
708 }
709
710 pub fn array(array: impl Into<Array>) -> Self {
712 Self::Array(array.into().0)
713 }
714
715 pub fn map(map: impl Into<Map>) -> Self {
717 Self::Map(map.into().0)
718 }
719
720 pub fn tag(number: u64, content: impl Into<Value>) -> Self {
728 Self::Tag(number, Box::new(content.into()))
729 }
730
731 #[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 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 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 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 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 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 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 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 #[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 #[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 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 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 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 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 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 #[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 #[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 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 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 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 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 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 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 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 pub fn into_string(self) -> Result<String> {
1011 match self {
1012 Self::TextString(s) => Ok(s),
1013 _ => Err(Error::IncompatibleType),
1014 }
1015 }
1016
1017 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 #[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
1164impl 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
1256impl 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
1276impl 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
1302impl 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
1334impl 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
1354impl 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
1374impl 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}