fhir-types 0.1.106

Generated per-version FHIR types and terminology operation contracts
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
// @generated by fhir-codegen from hl7.fhir.r4.core 4.0.1, hl7.fhir.r4b.core 4.3.0, hl7.fhir.r5.core 5.0.0, hl7.fhir.r6.core 6.0.0-ballot5. DO NOT EDIT.
// Change the emitter (tools/fhir-codegen) and regenerate.
// SPDX-FileCopyrightText: Vernum Projecten B.V.
// SPDX-License-Identifier: Apache-2.0
//! The FHIR JSON representation shared by every version module.
//!
//! Resources carry `resourceType`; a primitive element is a JSON value plus an
//! optional sibling named with a leading underscore that holds its `id` and
//! `extension`; repeating primitives are two arrays aligned with `null`;
//! integers and decimals are JSON numbers with their lexical form preserved;
//! objects and arrays are never empty; unknown properties are refused
//! (<https://hl7.org/fhir/R4B/json.html>).

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

use serde_json::value::RawValue;

/// A JSON object, its keys in sorted order.
pub type Object = BTreeMap<String, Value>;

/// A JSON number, in the lexical form the document carried.
///
/// FHIR forbids reading a decimal through a binary float: "Do not use an IEEE
/// type floating point type, instead use something that works like a true
/// decimal" (<https://hl7.org/fhir/R4B/datatypes.html#decimal>), so the number
/// keeps its text and the codec never rounds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Number(String);

impl Number {
    /// The number as it was written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The number as an `i64`, `None` when it is no whole number in range.
    #[must_use]
    pub fn as_i64(&self) -> Option<i64> {
        self.as_str().parse().ok()
    }

    /// The number as a `u64`, `None` when it is no whole number in range.
    #[must_use]
    pub fn as_u64(&self) -> Option<u64> {
        self.as_str().parse().ok()
    }
}

impl fmt::Display for Number {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Text that is no JSON number.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NotANumber;

impl fmt::Display for NotANumber {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("not a JSON number")
    }
}

impl std::error::Error for NotANumber {}

impl FromStr for Number {
    type Err = NotANumber;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let numeric = matches!(text.as_bytes().first(), Some(b'-' | b'0'..=b'9'))
            && matches!(text.as_bytes().last(), Some(b'0'..=b'9'));
        if !numeric {
            return Err(NotANumber);
        }
        serde_json::from_str::<&RawValue>(text).map_err(|_| NotANumber)?;
        Ok(Self(String::from(text)))
    }
}

impl From<i64> for Number {
    fn from(value: i64) -> Self {
        Self(value.to_string())
    }
}

impl From<i32> for Number {
    fn from(value: i32) -> Self {
        Self::from(i64::from(value))
    }
}

impl From<u32> for Number {
    fn from(value: u32) -> Self {
        Self::from(i64::from(value))
    }
}

impl serde::Serialize for Number {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // NOTE: JSON forbids a leading plus or zero (RFC 8259 §6), so an `i64`
        // that parses writes back the same text apart from `-0`; every other
        // number goes out raw, keeping the precision FHIR gives it.
        match self.as_i64() {
            Some(whole) if self.as_str() != "-0" => serializer.serialize_i64(whole),
            _ => {
                let raw = serde_json::from_str::<&RawValue>(self.as_str())
                    .map_err(serde::ser::Error::custom)?;
                serde::Serialize::serialize(raw, serializer)
            }
        }
    }
}

/// A JSON document, with every number kept in its lexical form.
///
/// Reading one goes through `serde_json`'s raw value, so a number arrives with
/// the precision the document wrote and the crate imposes no
/// `arbitrary_precision` feature on anything that depends on it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Value {
    /// `null`.
    #[default]
    Null,
    /// `true` or `false`.
    Bool(bool),
    /// A number.
    Number(Number),
    /// A string.
    String(String),
    /// An array.
    Array(Vec<Value>),
    /// An object.
    Object(Object),
}

