smithy4rs-core 0.0.1

Core functionality for smithy4rs.
Documentation
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
use std::{error::Error, fmt::Debug, sync::LazyLock};

use thiserror::Error;

use crate::{
    BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
    schema::{
        SchemaShape, ShapeId, ShapeType,
        default::{Number, Value},
        prelude::*,
    },
    smithy,
};

// ============================================================================
// Base Document Wrapper and trait
// ============================================================================

/// A Smithy [document](https://smithy.io/2.0/spec/simple-types.html#document) type,
/// representing untyped data in the Smithy data model.
///
/// TODO(doc): Update with dyn doc model
///
/// ### Smithy Data Model
///
/// The Smithy data model consists of:
/// - Numbers: `byte`, `short`, `integer`, `long`, `float`, `double`, `bigInteger`, `bigDecimal`.
///   `IntEnum` shapes are represented as integers in the Smithy data model.
/// - `boolean`
/// - `blob`
/// - `string`: `enum` shapes are represented as strings in the Smithy data model
/// - `timestamp`: Represented as an [`Instant`]
/// - `list`: list of Documents
/// - `map`: map of int|long|string keys to Document values
/// - `struct`: structure or union
///
/// ## Document Properties
/// 1. Shape Conversion - All generated shapes should be able to be converted to/from a document
/// 2. Lossless Serialization: Documents created from a shape should serialize exactly the same as the shape they are created from. I.e.
///
/// ```rust,ignore
/// // These two should be equivalent
/// my_smithy_shape.serialize(serializer)?;
/// my_smithy_shape.as_document().serialize(serializer)?;
/// ```
///
/// 3. Lossless Deserialization: Deserializing to a document then converting to a shape should be the same as deserializing to that shape. I.e. :
///
/// ```rust,ignore
/// // These two should be equivalent
/// let my_shape = deserializer::deserialize::<MyShape>::();
/// let my_shape = deserializer::deserialize::<Document>::().into();
/// ```
/// This is particularly important for dealing with errors, events, and over-the-wire polymorphism.
///
/// 4. Protocol Smoothing: Documents should try to smooth over any protocol-specific incompatibilities with the smithy data model.
/// 5. Discriminators - Documents with an encloded type should be able to be (de)serialized with data that identifies their
///
/// ### Protocol Smoothing
/// Because Document types are a protocol-agnostic view of untyped data, Protocol codecs should attempt to smooth over
/// any protocol-specific incompatibilities with the Smithy data model when deserializing into a document type.
///
/// For example, If a protocol represents a blob as a base64 encoded string, then deserializing the value into a
/// document should base64 decode the value and use the underlying bytes as the blob value in the document.
/// When the document is re-serialized by the same protocol, the protocol should handle conversion from a byte
/// buffer back to a base64 encoded string.
///
/// ### Lossless serialization
/// Point two *REQUIRES* that documents created from a shape have the exact same schema as that shape.
///
/// A good example of why is to consider the following Smithy Shape:
///
/// ```smithy
/// structure MyStruct {
///     @jsonName("foo")
///     bar: String
/// }
/// ```
///
/// When we go to serialize an instance of this shape with a JSON protocol we would expect that the member `bar`
/// is renamed to `foo` in the serialized JSON data:
///
/// ```rust,ignore
/// let myStructInstance = MyStruct::builder().bar("my-string").build()?;
/// myStructInstance.serialize(jsonSerializer);  // -> Yields `{ "foo": "my-string" }`
/// ```
///
/// The JSON protocol will achieve this conversion by discovering the `jsonName` trait on the
/// schema of the `myStructInstance` `bar` member.
///
/// Another good example is the case of a `@sensitive` field on a structure:
///
/// ```smithy
/// structure MyStructRedacted {
///     @sensitive
///     password: String
/// }
/// ```
///
/// `Display`-ing such a structure should result in the `@sensitive` field being redacted:
/// ```rust,ignore
/// let myStructInstance = MyStruct::builder().password("Secret".to_string()).build()?;
/// assert_eq!("MyStruct[password:**REDACTED**]", format!("{myStructInstance}"))
/// ```
///
/// We do _not_ want conversion to a document to suddenly start leaking a sensitive field.
///
/// In order to retain trait information, Documents created from a shape MUST retain that shape’s Schema.
///
/// ### Discriminators
/// Document types may have a `ShapeId` that indicates the type they correspond to.
/// This ID can be serialized to allow consumers to handle over the wire polymorphism (primarily for over-the wire polymorphism).
/// Typed documents must return the shape ID of the enclosed shape.
///
/// For example, let’s say we convert a shape of type `com.example#MyShape` into a document type.
/// The document would then store the `ShapeID` as its discriminator.
///
/// Serializing this document with a JSON protocol might result in a field `__type` being added to the output JSON :
///
/// ```json
/// {
///     "__type": "com.example#MyShape",
///     "other": {}
/// }
/// ```
///
/// <div class="warning">
/// Discriminators are only really useful for documents (or other structs) being serialized as Structure and Union types.
/// As such they, are serialized by the [`StructSerializer::serialize_discriminator`] method.
/// </div>
///
///
/// Similarly, a deserializer might want to pull the `__type` data from a JSON blob when deserializing into a Document type.
///
///
/// ## Lossless Deserialization
///
/// Let’s say we want to deserialize an error type that has the schema:
/// ```smithy
/// @error("client")
/// @http
/// struct MyClientError {
///     @required
///     message: String
///     @jsonName("foo")
///     bar: String
/// }
/// ```
///
/// Over the wire we might get a JSON body like:
///
/// ```json
/// {
///     "__type": "com.example#MyClientError",
///     "message": "Something broke pretty bad!",
///     "foo": "quux!"
/// }
/// ```
///
/// Because the error response _could_ be one of multiple error types, we don't know the type
/// to deserialize it to in advance.
/// We deserialize the JSON data to a Document, extract the discriminator, and use it to:
///
/// ```rust,ignore
/// let error_document = Document::deserialize(json_deserializer)?;
/// let builder = error_document.get_builder(error_document.discriminator());
/// let output = builder.deserialize(error_document)?.build();
/// ```
///
/// The initial `error_document` has no schema information (beyond the base `Document` schema), so it does not perform any protocol-specific
/// conversions during deserialization (i.e. it won't convert the field name `foo` to `bar` based on the `@jsonName` trait).
///
/// However, when we deserialize the document into the final Error type we need to execute the protocol-specific handling of the `jsonName` trait.
pub trait Document: SchemaShape + Send + Sync {
    /// Get the discriminator (type ID) of a type document
    ///
    /// The discriminator is primarily used to implement polymorphism using documents in deserialization.
    ///
    /// <div class="warning">
    /// It is expected that protocols set the discriminator on deserialization if applicable
    /// </div>
    #[must_use]
    fn discriminator(&self) -> Option<&ShapeId>;

