1use std::{error::Error, fmt::Debug, sync::LazyLock};
2
3use thiserror::Error;
4
5use crate::{
6 BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
7 schema::{
8 SchemaShape, ShapeId, ShapeType,
9 default::{Number, Value},
10 prelude::*,
11 },
12 smithy,
13};
14
15pub trait Document: SchemaShape + Send + Sync {
175 #[must_use]
183 fn discriminator(&self) -> Option<&ShapeId>;
184
185 #[must_use]
201 fn get_type(&self) -> Option<&ShapeType>;
202
203 #[must_use]
207 fn size(&self) -> usize;
208
209 #[must_use]
216 fn as_blob(&self) -> Option<&ByteBuffer>;
217
218 #[must_use]
223 fn as_bool(&self) -> Option<bool>;
224
225 #[must_use]
230 fn as_string(&self) -> Option<&str>;
231
232 #[must_use]
237 fn as_timestamp(&self) -> Option<&Instant>;
238
239 #[must_use]
244 fn as_byte(&self) -> Option<i8>;
245
246 #[must_use]
251 fn as_short(&self) -> Option<i16>;
252
253 #[must_use]
258 fn as_integer(&self) -> Option<i32>;
259
260 #[must_use]
265 fn as_long(&self) -> Option<i64>;
266
267 #[must_use]
272 fn as_float(&self) -> Option<f32>;
273
274 #[must_use]
279 fn as_double(&self) -> Option<f64>;
280
281 #[must_use]
286 fn as_big_integer(&self) -> Option<&BigInt>;
287
288 #[must_use]
293 fn as_big_decimal(&self) -> Option<&BigDecimal>;
294
295 #[must_use]
299 fn as_list(&self) -> Option<&Vec<Box<dyn Document>>>;
300
301 #[must_use]
305 fn as_map(&self) -> Option<&IndexMap<String, Box<dyn Document>>>;
306
307 #[must_use]
309 fn is_null(&self) -> bool;
310
311 fn into_blob(self: Box<Self>) -> Result<ByteBuffer, DocumentError>;
319
320 fn into_bool(self: Box<Self>) -> Result<bool, DocumentError>;
326
327 fn into_string(self: Box<Self>) -> Result<String, DocumentError>;
333
334 fn into_timestamp(self: Box<Self>) -> Result<Instant, DocumentError>;
340
341 fn into_byte(self: Box<Self>) -> Result<i8, DocumentError>;
347
348 fn into_short(self: Box<Self>) -> Result<i16, DocumentError>;
354
355 fn into_integer(self: Box<Self>) -> Result<i32, DocumentError>;
361
362 fn into_long(self: Box<Self>) -> Result<i64, DocumentError>;
368
369 fn into_float(self: Box<Self>) -> Result<f32, DocumentError>;
375
376 fn into_double(self: Box<Self>) -> Result<f64, DocumentError>;
382
383 fn into_big_integer(self: Box<Self>) -> Result<BigInt, DocumentError>;
389
390 fn into_big_decimal(self: Box<Self>) -> Result<BigDecimal, DocumentError>;
396
397 fn into_list(self: Box<Self>) -> Result<Vec<Box<dyn Document>>, DocumentError>;
402
403 fn into_map(self: Box<Self>) -> Result<IndexMap<String, Box<dyn Document>>, DocumentError>;
408
409 fn box_clone(&self) -> Box<dyn Document>;
411}
412
413impl PartialEq for dyn Document {
418 fn eq(&self, other: &Self) -> bool {
419 if self.schema() != other.schema() {
420 return false;
421 }
422 if self.discriminator() != other.discriminator() {
423 return false;
424 }
425 match (self.get_type(), other.get_type()) {
428 (Some(ShapeType::String), Some(ShapeType::String)) => {
429 self.as_string() == other.as_string()
430 }
431 (Some(ShapeType::Blob), Some(ShapeType::Blob)) => self.as_blob() == other.as_blob(),
432 (Some(ShapeType::Boolean), Some(ShapeType::Boolean)) => {
433 self.as_bool() == other.as_bool()
434 }
435 (Some(ShapeType::Timestamp), Some(ShapeType::Timestamp)) => {
436 self.as_timestamp() == other.as_timestamp()
437 }
438 (Some(ShapeType::Byte), Some(ShapeType::Byte)) => self.as_byte() == other.as_byte(),
439 (Some(ShapeType::Short), Some(ShapeType::Short)) => self.as_short() == other.as_short(),
440 (Some(ShapeType::Integer), Some(ShapeType::Integer)) => {
441 self.as_integer() == other.as_integer()
442 }
443 (Some(ShapeType::Long), Some(ShapeType::Long)) => self.as_long() == other.as_long(),
444 (Some(ShapeType::Float), Some(ShapeType::Float)) => self.as_float() == other.as_float(),
445 (Some(ShapeType::Double), Some(ShapeType::Double)) => {
446 self.as_double() == other.as_double()
447 }
448 (Some(ShapeType::BigInteger), Some(ShapeType::BigInteger)) => {
449 self.as_big_integer() == other.as_big_integer()
450 }
451 (Some(ShapeType::BigDecimal), Some(ShapeType::BigDecimal)) => {
452 self.as_big_decimal() == other.as_big_decimal()
453 }
454 (Some(ShapeType::List), Some(ShapeType::List)) => self.as_list() == other.as_list(),
455 (Some(ShapeType::Map), Some(ShapeType::Map)) => self.as_map() == other.as_map(),
456 (None, None) => true,
457 _ => false,
458 }
459 }
460}
461
462impl Clone for Box<dyn Document> {
463 #[inline]
464 fn clone(&self) -> Self {
465 self.box_clone()
466 }
467}
468
469#[derive(Error, Debug)]
475pub enum DocumentError {
476 #[error("Failed to convert document to type {0}")]
478 DocumentSerialization(String),
479 #[error("Failed to convert document to type {0}")]
481 DocumentConversion(String),
482 #[error("Encountered unknown error")]
484 Unknown(#[from] Box<dyn Error>),
485 #[error("Encountered error: {0}")]
487 CustomError(String),
488}
489
490impl crate::serde::de::Error for DocumentError {
491 fn custom<T: std::fmt::Display>(msg: T) -> Self {
492 DocumentError::CustomError(msg.to_string())
493 }
494}
495
496impl TryFrom<Box<dyn Document>> for ByteBuffer {
501 type Error = DocumentError;
502
503 #[inline]
504 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
505 value.into_blob()
506 }
507}
508
509impl TryFrom<Box<dyn Document>> for bool {
510 type Error = DocumentError;
511
512 #[inline]
513 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
514 value.into_bool()
515 }
516}
517
518impl TryFrom<Box<dyn Document>> for String {
519 type Error = DocumentError;
520
521 #[inline]
522 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
523 value.into_string()
524 }
525}
526
527impl TryFrom<Box<dyn Document>> for Instant {
528 type Error = DocumentError;
529
530 #[inline]
531 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
532 value.into_timestamp()
533 }
534}
535
536impl TryFrom<Box<dyn Document>> for i8 {
537 type Error = DocumentError;
538
539 #[inline]
540 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
541 value.into_byte()
542 }
543}
544
545impl TryFrom<Box<dyn Document>> for i16 {
546 type Error = DocumentError;
547
548 #[inline]
549 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
550 value.into_short()
551 }
552}
553
554impl TryFrom<Box<dyn Document>> for i32 {
555 type Error = DocumentError;
556
557 #[inline]
558 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
559 value.into_integer()
560 }
561}
562
563impl TryFrom<Box<dyn Document>> for i64 {
564 type Error = DocumentError;
565
566 #[inline]
567 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
568 value.into_long()
569 }
570}
571
572impl TryFrom<Box<dyn Document>> for f32 {
573 type Error = DocumentError;
574
575 #[inline]
576 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
577 value.into_float()
578 }
579}
580
581impl TryFrom<Box<dyn Document>> for f64 {
582 type Error = DocumentError;
583
584 #[inline]
585 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
586 value.into_double()
587 }
588}
589
590impl TryFrom<Box<dyn Document>> for BigInt {
591 type Error = DocumentError;
592
593 #[inline]
594 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
595 value.into_big_integer()
596 }
597}
598
599impl TryFrom<Box<dyn Document>> for BigDecimal {
600 type Error = DocumentError;
601
602 #[inline]
603 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
604 value.into_big_decimal()
605 }
606}
607
608impl TryFrom<Box<dyn Document>> for Vec<Box<dyn Document>> {
609 type Error = DocumentError;
610
611 #[inline]
612 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
613 value.into_list()
614 }
615}
616
617impl TryFrom<Box<dyn Document>> for IndexMap<String, Box<dyn Document>> {
618 type Error = DocumentError;
619
620 #[inline]
621 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
622 value.into_map()
623 }
624}
625
626impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>> for Vec<T> {
627 type Error = DocumentError;
628
629 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
630 let vec = value.into_list()?;
631 let mut result: Vec<T> = Vec::new();
632 for doc in vec {
633 match T::try_from(doc.clone()) {
634 Ok(val) => result.push(val),
635 Err(e) => return Err(e),
636 }
637 }
638 Ok(result)
639 }
640}
641
642impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>>
643 for IndexMap<String, T>
644{
645 type Error = DocumentError;
646
647 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
648 let map = value.into_map()?;
649 let mut result: IndexMap<String, T> = IndexMap::new();
650 for (key, val) in map {
651 let _ = match T::try_from(val.clone()) {
652 Ok(val) => result.insert(key.clone(), val),
653 Err(e) => return Err(e),
654 };
655 }
656 Ok(result)
657 }
658}
659
660impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>>
661 for Option<T>
662{
663 type Error = DocumentError;
664
665 fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
666 if value.is_null() {
667 return Ok(None);
668 }
669 Ok(Some(value.try_into()?))
670 }
671}
672
673pub(crate) mod default {
678 use bigdecimal::ToPrimitive;
679
680 use crate::{
681 BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
682 schema::{DocumentError, SchemaRef, SchemaShape, ShapeId, ShapeType},
683 };
684
685 #[derive(Clone, PartialEq, Debug)]
686 pub struct Document {
687 pub schema: SchemaRef,
688 pub value: Value,
689 pub discriminator: Option<ShapeId>,
690 }
691
692 impl SchemaShape for Document {
693 fn schema(&self) -> &SchemaRef {
694 &self.schema
695 }
696 }
697
698 #[derive(Clone, PartialEq, Debug)]
699 pub enum Value {
700 Null,
701 Number(Number),
702 Boolean(bool),
703 Blob(ByteBuffer),
704 String(String),
705 Timestamp(Instant),
706 List(Vec<Box<dyn super::Document>>),
707 Map(IndexMap<String, Box<dyn super::Document>>),
708 }
709
710 impl super::Document for Document {
711 fn discriminator(&self) -> Option<&ShapeId> {
712 self.discriminator.as_ref()
713 }
714
715 fn get_type(&self) -> Option<&ShapeType> {
716 match &self.value {
717 Value::Number(n) => match n {
718 Number::Byte(_) => Some(&ShapeType::Byte),
719 Number::Short(_) => Some(&ShapeType::Short),
720 Number::Integer(_) => Some(&ShapeType::Integer),
721 Number::Long(_) => Some(&ShapeType::Long),
722 Number::BigInt(_) => Some(&ShapeType::BigInteger),
723 Number::Float(_) => Some(&ShapeType::Float),
724 Number::Double(_) => Some(&ShapeType::Double),
725 Number::BigDecimal(_) => Some(&ShapeType::BigDecimal),
726 },
727 Value::Boolean(_) => Some(&ShapeType::Boolean),
728 Value::Blob(_) => Some(&ShapeType::Blob),
729 Value::String(_) => Some(&ShapeType::String),
730 Value::Timestamp(_) => Some(&ShapeType::Timestamp),
731 Value::List(_) => Some(&ShapeType::List),
732 Value::Map(_) => {
733 if self.schema.shape_type() == &ShapeType::Map {
734 Some(&ShapeType::Map)
735 } else {
736 Some(&ShapeType::Structure)
738 }
739 }
740 Value::Null => None,
742 }
743 }
744
745 fn size(&self) -> usize {
746 match &self.value {
747 Value::List(v) => v.len(),
748 Value::Map(v) => v.len(),
749 _ => 0,
750 }
751 }
752
753 fn as_blob(&self) -> Option<&ByteBuffer> {
754 if let Value::Blob(b) = &self.value {
755 Some(b)
756 } else {
757 None
758 }
759 }
760
761 fn as_bool(&self) -> Option<bool> {
762 if let Value::Boolean(b) = &self.value {
763 Some(*b)
764 } else {
765 None
766 }
767 }
768
769 fn as_string(&self) -> Option<&str> {
770 if let Value::String(s) = &self.value {
771 Some(s.as_str())
772 } else {
773 None
774 }
775 }
776
777 fn as_timestamp(&self) -> Option<&Instant> {
778 if let Value::Timestamp(t) = &self.value {
779 Some(t)
780 } else {
781 None
782 }
783 }
784
785 fn as_byte(&self) -> Option<i8> {
786 match &self.value {
787 Value::Number(n) => match n {
788 &Number::Byte(b) => Some(b),
789 &Number::Short(s) => s.try_into().ok(),
790 &Number::Integer(i) => i.try_into().ok(),
791 &Number::Long(l) => l.try_into().ok(),
792 Number::BigInt(b) => b.to_i8(),
793 _ => None,
794 },
795 _ => None,
796 }
797 }
798
799 fn as_short(&self) -> Option<i16> {
800 match &self.value {
801 Value::Number(n) => match n {
802 &Number::Byte(b) => Some(b.into()),
803 &Number::Short(s) => Some(s),
804 &Number::Integer(i) => i.try_into().ok(),
805 &Number::Long(l) => l.try_into().ok(),
806 Number::BigInt(b) => b.to_i16(),
807 _ => None,
808 },
809 _ => None,
810 }
811 }
812
813 fn as_integer(&self) -> Option<i32> {
814 match &self.value {
815 Value::Number(n) => match n {
816 &Number::Byte(b) => Some(b.into()),
817 &Number::Short(s) => Some(s.into()),
818 &Number::Integer(i) => Some(i),
819 &Number::Long(l) => l.try_into().ok(),
820 Number::BigInt(b) => b.to_i32(),
821 _ => None,
822 },
823 _ => None,
824 }
825 }
826
827 fn as_long(&self) -> Option<i64> {
828 match &self.value {
829 Value::Number(n) => match n {
830 &Number::Byte(b) => Some(b.into()),
831 &Number::Short(s) => Some(s.into()),
832 &Number::Integer(i) => Some(i.into()),
833 &Number::Long(l) => Some(l),
834 Number::BigInt(b) => b.to_i64(),
835 _ => None,
836 },
837 _ => None,
838 }
839 }
840
841 fn as_float(&self) -> Option<f32> {
842 match &self.value {
843 Value::Number(n) => match n {
844 &Number::Float(f) => Some(f),
845 &Number::Double(d) => Some(d as f32),
846 Number::BigDecimal(b) => b.to_f32(),
847 _ => None,
848 },
849 _ => None,
850 }
851 }
852
853 fn as_double(&self) -> Option<f64> {
854 match &self.value {
855 Value::Number(n) => match n {
856 &Number::Float(f) => Some(f.into()),
857 &Number::Double(d) => Some(d),
858 Number::BigDecimal(b) => b.to_f64(),
859 _ => None,
860 },
861 _ => None,
862 }
863 }
864
865 fn as_big_integer(&self) -> Option<&BigInt> {
866 todo!()
867 }
868
869 fn as_big_decimal(&self) -> Option<&BigDecimal> {
870 todo!()
871 }
872
873 fn as_list(&self) -> Option<&Vec<Box<dyn super::Document>>> {
874 if let Value::List(document_list) = &self.value {
875 Some(document_list)
876 } else {
877 None
878 }
879 }
880
881 fn as_map(&self) -> Option<&IndexMap<String, Box<dyn super::Document>>> {
882 if let Value::Map(document_map) = &self.value {
883 Some(document_map)
884 } else {
885 None
886 }
887 }
888
889 fn is_null(&self) -> bool {
890 matches!(self.value, Value::Null)
891 }
892
893 fn into_blob(self: Box<Self>) -> Result<ByteBuffer, DocumentError> {
894 if let Value::Blob(value) = self.value {
895 Ok(value)
896 } else {
897 Err(DocumentError::DocumentConversion(
898 "Expected blob document".to_string(),
899 ))
900 }
901 }
902
903 fn into_bool(self: Box<Self>) -> Result<bool, DocumentError> {
904 if let Value::Boolean(value) = self.value {
905 Ok(value)
906 } else {
907 Err(DocumentError::DocumentConversion(
908 "Expected boolean document".to_string(),
909 ))
910 }
911 }
912
913 fn into_string(self: Box<Self>) -> Result<String, DocumentError> {
914 if let Value::String(value) = self.value {
915 Ok(value)
916 } else {
917 Err(DocumentError::DocumentConversion(
918 "Expected string document".to_string(),
919 ))
920 }
921 }
922
923 fn into_timestamp(self: Box<Self>) -> Result<Instant, DocumentError> {
924 if let Value::Timestamp(value) = self.value {
925 Ok(value)
926 } else {
927 Err(DocumentError::DocumentConversion(
928 "Expected timestamp document".to_string(),
929 ))
930 }
931 }
932
933 fn into_byte(self: Box<Self>) -> Result<i8, DocumentError> {
935 self.as_byte().ok_or_else(|| {
936 DocumentError::DocumentConversion("Expected byte document".to_string())
937 })
938 }
939
940 fn into_short(self: Box<Self>) -> Result<i16, DocumentError> {
941 self.as_short().ok_or_else(|| {
942 DocumentError::DocumentConversion("Expected short document".to_string())
943 })
944 }
945
946 fn into_integer(self: Box<Self>) -> Result<i32, DocumentError> {
947 self.as_integer().ok_or_else(|| {
948 DocumentError::DocumentConversion("Expected integer document".to_string())
949 })
950 }
951
952 fn into_long(self: Box<Self>) -> Result<i64, DocumentError> {
953 self.as_long().ok_or_else(|| {
954 DocumentError::DocumentConversion("Expected long document".to_string())
955 })
956 }
957
958 fn into_float(self: Box<Self>) -> Result<f32, DocumentError> {
959 self.as_float().ok_or_else(|| {
960 DocumentError::DocumentConversion("Expected float document".to_string())
961 })
962 }
963
964 fn into_double(self: Box<Self>) -> Result<f64, DocumentError> {
965 self.as_double().ok_or_else(|| {
966 DocumentError::DocumentConversion("Expected double document".to_string())
967 })
968 }
969
970 fn into_big_integer(self: Box<Self>) -> Result<BigInt, DocumentError> {
972 self.as_big_integer().cloned().ok_or_else(|| {
973 DocumentError::DocumentConversion("Expected bigInteger document".to_string())
974 })
975 }
976
977 fn into_big_decimal(self: Box<Self>) -> Result<BigDecimal, DocumentError> {
978 self.as_big_decimal().cloned().ok_or_else(|| {
979 DocumentError::DocumentConversion("Expected bigInteger document".to_string())
980 })
981 }
982
983 fn into_list(self: Box<Self>) -> Result<Vec<Box<dyn super::Document>>, DocumentError> {
984 if let Value::List(value) = self.value {
985 Ok(value)
986 } else {
987 Err(DocumentError::DocumentConversion(
988 "Expected list document".to_string(),
989 ))
990 }
991 }
992
993 fn into_map(
994 self: Box<Self>,
995 ) -> Result<IndexMap<String, Box<dyn super::Document>>, DocumentError> {
996 if let Value::Map(value) = self.value {
997 Ok(value)
998 } else {
999 Err(DocumentError::DocumentConversion(
1000 "Expected map document".to_string(),
1001 ))
1002 }
1003 }
1004
1005 fn box_clone(&self) -> Box<dyn super::Document> {
1006 Box::new(self.clone())
1007 }
1008 }
1009
1010 #[derive(Debug, Clone, PartialEq)]
1018 pub enum Number {
1019 Byte(i8),
1020 Short(i16),
1021 Integer(i32),
1022 Long(i64),
1023 BigInt(BigInt),
1024 Float(f32),
1025 Double(f64),
1026 BigDecimal(BigDecimal),
1027 }
1028}
1029
1030impl From<default::Document> for Box<dyn Document> {
1035 #[inline]
1036 fn from(value: default::Document) -> Self {
1037 Box::new(value)
1038 }
1039}
1040
1041impl From<bool> for Box<dyn Document> {
1042 #[inline]
1043 fn from(value: bool) -> Self {
1044 default::Document {
1045 schema: BOOLEAN.clone(),
1046 value: Value::Boolean(value),
1047 discriminator: None,
1048 }
1049 .into()
1050 }
1051}
1052
1053impl From<i8> for Box<dyn Document> {
1054 #[inline]
1055 fn from(value: i8) -> Self {
1056 default::Document {
1057 schema: BYTE.clone(),
1058 value: Value::Number(Number::Byte(value)),
1059 discriminator: None,
1060 }
1061 .into()
1062 }
1063}
1064
1065impl From<i16> for Box<dyn Document> {
1066 #[inline]
1067 fn from(value: i16) -> Self {
1068 default::Document {
1069 schema: SHORT.clone(),
1070 value: Value::Number(Number::Short(value)),
1071 discriminator: None,
1072 }
1073 .into()
1074 }
1075}
1076
1077impl From<i32> for Box<dyn Document> {
1078 #[inline]
1079 fn from(value: i32) -> Self {
1080 default::Document {
1081 schema: INTEGER.clone(),
1082 value: Value::Number(Number::Integer(value)),
1083 discriminator: None,
1084 }
1085 .into()
1086 }
1087}
1088
1089impl From<i64> for Box<dyn Document> {
1090 #[inline]
1091 fn from(value: i64) -> Self {
1092 default::Document {
1093 schema: LONG.clone(),
1094 value: Value::Number(Number::Long(value)),
1095 discriminator: None,
1096 }
1097 .into()
1098 }
1099}
1100
1101impl From<f32> for Box<dyn Document> {
1102 #[inline]
1103 fn from(value: f32) -> Self {
1104 default::Document {
1105 schema: FLOAT.clone(),
1106 value: Value::Number(Number::Float(value)),
1107 discriminator: None,
1108 }
1109 .into()
1110 }
1111}
1112
1113impl From<f64> for Box<dyn Document> {
1114 #[inline]
1115 fn from(value: f64) -> Self {
1116 default::Document {
1117 schema: DOUBLE.clone(),
1118 value: Value::Number(Number::Double(value)),
1119 discriminator: None,
1120 }
1121 .into()
1122 }
1123}
1124
1125impl From<&str> for Box<dyn Document> {
1126 #[inline]
1127 fn from(value: &str) -> Self {
1128 default::Document {
1129 schema: STRING.clone(),
1130 value: Value::String(value.to_string()),
1131 discriminator: None,
1132 }
1133 .into()
1134 }
1135}
1136
1137impl From<BigInt> for Box<dyn Document> {
1138 #[inline]
1139 fn from(value: BigInt) -> Self {
1140 default::Document {
1141 schema: BIG_INTEGER.clone(),
1142 value: Value::Number(Number::BigInt(value)),
1143 discriminator: None,
1144 }
1145 .into()
1146 }
1147}
1148
1149impl From<BigDecimal> for Box<dyn Document> {
1150 #[inline]
1151 fn from(value: BigDecimal) -> Self {
1152 default::Document {
1153 schema: BIG_DECIMAL.clone(),
1154 value: Value::Number(Number::BigDecimal(value)),
1155 discriminator: None,
1156 }
1157 .into()
1158 }
1159}
1160
1161impl From<ByteBuffer> for Box<dyn Document> {
1162 #[inline]
1163 fn from(value: ByteBuffer) -> Self {
1164 default::Document {
1165 schema: BLOB.clone(),
1166 value: Value::Blob(value),
1167 discriminator: None,
1168 }
1169 .into()
1170 }
1171}
1172
1173impl From<String> for Box<dyn Document> {
1174 #[inline]
1175 fn from(value: String) -> Self {
1176 default::Document {
1177 schema: STRING.clone(),
1178 value: Value::String(value),
1179 discriminator: None,
1180 }
1181 .into()
1182 }
1183}
1184
1185impl From<Instant> for Box<dyn Document> {
1186 #[inline]
1187 fn from(value: Instant) -> Self {
1188 default::Document {
1189 schema: TIMESTAMP.clone(),
1190 value: Value::Timestamp(value),
1191 discriminator: None,
1192 }
1193 .into()
1194 }
1195}
1196impl From<&Instant> for Box<dyn Document> {
1197 #[inline]
1198 fn from(value: &Instant) -> Self {
1199 default::Document {
1200 schema: TIMESTAMP.clone(),
1201 value: Value::Timestamp(*value),
1202 discriminator: None,
1203 }
1204 .into()
1205 }
1206}
1207
1208smithy!("smithy.api#Document": {
1209 #[doc(hidden)]
1210 list LIST_DOCUMENT_SCHEMA {
1211 member: DOCUMENT
1212 }
1213});
1214
1215impl<T: Into<Box<dyn Document>>> From<Vec<T>> for Box<dyn Document> {
1216 fn from(value: Vec<T>) -> Self {
1217 let result = value.into_iter().map(Into::into).collect();
1218 default::Document {
1219 schema: LIST_DOCUMENT_SCHEMA.clone(),
1220 value: Value::List(result),
1221 discriminator: None,
1222 }
1223 .into()
1224 }
1225}
1226
1227smithy!("smithy.api#Document": {
1228 #[doc(hidden)]
1229 map MAP_DOCUMENT_SCHEMA {
1230 key: STRING
1231 value: DOCUMENT
1232 }
1233});
1234
1235impl<T: Into<Box<dyn Document>>> From<IndexMap<String, T>> for Box<dyn Document> {
1236 fn from(value: IndexMap<String, T>) -> Self {
1237 let mut result = IndexMap::new();
1238 for (key, value) in value {
1239 result.insert(key, value.into());
1240 }
1241 default::Document {
1242 schema: MAP_DOCUMENT_SCHEMA.clone(),
1243 value: Value::Map(result),
1244 discriminator: None,
1245 }
1246 .into()
1247 }
1248}
1249
1250macro_rules! option_conversion {
1251 ($ty:ty, $schema:ident) => {
1252 impl From<Option<$ty>> for Box<dyn Document> {
1253 fn from(value: Option<$ty>) -> Self {
1254 value.map_or_else(
1255 || {
1256 default::Document {
1257 schema: $schema.clone(),
1258 value: Value::Null,
1259 discriminator: None,
1260 }
1261 .into()
1262 },
1263 Into::into,
1264 )
1265 }
1266 }
1267 };
1268}
1269option_conversion!(String, STRING);
1270option_conversion!(bool, BOOLEAN);
1271option_conversion!(Instant, TIMESTAMP);
1272option_conversion!(ByteBuffer, BLOB);
1273option_conversion!(i8, BYTE);
1274option_conversion!(i16, SHORT);
1275option_conversion!(i32, INTEGER);
1276option_conversion!(i64, LONG);
1277option_conversion!(f32, FLOAT);
1278option_conversion!(BigInt, BIG_INTEGER);
1279option_conversion!(BigDecimal, BIG_DECIMAL);
1280
1281#[doc(hidden)]
1285pub static NULL: LazyLock<Box<dyn Document>> = LazyLock::new(|| {
1286 default::Document {
1287 schema: DOCUMENT.clone(),
1288 value: Value::Null,
1289 discriminator: None,
1290 }
1291 .into()
1292});
1293
1294#[cfg(test)]
1295mod tests {
1296 use super::*;
1297 use crate::schema::SchemaRef;
1298
1299 #[test]
1300 fn string_document_value() {
1301 let document_str: Box<dyn Document> = "MyStr".into();
1302 let val: &SchemaRef = &STRING;
1303 assert_eq!(document_str.schema(), val);
1304 let output_str: String = document_str.as_string().unwrap().to_string();
1305 assert_eq!(output_str, "MyStr".to_string());
1306
1307 let document_string: Box<dyn Document> = "MyString".into();
1308 assert_eq!(document_string.schema(), val);
1309 let output_string: String = document_string.as_string().unwrap().to_string();
1310 assert_eq!(&output_string, &"MyString");
1311 }
1312
1313 #[test]
1314 fn list_document_value() {
1315 let vec = vec!["a", "b", "c"];
1316 let document_list: Box<dyn Document> = vec.into();
1317 let val: &SchemaRef = &LIST_DOCUMENT_SCHEMA;
1318 assert_eq!(document_list.schema(), val);
1319 assert_eq!(document_list.size(), 3);
1320 let vec_out: Vec<String> = document_list.try_into().unwrap();
1321 assert_eq!(vec_out.len(), 3);
1322 assert_eq!(vec_out[0], "a");
1323 assert_eq!(vec_out[1], "b");
1324 assert_eq!(vec_out[2], "c");
1325 }
1326
1327 #[test]
1328 fn map_document_value() {
1329 let mut map_in: IndexMap<String, String> = IndexMap::new();
1330 map_in.insert("a".to_string(), "b".to_string());
1331 let map_doc: Box<dyn Document> = map_in.into();
1332 let val: &SchemaRef = &MAP_DOCUMENT_SCHEMA;
1333 assert_eq!(map_doc.schema(), val);
1334 assert_eq!(map_doc.size(), 1);
1335
1336 let map_out: IndexMap<String, String> = map_doc.try_into().unwrap();
1337 assert_eq!(map_out.len(), 1);
1338 assert_eq!(map_out["a"], "b");
1339 }
1340
1341 #[test]
1342 fn integer_document_values() {
1343 let byte: Box<dyn Document> = 1i8.into();
1344 let byte_val: &SchemaRef = &BYTE;
1345 assert_eq!(byte.schema(), byte_val);
1346
1347 let short: Box<dyn Document> = 1i16.into();
1348 let short_val: &SchemaRef = &SHORT;
1349
1350 assert_eq!(short.schema(), short_val);
1351
1352 let integer: Box<dyn Document> = 1i32.into();
1353 let integer_val: &SchemaRef = &INTEGER;
1354
1355 assert_eq!(integer.schema(), integer_val);
1356
1357 let long: Box<dyn Document> = 1i64.into();
1358 let long_val: &SchemaRef = &LONG;
1359
1360 assert_eq!(long.schema(), long_val);
1361 }
1362
1363 #[test]
1366 fn float_document_values() {
1367 let float: Box<dyn Document> = 1f32.into();
1368 let float_val: &SchemaRef = &FLOAT;
1369 assert_eq!(float.schema(), float_val);
1370
1371 let double: Box<dyn Document> = 1f64.into();
1372 let double_val: &SchemaRef = &DOUBLE;
1373 assert_eq!(double.schema(), double_val);
1374
1375 let float_value: f32 = float.try_into().unwrap();
1376 assert_eq!(float_value, 1f32);
1377 let double_value: f64 = double.try_into().unwrap();
1378 assert_eq!(double_value, 1f64);
1379 }
1380}