impl Value {
    /// The member named `key`, `None` unless this is an object holding it.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&Self> {
        match self {
            Self::Object(object) => object.get(key),
            _ => None,
        }
    }

    /// The object this holds, `None` for every other kind.
    #[must_use]
    pub const fn as_object(&self) -> Option<&Object> {
        match self {
            Self::Object(object) => Some(object),
            _ => None,
        }
    }

    /// The array this holds, `None` for every other kind.
    #[must_use]
    pub fn as_array(&self) -> Option<&[Self]> {
        match self {
            Self::Array(items) => Some(items),
            _ => None,
        }
    }

    /// The string this holds, `None` for every other kind.
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(text) => Some(text),
            _ => None,
        }
    }

    /// Whether this is `null`.
    #[must_use]
    pub const fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// This document as a `serde_json::Value`, keeping every number exact.
    ///
    /// A number converts only when `serde_json` writes it back in the text
    /// this document carried, so a decimal is never altered on the way out:
    /// FHIR regards `0.010` as different from `0.01`
    /// (<https://hl7.org/fhir/R4/datatypes.html#decimal>). A `serde_json`
    /// built with `arbitrary_precision` keeps every lexical form, and one
    /// built without it keeps whole numbers and the decimals `f64` writes back
    /// unchanged. Object keys stay in the sorted order [`Object`] holds them
    /// in, which carries no meaning: "the order of properties of an object is
    /// not significant in the JSON representation"
    /// (<https://hl7.org/fhir/R4/json.html>).
    ///
    /// # Errors
    ///
    /// Returns [`ValueConversionError`] naming the element path of the first
    /// number `serde_json` would alter or cannot hold.
    pub fn into_serde_json(
        self,
        path: &mut Path,
    ) -> Result<serde_json::Value, ValueConversionError> {
        match self {
            Self::Null => Ok(serde_json::Value::Null),
            Self::Bool(flag) => Ok(serde_json::Value::Bool(flag)),
            Self::Number(number) => convert_number(&number, path).map(serde_json::Value::Number),
            Self::String(text) => Ok(serde_json::Value::String(text)),
            Self::Array(items) => {
                let mut converted = Vec::with_capacity(items.len());
                for (index, item) in items.into_iter().enumerate() {
                    converted.push(path.with_index("", index, |path| item.into_serde_json(path))?);
                }
                Ok(serde_json::Value::Array(converted))
            }
            Self::Object(members) => {
                let mut converted = serde_json::Map::with_capacity(members.len());
                for (key, member) in members {
                    let value = convert_member(&key, member, path)?;
                    converted.insert(key, value);
                }
                Ok(serde_json::Value::Object(converted))
            }
        }
    }

    /// A copy of this document as a `serde_json::Value`, keeping every number
    /// exact.
    ///
    /// The document is cloned first, so prefer [`Value::into_serde_json`]
    /// where the caller owns it. The number rule is the same.
    ///
    /// # Errors
    ///
    /// Returns [`ValueConversionError`] naming the element path of the first
    /// number `serde_json` would alter or cannot hold.
    pub fn to_serde_json(
        &self,
        path: &mut Path,
    ) -> Result<serde_json::Value, ValueConversionError> {
        self.clone().into_serde_json(path)
    }

    /// A `serde_json::Value` as this document.
    ///
    /// A number arrives in the text `serde_json` holds for it, which is the
    /// form the document carried when `serde_json` was built with
    /// `arbitrary_precision` and the `f64` rendering of it otherwise. Read a
    /// FHIR document whose decimals must stay exact through this crate's own
    /// [`Value`] decoder instead; this direction serves the HTTP edge and test
    /// fixtures, where the document is already a `serde_json::Value`.
    #[must_use]
    pub fn from_serde_json(value: serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => Self::Null,
            serde_json::Value::Bool(flag) => Self::Bool(flag),
            serde_json::Value::Number(number) => Self::Number(Number(number.to_string())),
            serde_json::Value::String(text) => Self::String(text),
            serde_json::Value::Array(items) => {
                Self::Array(items.into_iter().map(Self::from_serde_json).collect())
            }
            serde_json::Value::Object(members) => Self::Object(
                members
                    .into_iter()
                    .map(|(key, member)| (key, Self::from_serde_json(member)))
                    .collect(),
            ),
        }
    }
}