    // ========== Basic info Methods ==========

    /// Get the Shape Type for the underlying contents of the document.
    ///
    /// The type returned from this method will differ from the type of the document (which will
    /// always be [`ShapeType::Document`]).
    ///
    /// NOTE: It is important that `self.get_type()` NEVER return `Document` as the type as that
    /// will result in infinite loops in serializers.
    ///
    /// ### Enums
    /// - `enum` shapes: Enum shapes are treated as a `string`, and variants can be found in
    ///   the corresponding schema for the document.
    ///  - `intEnum` shapes: Enum shapes are treated as an `integer`, and variants can be found in
    ///    the corresponding schema for the document.
    #[must_use]
    fn get_type(&self) -> Option<&ShapeType>;

    /// Get the number of elements in an array document, or the number of key value pairs in a map document.
    ///
    /// *NOTE*: Should return `0` for all other
    #[must_use]
    fn size(&self) -> usize;

    // ========== Borrowed data conversions ==========

    /// Get the `blob` value of the Document if it is a `blob`.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `blob` ([`ByteBuffer`]) value.
    #[must_use]
    fn as_blob(&self) -> Option<&ByteBuffer>;

    /// Get the `boolean` value of the Document if it is a `boolean` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `boolean` value.
    #[must_use]
    fn as_bool(&self) -> Option<bool>;

    /// Get the `string` value of the Document if it is a `string` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `string` value.
    #[must_use]
    fn as_string(&self) -> Option<&str>;

    /// Get the `timestamp` value of the Document if it is a `timestamp` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `timestamp` ([`Instant`]) value.
    #[must_use]
    fn as_timestamp(&self) -> Option<&Instant>;

    /// Get the `byte` value of the Document if it is a `byte` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `byte` (`i8`) value.
    #[must_use]
    fn as_byte(&self) -> Option<i8>;

    /// Get the `short` value of the Document if it is a `short` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `short` (`i16`) value.
    #[must_use]
    fn as_short(&self) -> Option<i16>;

    /// Get the `integer` value of the Document if it is an `integer` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to an
    /// `integer` (`i32`) value.
    #[must_use]
    fn as_integer(&self) -> Option<i32>;

    /// Get the `long` value of the Document if it is a `long` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to a
    /// `long` (`i64`) value.
    #[must_use]
    fn as_long(&self) -> Option<i64>;

    /// Get the `float` value of the Document if it is a `float` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to
    /// `float` (`f32`) value.
    #[must_use]
    fn as_float(&self) -> Option<f32>;