/// Why a [`Value`] has no `serde_json::Value` form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueConversionError {
    /// `serde_json` writes the number back in another form.
    LossyNumber {
        /// The element path, for example `Observation.valueQuantity.value`.
        path: String,
        /// The number as the document carried it.
        lexical: String,
        /// The number as `serde_json` writes it.
        rendered: String,
    },
    /// `serde_json` holds no number of this magnitude.
    UnrepresentableNumber {
        /// The element path, for example `Observation.valueQuantity.value`.
        path: String,
        /// The number as the document carried it.
        lexical: String,
    },
}

impl fmt::Display for ValueConversionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LossyNumber {
                path,
                lexical,
                rendered,
            } => write!(f, "{path}: serde_json writes {lexical} as {rendered}"),
            Self::UnrepresentableNumber { path, lexical } => {
                write!(f, "{path}: serde_json holds no number {lexical}")
            }
        }
    }
}

impl std::error::Error for ValueConversionError {}

fn convert_number(
    number: &Number,
    path: &Path,
) -> Result<serde_json::Number, ValueConversionError> {
    let lexical = number.as_str();
    let converted = serde_json::Number::from_str(lexical).map_err(|_| {
        ValueConversionError::UnrepresentableNumber {
            path: path.location(),
            lexical: String::from(lexical),
        }
    })?;
    let rendered = converted.to_string();
    if rendered == lexical {
        return Ok(converted);
    }
    Err(ValueConversionError::LossyNumber {
        path: path.location(),
        lexical: String::from(lexical),
        rendered,
    })
}

fn convert_member(
    key: &str,
    member: Value,
    path: &mut Path,
) -> Result<serde_json::Value, ValueConversionError> {
    match member {
        Value::Array(items) => {
            let mut converted = Vec::with_capacity(items.len());
            for (index, item) in items.into_iter().enumerate() {
                converted.push(path.with_index(key, index, |path| item.into_serde_json(path))?);
            }
            Ok(serde_json::Value::Array(converted))
        }
        other => path.with(key, |path| other.into_serde_json(path)),
    }
}

impl From<i32> for Value {
    fn from(value: i32) -> Self {
        Self::Number(Number::from(value))
    }
}

impl From<u32> for Value {
    fn from(value: u32) -> Self {
        Self::Number(Number::from(value))
    }
}

impl serde::Serialize for Value {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Null => serializer.serialize_unit(),
            Self::Bool(flag) => serializer.serialize_bool(*flag),
            Self::Number(number) => serde::Serialize::serialize(number, serializer),
            Self::String(text) => serializer.serialize_str(text),
            Self::Array(items) => serde::Serialize::serialize(items, serializer),
            Self::Object(object) => serde::Serialize::serialize(object, serializer),
        }
    }
}

impl<'de> serde::Deserialize<'de> for Value {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = <Box<RawValue> as serde::Deserialize>::deserialize(deserializer)?;
        read_raw(raw.get(), 0).map_err(serde::de::Error::custom)
    }
}

/// How deeply a document may nest, the limit `serde_json` itself enforces
/// (<https://docs.rs/serde_json/1/serde_json/de/struct.Deserializer.html>).
const NESTING_LIMIT: usize = 128;

// NOTE: `RawValue` hands back the text of a value serde_json already validated
// (<https://docs.rs/serde_json/1/serde_json/value/struct.RawValue.html>), so the
// first byte names the kind and a number arrives with its precision intact.
fn read_raw(raw: &str, depth: usize) -> Result<Value, serde_json::Error> {
    let text = raw.trim();
    if depth > NESTING_LIMIT {
        return Err(serde::de::Error::custom("recursion limit exceeded"));
    }
    match text.as_bytes().first() {
        Some(b'{') => {
            let members: BTreeMap<String, Box<RawValue>> = serde_json::from_str(text)?;
            let mut object = Object::new();
            for (key, member) in members {
                object.insert(key, read_raw(member.get(), depth + 1)?);
            }
            Ok(Value::Object(object))
        }
        Some(b'[') => {
            let members: Vec<Box<RawValue>> = serde_json::from_str(text)?;
            let mut items = Vec::with_capacity(members.len());
            for member in members {
                items.push(read_raw(member.get(), depth + 1)?);
            }
            Ok(Value::Array(items))
        }
        Some(b'"') => Ok(Value::String(serde_json::from_str(text)?)),
        Some(b't' | b'f') => Ok(Value::Bool(serde_json::from_str(text)?)),
        Some(b'n') => Ok(Value::Null),
        _ => Ok(Value::Number(Number(String::from(text)))),
    }
}

/// Why a JSON document was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeErrorKind {
    /// A property the type does not define.
    UnknownProperty,
    /// A required property is absent.
    MissingProperty,
    /// The value has the wrong JSON type.
    WrongType {
        /// What the type expected.
        expected: &'static str,
    },
    /// A property appears with a shape its cardinality forbids (an array
    /// for a single element or the reverse).
    WrongCardinality,
    /// An object or array is empty.
    Empty,
    /// A number is out of range or not a whole number where one is required.
    BadNumber,
    /// The lexical form of a primitive is invalid.
    BadValue,
    /// Two forms of one choice element are both present.
    DuplicateChoice,
    /// `resourceType` is absent, not a string, or names another type.
    ResourceType,
    /// An XML element the type does not define.
    UnknownElement,
    /// Text where XML elements belong.
    UnexpectedText,
    /// An XML root element that is no resource of the version.
    WrongRoot,
    /// XML the parser refuses.
    MalformedXml {
        /// The parser's reason.
        reason: String,
    },
}

impl fmt::Display for DecodeErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownProperty => f.write_str("unknown property"),
            Self::MissingProperty => f.write_str("required property is missing"),
            Self::WrongType { expected } => write!(f, "expected {expected}"),
            Self::WrongCardinality => f.write_str("cardinality mismatch"),
            Self::Empty => f.write_str("empty object or array"),
            Self::BadNumber => f.write_str("number out of range"),
            Self::BadValue => f.write_str("invalid value"),
            Self::DuplicateChoice => f.write_str("more than one form of a choice element"),
            Self::ResourceType => f.write_str("resourceType is missing or does not match"),
            Self::UnknownElement => f.write_str("unknown element"),
            Self::UnexpectedText => f.write_str("text where an element belongs"),
            Self::WrongRoot => f.write_str("the root element is no resource of this version"),
            Self::MalformedXml { reason } => write!(f, "malformed XML: {reason}"),
        }
    }
}

/// A refused JSON document, located by its element path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodeError {
    /// The element path, for example `ValueSet.compose.include[2].system`.
    pub path: String,
    /// Why it was refused.
    pub kind: DecodeErrorKind,
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.path, self.kind)
    }
}

impl std::error::Error for DecodeError {}

/// The element path being decoded, for error reports.
#[derive(Debug, Default, Clone)]
pub struct Path {
    segments: Vec<String>,
    lenient: bool,
}

impl Path {
    /// A path starting at `root`.
    #[must_use]
    pub fn root(root: &str) -> Self {
        Self {
            segments: vec![root.to_owned()],
            lenient: false,
        }
    }

    /// A path starting at `root` that reads a required primitive stating no
    /// value as the value-less element it would be with only an extension.
    ///
    /// Cardinality is an aspect of validating a resource, which a server
    /// performs at its discretion, and an implementation "should be
    /// conservative in its sending behavior, and liberal in its receiving
    /// behavior" (<https://hl7.org/fhir/R4B/validation.html>). A reader that
    /// is handed a resource to use, rather than to store, takes this path so
    /// one absent element does not cost the whole request.
    #[must_use]
    pub fn lenient(root: &str) -> Self {
        Self {
            segments: vec![root.to_owned()],
            lenient: true,
        }
    }