    /// Get the `decimal` value of the Document if it is a `decimal` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to
    /// `double` (`f64`) value.
    #[must_use]
    fn as_double(&self) -> Option<f64>;

    /// Get the `bigInteger` value of the Document if it is a `bigInteger` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to
    /// `bigInteger` ([`BigInt`]) value.
    #[must_use]
    fn as_big_integer(&self) -> Option<&BigInt>;

    /// Get the `bigDecimal` value of the Document if it is a `bigDecimal` or can be converted into one.
    ///
    /// Returns `None` if the document could not be converted to
    /// `bigDecimal` ([`BigDecimal`]) value.
    #[must_use]
    fn as_big_decimal(&self) -> Option<&BigDecimal>;

    /// Get the list contents of the Document if it is a list.
    ///
    /// Returns `None` if the document is not a list.
    #[must_use]
    fn as_list(&self) -> Option<&Vec<Box<dyn Document>>>;

    /// Get the map contents of the Document if it is a map.
    ///
    /// Returns `None` if the document is not a map.
    #[must_use]
    fn as_map(&self) -> Option<&IndexMap<String, Box<dyn Document>>>;

    /// Returns true if the document represents a `Null` value.
    #[must_use]
    fn is_null(&self) -> bool;

    // ========== Owned data conversions ==========

    /// Convert the [`Document`] to a `blob`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `blob` ([`ByteBuffer`]) value.
    fn into_blob(self: Box<Self>) -> Result<ByteBuffer, DocumentError>;

    /// Convert the [`Document`] to a `boolean`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `boolean` value.
    fn into_bool(self: Box<Self>) -> Result<bool, DocumentError>;

    /// Convert the [`Document`] to a `string`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `string` value.
    fn into_string(self: Box<Self>) -> Result<String, DocumentError>;

    /// Convert the [`Document`] to a `timestamp`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `timestamp` ([`Instant`]) value.
    fn into_timestamp(self: Box<Self>) -> Result<Instant, DocumentError>;

    /// Convert the [`Document`] to a `byte`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `byte` (`i8`) value.
    fn into_byte(self: Box<Self>) -> Result<i8, DocumentError>;

    /// Convert the [`Document`] to a `short`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `short` (`i16`) value.
    fn into_short(self: Box<Self>) -> Result<i16, DocumentError>;

    /// Convert the [`Document`] to an `integer`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `integer` (`i32`) value.
    fn into_integer(self: Box<Self>) -> Result<i32, DocumentError>;

    /// Convert the [`Document`] to a `long`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `long` (`i64`) value.
    fn into_long(self: Box<Self>) -> Result<i64, DocumentError>;

    /// Convert the [`Document`] to a `float`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `float` (`f32`) value.
    fn into_float(self: Box<Self>) -> Result<f32, DocumentError>;

    /// Convert the [`Document`] to a `double`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `double` (`f64`) value.
    fn into_double(self: Box<Self>) -> Result<f64, DocumentError>;

    /// Convert the [`Document`] to a `bigInteger`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `bigInteger` ([`BigInt`]) value.
    fn into_big_integer(self: Box<Self>) -> Result<BigInt, DocumentError>;

    /// Convert the [`Document`] to a `bigDecimal`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document could not be converted to a
    /// `bigDecimal` ([`BigDecimal`]) value.
    fn into_big_decimal(self: Box<Self>) -> Result<BigDecimal, DocumentError>;

    /// Convert the [`Document`] to a `list`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document is not a list.
    fn into_list(self: Box<Self>) -> Result<Vec<Box<dyn Document>>, DocumentError>;

    /// Convert the [`Document`] to a `map`.
    ///
    /// # Errors
    /// Returns a [`DocumentError`] if the document is not a map.
    fn into_map(self: Box<Self>) -> Result<IndexMap<String, Box<dyn Document>>, DocumentError>;

    /// Clone implementation necessary to satisfy the compiler
    fn box_clone(&self) -> Box<dyn Document>;
}

// ================================================================
// Blanket impl for dyn Documents
// ================================================================