    /// Whether this read tolerates a required primitive that states no value.
    #[must_use]
    pub const fn is_lenient(&self) -> bool {
        self.lenient
    }

    /// The dotted path, for example `Observation.valueQuantity.value`.
    #[must_use]
    pub fn location(&self) -> String {
        self.segments.join(".")
    }

    /// Runs `f` under `name`.
    ///
    /// # Errors
    ///
    /// Returns whatever `f` returns.
    pub fn with<T, E>(
        &mut self,
        name: &str,
        f: impl FnOnce(&mut Self) -> Result<T, E>,
    ) -> Result<T, E> {
        self.segments.push(name.to_owned());
        let out = f(self);
        self.segments.pop();
        out
    }

    /// Runs `f` under `name[index]`.
    ///
    /// # Errors
    ///
    /// Returns whatever `f` returns.
    pub fn with_index<T, E>(
        &mut self,
        name: &str,
        index: usize,
        f: impl FnOnce(&mut Self) -> Result<T, E>,
    ) -> Result<T, E> {
        self.segments.push(format!("{name}[{index}]"));
        let out = f(self);
        self.segments.pop();
        out
    }

    /// An error at the current path.
    #[must_use]
    pub fn error(&self, kind: DecodeErrorKind) -> DecodeError {
        DecodeError {
            path: self.location(),
            kind,
        }
    }
}

/// A type with a FHIR JSON representation as an object.
pub trait Json: Sized {
    /// The JSON object.
    ///
    /// # Errors
    ///
    /// Returns [`EncodeError`] when a held value has no JSON form.
    fn to_json(&self) -> Result<Object, EncodeError>;

    /// Decodes `object`, refusing unknown properties.
    ///
    /// # Errors
    ///
    /// Returns [`DecodeError`] for any deviation from the type's definition.
    fn from_json(object: &Object, path: &mut Path) -> Result<Self, DecodeError>;
}

/// Decodes a resource straight into a box.
///
/// The resource enum matches over every resource type its features select, and
/// a decoded resource is a large value, so building each one inside the match
/// would size that one stack frame for the whole set. This call keeps each
/// value in its own frame.
///
/// # Errors
///
/// Returns [`DecodeError`] for any deviation from the type's definition.
#[inline(never)]
pub fn boxed<T: Json>(object: &Object, path: &mut Path) -> Result<Box<T>, DecodeError> {
    Ok(Box::new(T::from_json(object, path)?))
}

/// A FHIR primitive: a JSON value plus an optional element object.
pub trait Primitive: Sized {
    /// The JSON value, `None` when only `id` or `extension` are present.
    ///
    /// # Errors
    ///
    /// Returns [`EncodeError`] when the held value has no JSON form.
    fn value_json(&self) -> Result<Option<Value>, EncodeError>;

    /// The `_name` object, `None` when the primitive has no `id` or `extension`.
    ///
    /// # Errors
    ///
    /// Returns [`EncodeError`] when an extension value has no JSON form.
    fn element_json(&self) -> Result<Option<Value>, EncodeError>;

    /// Decodes the value and its `_name` sibling.
    ///
    /// # Errors
    ///
    /// Returns [`DecodeError`] when both parts are absent or either is malformed.
    fn from_json_parts(
        value: Option<&Value>,
        element: Option<&Value>,
        path: &mut Path,
    ) -> Result<Self, DecodeError>;

    /// Whether the primitive carries a value.
    fn has_value(&self) -> bool;

    /// Whether the primitive carries an `id` or an `extension`.
    fn has_element(&self) -> bool;

    /// Writes the value, `null` when the primitive carries none.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error, which for a decimal includes a lexical
    /// form that is no JSON number.
    fn serialize_value<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;

    /// Writes the `_name` object, `null` when the primitive carries no `id`
    /// and no `extension`.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error.
    fn serialize_element<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
}

/// A primitive's value, written straight to a serializer.
///
/// This wrapper and the three below carry a primitive into `serde`, so a
/// generated type writes it as a map entry without building a [`Value`] first.
#[derive(Debug)]
pub struct PrimitiveValue<'a, P: Primitive>(pub &'a P);

impl<P: Primitive> serde::Serialize for PrimitiveValue<'_, P> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize_value(serializer)
    }
}

/// A primitive's `_name` object, written straight to a serializer.
#[derive(Debug)]
pub struct PrimitiveElement<'a, P: Primitive>(pub &'a P);

impl<P: Primitive> serde::Serialize for PrimitiveElement<'_, P> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize_element(serializer)
    }
}

/// The value array of a repeating primitive, `null` at a position that carries
/// only an `id` or an `extension`.
#[derive(Debug)]
pub struct PrimitiveValues<'a, P: Primitive>(pub &'a [P]);

impl<P: Primitive> serde::Serialize for PrimitiveValues<'_, P> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serde::Serializer::serialize_seq(serializer, Some(self.0.len()))?;
        for item in self.0 {
            serde::ser::SerializeSeq::serialize_element(&mut seq, &PrimitiveValue(item))?;
        }
        serde::ser::SerializeSeq::end(seq)
    }
}

/// The `_name` array of a repeating primitive, `null` at a position that
/// carries no `id` and no `extension`.
#[derive(Debug)]
pub struct PrimitiveElements<'a, P: Primitive>(pub &'a [P]);

impl<P: Primitive> serde::Serialize for PrimitiveElements<'_, P> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serde::Serializer::serialize_seq(serializer, Some(self.0.len()))?;
        for item in self.0 {
            serde::ser::SerializeSeq::serialize_element(&mut seq, &PrimitiveElement(item))?;
        }
        serde::ser::SerializeSeq::end(seq)
    }
}

/// Writes `key` with the primitive's value, unless it carries none.
///
/// # Errors
///
/// Returns the serializer's error.
pub fn value_entry<M: serde::ser::SerializeMap, P: Primitive>(
    map: &mut M,
    key: &str,
    primitive: &P,
) -> Result<(), M::Error> {
    if primitive.has_value() {
        map.serialize_entry(key, &PrimitiveValue(primitive))?;
    }
    Ok(())
}

/// Writes `key` with the primitive's `_name` object, unless it carries no
/// `id` and no `extension`.
///
/// # Errors
///
/// Returns the serializer's error.
pub fn element_entry<M: serde::ser::SerializeMap, P: Primitive>(
    map: &mut M,
    key: &str,
    primitive: &P,
) -> Result<(), M::Error> {
    if primitive.has_element() {
        map.serialize_entry(key, &PrimitiveElement(primitive))?;
    }
    Ok(())
}

/// Writes `key` with the value array of a repeating primitive, unless the list
/// is empty.
///
/// # Errors
///
/// Returns the serializer's error.
pub fn value_list_entry<M: serde::ser::SerializeMap, P: Primitive>(
    map: &mut M,
    key: &str,
    items: &[P],
) -> Result<(), M::Error> {
    if !items.is_empty() {
        map.serialize_entry(key, &PrimitiveValues(items))?;
    }
    Ok(())
}

/// Writes `key` with the `_name` array of a repeating primitive, when any
/// position carries an `id` or an `extension`.
///
/// # Errors
///
/// Returns the serializer's error.
pub fn element_list_entry<M: serde::ser::SerializeMap, P: Primitive>(
    map: &mut M,
    key: &str,
    items: &[P],
) -> Result<(), M::Error> {
    if items.iter().any(Primitive::has_element) {
        map.serialize_entry(key, &PrimitiveElements(items))?;
    }
    Ok(())
}

/// Reads a non-empty JSON object.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not an object or is empty.
pub fn expect_object<'a>(value: &'a Value, path: &Path) -> Result<&'a Object, DecodeError> {
    match value {
        Value::Object(object) if object.is_empty() => Err(path.error(DecodeErrorKind::Empty)),
        Value::Object(object) => Ok(object),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "an object",
        })),
    }
}