impl PartialEq for dyn Document {
    fn eq(&self, other: &Self) -> bool {
        if self.schema() != other.schema() {
            return false;
        }
        if self.discriminator() != other.discriminator() {
            return false;
        }
        // TODO(numerical comparison): We should compare compatible numeric types
        // if possible. This is just a placeholder to get test working.
        match (self.get_type(), other.get_type()) {
            (Some(ShapeType::String), Some(ShapeType::String)) => {
                self.as_string() == other.as_string()
            }
            (Some(ShapeType::Blob), Some(ShapeType::Blob)) => self.as_blob() == other.as_blob(),
            (Some(ShapeType::Boolean), Some(ShapeType::Boolean)) => {
                self.as_bool() == other.as_bool()
            }
            (Some(ShapeType::Timestamp), Some(ShapeType::Timestamp)) => {
                self.as_timestamp() == other.as_timestamp()
            }
            (Some(ShapeType::Byte), Some(ShapeType::Byte)) => self.as_byte() == other.as_byte(),
            (Some(ShapeType::Short), Some(ShapeType::Short)) => self.as_short() == other.as_short(),
            (Some(ShapeType::Integer), Some(ShapeType::Integer)) => {
                self.as_integer() == other.as_integer()
            }
            (Some(ShapeType::Long), Some(ShapeType::Long)) => self.as_long() == other.as_long(),
            (Some(ShapeType::Float), Some(ShapeType::Float)) => self.as_float() == other.as_float(),
            (Some(ShapeType::Double), Some(ShapeType::Double)) => {
                self.as_double() == other.as_double()
            }
            (Some(ShapeType::BigInteger), Some(ShapeType::BigInteger)) => {
                self.as_big_integer() == other.as_big_integer()
            }
            (Some(ShapeType::BigDecimal), Some(ShapeType::BigDecimal)) => {
                self.as_big_decimal() == other.as_big_decimal()
            }
            (Some(ShapeType::List), Some(ShapeType::List)) => self.as_list() == other.as_list(),
            (Some(ShapeType::Map), Some(ShapeType::Map)) => self.as_map() == other.as_map(),
            (None, None) => true,
            _ => false,
        }
    }
}

impl Clone for Box<dyn Document> {
    #[inline]
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

// ============================================================================
// Document Errors
// ============================================================================

/// Errors that can occur when converting to/from a document type.
#[derive(Error, Debug)]
pub enum DocumentError {
    /// Document failed to serialize to a data sink
    #[error("Failed to convert document to type {0}")]
    DocumentSerialization(String),
    /// Could not convert a type _into_ a document
    #[error("Failed to convert document to type {0}")]
    DocumentConversion(String),
    /// An unknown error
    #[error("Encountered unknown error")]
    Unknown(#[from] Box<dyn Error>),
    /// A custom error
    #[error("Encountered error: {0}")]
    CustomError(String),
}

impl crate::serde::de::Error for DocumentError {
    fn custom<T: std::fmt::Display>(msg: T) -> Self {
        DocumentError::CustomError(msg.to_string())
    }
}

// ============================================================================
// Convert Document into types
// ============================================================================

impl TryFrom<Box<dyn Document>> for ByteBuffer {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_blob()
    }
}

impl TryFrom<Box<dyn Document>> for bool {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_bool()
    }
}

impl TryFrom<Box<dyn Document>> for String {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_string()
    }
}

impl TryFrom<Box<dyn Document>> for Instant {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_timestamp()
    }
}

impl TryFrom<Box<dyn Document>> for i8 {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_byte()
    }
}

impl TryFrom<Box<dyn Document>> for i16 {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_short()
    }
}

impl TryFrom<Box<dyn Document>> for i32 {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_integer()
    }
}

impl TryFrom<Box<dyn Document>> for i64 {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_long()
    }
}

impl TryFrom<Box<dyn Document>> for f32 {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_float()
    }
}

impl TryFrom<Box<dyn Document>> for f64 {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_double()
    }
}

impl TryFrom<Box<dyn Document>> for BigInt {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_big_integer()
    }
}

impl TryFrom<Box<dyn Document>> for BigDecimal {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_big_decimal()
    }
}

impl TryFrom<Box<dyn Document>> for Vec<Box<dyn Document>> {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_list()
    }
}

impl TryFrom<Box<dyn Document>> for IndexMap<String, Box<dyn Document>> {
    type Error = DocumentError;

    #[inline]
    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        value.into_map()
    }
}

impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>> for Vec<T> {
    type Error = DocumentError;

    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        let vec = value.into_list()?;
        let mut result: Vec<T> = Vec::new();
        for doc in vec {
            match T::try_from(doc.clone()) {
                Ok(val) => result.push(val),
                Err(e) => return Err(e),
            }
        }
        Ok(result)
    }
}

impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>>
    for IndexMap<String, T>
{
    type Error = DocumentError;

    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        let map = value.into_map()?;
        let mut result: IndexMap<String, T> = IndexMap::new();
        for (key, val) in map {
            let _ = match T::try_from(val.clone()) {
                Ok(val) => result.insert(key.clone(), val),
                Err(e) => return Err(e),
            };
        }
        Ok(result)
    }
}

impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>>
    for Option<T>
{
    type Error = DocumentError;

    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
        if value.is_null() {
            return Ok(None);
        }
        Ok(Some(value.try_into()?))
    }
}

// ============================================================================
// Default Document Implementation
// ============================================================================

pub(crate) mod default {
    use bigdecimal::ToPrimitive;