/// Reads a non-empty JSON array.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not an array or is empty.
pub fn expect_array<'a>(value: &'a Value, path: &Path) -> Result<&'a [Value], DecodeError> {
    match value {
        Value::Array(items) if items.is_empty() => Err(path.error(DecodeErrorKind::Empty)),
        Value::Array(items) => Ok(items),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "an array",
        })),
    }
}

/// Refuses an array where a single value is expected.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is an array.
pub fn expect_single<'a>(value: &'a Value, path: &Path) -> Result<&'a Value, DecodeError> {
    match value {
        Value::Array(_) => Err(path.error(DecodeErrorKind::WrongCardinality)),
        other => Ok(other),
    }
}

/// Reads a JSON string.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not a string.
pub fn expect_string(value: &Value, path: &Path) -> Result<String, DecodeError> {
    match value {
        Value::String(s) => Ok(s.clone()),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "a string",
        })),
    }
}

/// Reads a JSON boolean.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not a boolean.
pub fn expect_bool(value: &Value, path: &Path) -> Result<bool, DecodeError> {
    match value {
        Value::Bool(b) => Ok(*b),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "a boolean",
        })),
    }
}

/// Reads a JSON number as an `i32`.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not a whole number in range.
pub fn expect_i32(value: &Value, path: &Path) -> Result<i32, DecodeError> {
    match value {
        Value::Number(n) => n
            .as_i64()
            .and_then(|i| i32::try_from(i).ok())
            .ok_or_else(|| path.error(DecodeErrorKind::BadNumber)),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "a number",
        })),
    }
}

/// Reads a JSON number as a `u32`, at least `min`.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not a whole number in range.
pub fn expect_u32(value: &Value, min: u32, path: &Path) -> Result<u32, DecodeError> {
    match value {
        Value::Number(n) => n
            .as_u64()
            .and_then(|u| u32::try_from(u).ok())
            .filter(|u| *u >= min)
            .ok_or_else(|| path.error(DecodeErrorKind::BadNumber)),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "a number",
        })),
    }
}

/// Reads a 64-bit integer carried as a JSON string (the R5 `integer64` form).
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not a string holding an integer.
pub fn expect_i64_string(value: &Value, path: &Path) -> Result<i64, DecodeError> {
    match value {
        Value::String(s) => s
            .parse()
            .map_err(|_| path.error(DecodeErrorKind::BadNumber)),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "a string holding an integer",
        })),
    }
}

/// Reads a JSON number keeping its lexical form, for the FHIR decimal.
///
/// # Errors
///
/// Returns [`DecodeError`] when `value` is not a number.
pub fn expect_decimal(value: &Value, path: &Path) -> Result<String, DecodeError> {
    match value {
        Value::Number(n) => Ok(String::from(n.as_str())),
        _ => Err(path.error(DecodeErrorKind::WrongType {
            expected: "a number",
        })),
    }
}

/// A decimal's lexical form as a JSON number.
///
/// # Errors
///
/// Returns [`DecodeError`] when `text` is not a JSON number.
pub fn decimal_value(text: &str, path: &Path) -> Result<Value, DecodeError> {
    text.parse::<Number>()
        .map(Value::Number)
        .map_err(|_| path.error(DecodeErrorKind::BadValue))
}

/// One position of a repeating primitive: the value and its `_name` object.
pub type ValuePair<'a> = (Option<&'a Value>, Option<&'a Value>);