    use crate::{
        BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
        schema::{DocumentError, SchemaRef, SchemaShape, ShapeId, ShapeType},
    };

    #[derive(Clone, PartialEq, Debug)]
    pub struct Document {
        pub schema: SchemaRef,
        pub value: Value,
        pub discriminator: Option<ShapeId>,
    }

    impl SchemaShape for Document {
        fn schema(&self) -> &SchemaRef {
            &self.schema
        }
    }

    #[derive(Clone, PartialEq, Debug)]
    pub enum Value {
        Null,
        Number(Number),
        Boolean(bool),
        Blob(ByteBuffer),
        String(String),
        Timestamp(Instant),
        List(Vec<Box<dyn super::Document>>),
        Map(IndexMap<String, Box<dyn super::Document>>),
    }

    impl super::Document for Document {
        fn discriminator(&self) -> Option<&ShapeId> {
            self.discriminator.as_ref()
        }

        fn get_type(&self) -> Option<&ShapeType> {
            match &self.value {
                Value::Number(n) => match n {
                    Number::Byte(_) => Some(&ShapeType::Byte),
                    Number::Short(_) => Some(&ShapeType::Short),
                    Number::Integer(_) => Some(&ShapeType::Integer),
                    Number::Long(_) => Some(&ShapeType::Long),
                    Number::BigInt(_) => Some(&ShapeType::BigInteger),
                    Number::Float(_) => Some(&ShapeType::Float),
                    Number::Double(_) => Some(&ShapeType::Double),
                    Number::BigDecimal(_) => Some(&ShapeType::BigDecimal),
                },
                Value::Boolean(_) => Some(&ShapeType::Boolean),
                Value::Blob(_) => Some(&ShapeType::Blob),
                Value::String(_) => Some(&ShapeType::String),
                Value::Timestamp(_) => Some(&ShapeType::Timestamp),
                Value::List(_) => Some(&ShapeType::List),
                Value::Map(_) => {
                    if self.schema.shape_type() == &ShapeType::Map {
                        Some(&ShapeType::Map)
                    } else {
                        // If we created the document from a structure schema, treat it as a struct
                        Some(&ShapeType::Structure)
                    }
                }
                // Null is not representable as a shape type
                Value::Null => None,
            }
        }

        fn size(&self) -> usize {
            match &self.value {
                Value::List(v) => v.len(),
                Value::Map(v) => v.len(),
                _ => 0,
            }
        }

        fn as_blob(&self) -> Option<&ByteBuffer> {
            if let Value::Blob(b) = &self.value {
                Some(b)
            } else {
                None
            }
        }

        fn as_bool(&self) -> Option<bool> {
            if let Value::Boolean(b) = &self.value {
                Some(*b)
            } else {
                None
            }
        }

        fn as_string(&self) -> Option<&str> {
            if let Value::String(s) = &self.value {
                Some(s.as_str())
            } else {
                None
            }
        }

        fn as_timestamp(&self) -> Option<&Instant> {
            if let Value::Timestamp(t) = &self.value {
                Some(t)
            } else {
                None
            }
        }

        fn as_byte(&self) -> Option<i8> {
            match &self.value {
                Value::Number(n) => match n {
                    &Number::Byte(b) => Some(b),
                    &Number::Short(s) => s.try_into().ok(),
                    &Number::Integer(i) => i.try_into().ok(),
                    &Number::Long(l) => l.try_into().ok(),
                    Number::BigInt(b) => b.to_i8(),
                    _ => None,
                },
                _ => None,
            }
        }

        fn as_short(&self) -> Option<i16> {
            match &self.value {
                Value::Number(n) => match n {
                    &Number::Byte(b) => Some(b.into()),
                    &Number::Short(s) => Some(s),
                    &Number::Integer(i) => i.try_into().ok(),
                    &Number::Long(l) => l.try_into().ok(),
                    Number::BigInt(b) => b.to_i16(),
                    _ => None,
                },
                _ => None,
            }
        }

        fn as_integer(&self) -> Option<i32> {
            match &self.value {
                Value::Number(n) => match n {
                    &Number::Byte(b) => Some(b.into()),
                    &Number::Short(s) => Some(s.into()),
                    &Number::Integer(i) => Some(i),
                    &Number::Long(l) => l.try_into().ok(),
                    Number::BigInt(b) => b.to_i32(),
                    _ => None,
                },
                _ => None,
            }
        }

        fn as_long(&self) -> Option<i64> {
            match &self.value {
                Value::Number(n) => match n {
                    &Number::Byte(b) => Some(b.into()),
                    &Number::Short(s) => Some(s.into()),
                    &Number::Integer(i) => Some(i.into()),
                    &Number::Long(l) => Some(l),
                    Number::BigInt(b) => b.to_i64(),
                    _ => None,
                },
                _ => None,
            }
        }

        fn as_float(&self) -> Option<f32> {
            match &self.value {
                Value::Number(n) => match n {
                    &Number::Float(f) => Some(f),
                    &Number::Double(d) => Some(d as f32),
                    Number::BigDecimal(b) => b.to_f32(),
                    _ => None,
                },
                _ => None,
            }
        }

        fn as_double(&self) -> Option<f64> {
            match &self.value {
                Value::Number(n) => match n {
                    &Number::Float(f) => Some(f.into()),
                    &Number::Double(d) => Some(d),
                    Number::BigDecimal(b) => b.to_f64(),
                    _ => None,
                },
                _ => None,
            }
        }

        fn as_big_integer(&self) -> Option<&BigInt> {
            todo!()
        }

        fn as_big_decimal(&self) -> Option<&BigDecimal> {
            todo!()
        }

        fn as_list(&self) -> Option<&Vec<Box<dyn super::Document>>> {
            if let Value::List(document_list) = &self.value {
                Some(document_list)
            } else {
                None
            }
        }

        fn as_map(&self) -> Option<&IndexMap<String, Box<dyn super::Document>>> {
            if let Value::Map(document_map) = &self.value {
                Some(document_map)
            } else {
                None
            }
        }

        fn is_null(&self) -> bool {
            matches!(self.value, Value::Null)
        }

        fn into_blob(self: Box<Self>) -> Result<ByteBuffer, DocumentError> {
            if let Value::Blob(value) = self.value {
                Ok(value)
            } else {
                Err(DocumentError::DocumentConversion(
                    "Expected blob document".to_string(),
                ))
            }
        }

        fn into_bool(self: Box<Self>) -> Result<bool, DocumentError> {
            if let Value::Boolean(value) = self.value {
                Ok(value)
            } else {
                Err(DocumentError::DocumentConversion(
                    "Expected boolean document".to_string(),
                ))
            }
        }

        fn into_string(self: Box<Self>) -> Result<String, DocumentError> {
            if let Value::String(value) = self.value {
                Ok(value)
            } else {
                Err(DocumentError::DocumentConversion(
                    "Expected string document".to_string(),
                ))
            }
        }

        fn into_timestamp(self: Box<Self>) -> Result<Instant, DocumentError> {
            if let Value::Timestamp(value) = self.value {
                Ok(value)
            } else {
                Err(DocumentError::DocumentConversion(
                    "Expected timestamp document".to_string(),
                ))
            }
        }

        // TODO(numeric conversion): Review these numeric conversions.
        fn into_byte(self: Box<Self>) -> Result<i8, DocumentError> {
            self.as_byte().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected byte document".to_string())
            })
        }

        fn into_short(self: Box<Self>) -> Result<i16, DocumentError> {
            self.as_short().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected short document".to_string())
            })
        }

        fn into_integer(self: Box<Self>) -> Result<i32, DocumentError> {
            self.as_integer().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected integer document".to_string())
            })
        }

        fn into_long(self: Box<Self>) -> Result<i64, DocumentError> {
            self.as_long().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected long document".to_string())
            })
        }

        fn into_float(self: Box<Self>) -> Result<f32, DocumentError> {
            self.as_float().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected float document".to_string())
            })
        }

        fn into_double(self: Box<Self>) -> Result<f64, DocumentError> {
            self.as_double().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected double document".to_string())
            })
        }

        // TODO(numeric conversion): These shouldnt need to clone.
        fn into_big_integer(self: Box<Self>) -> Result<BigInt, DocumentError> {
            self.as_big_integer().cloned().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected bigInteger document".to_string())
            })
        }

        fn into_big_decimal(self: Box<Self>) -> Result<BigDecimal, DocumentError> {
            self.as_big_decimal().cloned().ok_or_else(|| {
                DocumentError::DocumentConversion("Expected bigInteger document".to_string())
            })
        }

        fn into_list(self: Box<Self>) -> Result<Vec<Box<dyn super::Document>>, DocumentError> {
            if let Value::List(value) = self.value {
                Ok(value)
            } else {
                Err(DocumentError::DocumentConversion(
                    "Expected list document".to_string(),
                ))
            }
        }

        fn into_map(
            self: Box<Self>,
        ) -> Result<IndexMap<String, Box<dyn super::Document>>, DocumentError> {
            if let Value::Map(value) = self.value {
                Ok(value)
            } else {
                Err(DocumentError::DocumentConversion(
                    "Expected map document".to_string(),
                ))
            }
        }

        fn box_clone(&self) -> Box<dyn super::Document> {
            Box::new(self.clone())
        }
    }

    /// Represents numbers in the smithy data model
    ///
    /// Smithy numbers types include: byte, short, integer, long, float, double, bigInteger, bigDecimal.
    ///
    /// <div class ="note">
    /// **NOTE**: `IntEnum` shapes are represented as integers in the Smithy data model.
    /// </div>
    #[derive(Debug, Clone, PartialEq)]
    pub enum Number {
        Byte(i8),
        Short(i16),
        Integer(i32),
        Long(i64),
        BigInt(BigInt),
        Float(f32),
        Double(f64),
        BigDecimal(BigDecimal),
    }
}