/// Pairs a repeating primitive's value array with its `_name` array.
///
/// # Errors
///
/// Returns [`DecodeError`] when either is not an array, is empty, or the
/// arrays differ in length.
pub fn pair_arrays<'a>(
    values: Option<&'a Value>,
    elements: Option<&'a Value>,
    path: &Path,
) -> Result<Vec<ValuePair<'a>>, DecodeError> {
    let values = values.map(|v| expect_array(v, path)).transpose()?;
    let elements = elements.map(|v| expect_array(v, path)).transpose()?;
    let len = match (values, elements) {
        (Some(v), Some(e)) if v.len() != e.len() => {
            return Err(path.error(DecodeErrorKind::WrongCardinality));
        }
        (Some(v), _) => v.len(),
        (None, Some(e)) => e.len(),
        (None, None) => 0,
    };
    Ok((0..len)
        .map(|i| {
            let value = values.and_then(|v| v.get(i)).filter(|v| !v.is_null());
            let element = elements.and_then(|e| e.get(i)).filter(|e| !e.is_null());
            (value, element)
        })
        .collect())
}

/// Serializes a list of primitives as the value array and, when any carries
/// an element object, the aligned `_name` array.
///
/// # Errors
///
/// Returns [`EncodeError`] when a held value has no JSON form.
pub fn primitive_arrays<P: Primitive>(items: &[P]) -> Result<(Value, Option<Value>), EncodeError> {
    let mut values = Vec::with_capacity(items.len());
    let mut elements = Vec::with_capacity(items.len());
    for item in items {
        values.push(item.value_json()?.unwrap_or(Value::Null));
        elements.push(item.element_json()?.unwrap_or(Value::Null));
    }
    let any_element = elements.iter().any(|e| !e.is_null());
    Ok((
        Value::Array(values),
        any_element.then_some(Value::Array(elements)),
    ))
}

/// Why a value could not be written as JSON.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EncodeError {
    /// A decimal's lexical form is not a JSON number.
    BadDecimal {
        /// The text that was held.
        text: String,
    },
    /// An unknown resource's body is not a JSON object.
    UnknownResourceBody,
    /// A value has no XML form, or the XML writer failed.
    Xml {
        /// What went wrong.
        reason: String,
    },
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadDecimal { text } => write!(f, "decimal {text:?} is not a JSON number"),
            Self::UnknownResourceBody => f.write_str("an unknown resource's body is not an object"),
            Self::Xml { reason } => write!(f, "no XML form: {reason}"),
        }
    }
}

impl std::error::Error for EncodeError {}

/// The parts of one choice element met while reading an object.
#[derive(Debug, Default)]
pub struct ChoiceSlot<'a> {
    /// The type suffix of the key seen, for example `String` for `valueString`.
    pub suffix: Option<&'static str>,
    /// The value part.
    pub value: Option<&'a Value>,
    /// The `_name` part.
    pub element: Option<&'a Value>,
}

impl<'a> ChoiceSlot<'a> {
    fn claim(&mut self, suffix: &'static str, path: &Path) -> Result<(), DecodeError> {
        match self.suffix {
            Some(seen) if seen != suffix => Err(path.error(DecodeErrorKind::DuplicateChoice)),
            _ => {
                self.suffix = Some(suffix);
                Ok(())
            }
        }
    }

    /// Records the value part of the form `suffix`.
    ///
    /// # Errors
    ///
    /// Returns [`DecodeError`] when another form was already seen.
    pub fn value(
        &mut self,
        suffix: &'static str,
        value: &'a Value,
        path: &Path,
    ) -> Result<(), DecodeError> {
        self.claim(suffix, path)?;
        self.value = Some(value);
        Ok(())
    }

    /// Records the `_name` part of the form `suffix`.
    ///
    /// # Errors
    ///
    /// Returns [`DecodeError`] when another form was already seen.
    pub fn element(
        &mut self,
        suffix: &'static str,
        element: &'a Value,
        path: &Path,
    ) -> Result<(), DecodeError> {
        self.claim(suffix, path)?;
        self.element = Some(element);
        Ok(())
    }
}

/// The `resourceType` of an object, for dispatch.
///
/// # Errors
///
/// Returns [`DecodeError`] when the property is absent or not a string.
pub fn resource_type<'a>(object: &'a Object, path: &Path) -> Result<&'a str, DecodeError> {
    match object.get("resourceType") {
        Some(Value::String(name)) => Ok(name),
        _ => Err(path.error(DecodeErrorKind::ResourceType)),
    }
}