// ============================================================================
// Conversions INTO Default Document
// ============================================================================

impl From<default::Document> for Box<dyn Document> {
    #[inline]
    fn from(value: default::Document) -> Self {
        Box::new(value)
    }
}

impl From<bool> for Box<dyn Document> {
    #[inline]
    fn from(value: bool) -> Self {
        default::Document {
            schema: BOOLEAN.clone(),
            value: Value::Boolean(value),
            discriminator: None,
        }
        .into()
    }
}

impl From<i8> for Box<dyn Document> {
    #[inline]
    fn from(value: i8) -> Self {
        default::Document {
            schema: BYTE.clone(),
            value: Value::Number(Number::Byte(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<i16> for Box<dyn Document> {
    #[inline]
    fn from(value: i16) -> Self {
        default::Document {
            schema: SHORT.clone(),
            value: Value::Number(Number::Short(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<i32> for Box<dyn Document> {
    #[inline]
    fn from(value: i32) -> Self {
        default::Document {
            schema: INTEGER.clone(),
            value: Value::Number(Number::Integer(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<i64> for Box<dyn Document> {
    #[inline]
    fn from(value: i64) -> Self {
        default::Document {
            schema: LONG.clone(),
            value: Value::Number(Number::Long(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<f32> for Box<dyn Document> {
    #[inline]
    fn from(value: f32) -> Self {
        default::Document {
            schema: FLOAT.clone(),
            value: Value::Number(Number::Float(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<f64> for Box<dyn Document> {
    #[inline]
    fn from(value: f64) -> Self {
        default::Document {
            schema: DOUBLE.clone(),
            value: Value::Number(Number::Double(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<&str> for Box<dyn Document> {
    #[inline]
    fn from(value: &str) -> Self {
        default::Document {
            schema: STRING.clone(),
            value: Value::String(value.to_string()),
            discriminator: None,
        }
        .into()
    }
}

impl From<BigInt> for Box<dyn Document> {
    #[inline]
    fn from(value: BigInt) -> Self {
        default::Document {
            schema: BIG_INTEGER.clone(),
            value: Value::Number(Number::BigInt(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<BigDecimal> for Box<dyn Document> {
    #[inline]
    fn from(value: BigDecimal) -> Self {
        default::Document {
            schema: BIG_DECIMAL.clone(),
            value: Value::Number(Number::BigDecimal(value)),
            discriminator: None,
        }
        .into()
    }
}

impl From<ByteBuffer> for Box<dyn Document> {
    #[inline]
    fn from(value: ByteBuffer) -> Self {
        default::Document {
            schema: BLOB.clone(),
            value: Value::Blob(value),
            discriminator: None,
        }
        .into()
    }
}

impl From<String> for Box<dyn Document> {
    #[inline]
    fn from(value: String) -> Self {
        default::Document {
            schema: STRING.clone(),
            value: Value::String(value),
            discriminator: None,
        }
        .into()
    }
}

impl From<Instant> for Box<dyn Document> {
    #[inline]
    fn from(value: Instant) -> Self {
        default::Document {
            schema: TIMESTAMP.clone(),
            value: Value::Timestamp(value),
            discriminator: None,
        }
        .into()
    }
}
impl From<&Instant> for Box<dyn Document> {
    #[inline]
    fn from(value: &Instant) -> Self {
        default::Document {
            schema: TIMESTAMP.clone(),
            value: Value::Timestamp(*value),
            discriminator: None,
        }
        .into()
    }
}

smithy!("smithy.api#Document": {
    #[doc(hidden)]
    list LIST_DOCUMENT_SCHEMA {
        member: DOCUMENT
    }
});

impl<T: Into<Box<dyn Document>>> From<Vec<T>> for Box<dyn Document> {
    fn from(value: Vec<T>) -> Self {
        let result = value.into_iter().map(Into::into).collect();
        default::Document {
            schema: LIST_DOCUMENT_SCHEMA.clone(),
            value: Value::List(result),
            discriminator: None,
        }
        .into()
    }
}

smithy!("smithy.api#Document": {
    #[doc(hidden)]
    map MAP_DOCUMENT_SCHEMA {
        key: STRING
        value: DOCUMENT
    }
});

impl<T: Into<Box<dyn Document>>> From<IndexMap<String, T>> for Box<dyn Document> {
    fn from(value: IndexMap<String, T>) -> Self {
        let mut result = IndexMap::new();
        for (key, value) in value {
            result.insert(key, value.into());
        }
        default::Document {
            schema: MAP_DOCUMENT_SCHEMA.clone(),
            value: Value::Map(result),
            discriminator: None,
        }
        .into()
    }
}

macro_rules! option_conversion {
    ($ty:ty, $schema:ident) => {
        impl From<Option<$ty>> for Box<dyn Document> {
            fn from(value: Option<$ty>) -> Self {
                value.map_or_else(
                    || {
                        default::Document {
                            schema: $schema.clone(),
                            value: Value::Null,
                            discriminator: None,
                        }
                        .into()
                    },
                    Into::into,
                )
            }
        }
    };
}
option_conversion!(String, STRING);
option_conversion!(bool, BOOLEAN);
option_conversion!(Instant, TIMESTAMP);
option_conversion!(ByteBuffer, BLOB);
option_conversion!(i8, BYTE);
option_conversion!(i16, SHORT);
option_conversion!(i32, INTEGER);
option_conversion!(i64, LONG);
option_conversion!(f32, FLOAT);
option_conversion!(BigInt, BIG_INTEGER);
option_conversion!(BigDecimal, BIG_DECIMAL);

// =========================================================================
// Null Document
// =========================================================================
#[doc(hidden)]
pub static NULL: LazyLock<Box<dyn Document>> = LazyLock::new(|| {
    default::Document {
        schema: DOCUMENT.clone(),
        value: Value::Null,
        discriminator: None,
    }
    .into()
});

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::SchemaRef;

    #[test]
    fn string_document_value() {
        let document_str: Box<dyn Document> = "MyStr".into();
        let val: &SchemaRef = &STRING;
        assert_eq!(document_str.schema(), val);
        let output_str: String = document_str.as_string().unwrap().to_string();
        assert_eq!(output_str, "MyStr".to_string());

        let document_string: Box<dyn Document> = "MyString".into();
        assert_eq!(document_string.schema(), val);
        let output_string: String = document_string.as_string().unwrap().to_string();
        assert_eq!(&output_string, &"MyString");
    }

    #[test]
    fn list_document_value() {
        let vec = vec!["a", "b", "c"];
        let document_list: Box<dyn Document> = vec.into();
        let val: &SchemaRef = &LIST_DOCUMENT_SCHEMA;
        assert_eq!(document_list.schema(), val);
        assert_eq!(document_list.size(), 3);
        let vec_out: Vec<String> = document_list.try_into().unwrap();
        assert_eq!(vec_out.len(), 3);
        assert_eq!(vec_out[0], "a");
        assert_eq!(vec_out[1], "b");
        assert_eq!(vec_out[2], "c");
    }

    #[test]
    fn map_document_value() {
        let mut map_in: IndexMap<String, String> = IndexMap::new();
        map_in.insert("a".to_string(), "b".to_string());
        let map_doc: Box<dyn Document> = map_in.into();
        let val: &SchemaRef = &MAP_DOCUMENT_SCHEMA;
        assert_eq!(map_doc.schema(), val);
        assert_eq!(map_doc.size(), 1);

        let map_out: IndexMap<String, String> = map_doc.try_into().unwrap();
        assert_eq!(map_out.len(), 1);
        assert_eq!(map_out["a"], "b");
    }

    #[test]
    fn integer_document_values() {
        let byte: Box<dyn Document> = 1i8.into();
        let byte_val: &SchemaRef = &BYTE;
        assert_eq!(byte.schema(), byte_val);

        let short: Box<dyn Document> = 1i16.into();
        let short_val: &SchemaRef = &SHORT;

        assert_eq!(short.schema(), short_val);

        let integer: Box<dyn Document> = 1i32.into();
        let integer_val: &SchemaRef = &INTEGER;

        assert_eq!(integer.schema(), integer_val);

        let long: Box<dyn Document> = 1i64.into();
        let long_val: &SchemaRef = &LONG;

        assert_eq!(long.schema(), long_val);
    }

    // TODO(numeric comparisons): Add comparison checks

    #[test]
    fn float_document_values() {
        let float: Box<dyn Document> = 1f32.into();
        let float_val: &SchemaRef = &FLOAT;
        assert_eq!(float.schema(), float_val);

        let double: Box<dyn Document> = 1f64.into();
        let double_val: &SchemaRef = &DOUBLE;
        assert_eq!(double.schema(), double_val);

        let float_value: f32 = float.try_into().unwrap();
        assert_eq!(float_value, 1f32);
        let double_value: f64 = double.try_into().unwrap();
        assert_eq!(double_value, 1f64);
    }
}