Skip to main content

fhir_types/r6/
timing.rs

1// @generated by fhir-codegen from hl7.fhir.r6.core 6.0.0-ballot5. DO NOT EDIT.
2// Change the emitter (tools/fhir-codegen) and regenerate.
3// SPDX-FileCopyrightText: Cadasto B.V.
4// SPDX-License-Identifier: Apache-2.0
5//! A timing schedule that specifies an event that may occur multiple times
6
7/// A timing schedule that specifies an event that may occur multiple times
8///
9/// Specifies an event that may occur multiple times. Timing schedules are used
10/// to record when things are planned, expected or requested to occur. The most
11/// common usage is in dosage instructions for medications. They are also used
12/// when planning care of various kinds, and may be used for reporting the
13/// schedule to which past regular activities were carried out.
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct Timing {
16    /// Unique id for inter-element referencing
17    ///
18    /// Unique id for the element within a resource (for internal references). This
19    /// may be any string value that does not contain spaces.
20    pub id: Option<std::string::String>,
21    /// Additional content defined by implementations
22    ///
23    /// May be used to represent additional information that is not part of the
24    /// basic definition of the element. To make the use of extensions safe and
25    /// managable, there is a strict set of governance applied to the definition and
26    /// use of extensions. Though any implementer can define an extension, there is
27    /// a set of requirements that SHALL be met as part of the definition of the
28    /// extension.
29    pub extension: Vec<super::extension::Extension>,
30    /// Extensions that cannot be ignored even if unrecognized
31    ///
32    /// May be used to represent additional information that is not part of the
33    /// basic definition of the element and that modifies the understanding of the
34    /// element in which it is contained and/or the understanding of the containing
35    /// element's descendants. Usually modifier elements provide negation or
36    /// qualification. To make the use of extensions safe and managable, there is a
37    /// strict set of governance applied to the definition and use of extensions.
38    /// Though any implementer can define an extension, there is a set of
39    /// requirements that SHALL be met as part of the definition of the extension.
40    /// Applications processing a resource are required to check for modifier
41    /// extensions. Modifier extensions SHALL NOT change the meaning of any elements
42    /// on Resource or DomainResource (including cannot change the meaning of
43    /// modifierExtension itself).
44    pub modifier_extension: Vec<super::extension::Extension>,
45    /// When the event occurs
46    ///
47    /// Identifies specific times when the event occurs.
48    pub event: Vec<super::primitives::DateTime>,
49    /// When the event is to occur
50    ///
51    /// A set of rules that describe when the event is scheduled.
52    pub repeat: Option<TimingRepeat>,
53    /// C | BID | TID | QID | AM | PM | QD | QOD | +
54    ///
55    /// A code for the timing schedule (or just text in code.text). Some codes such
56    /// as BID are ubiquitous, but many institutions define their own additional
57    /// codes. If a code is provided, the code is understood to be a complete
58    /// statement of whatever is specified in the structured timing data, and either
59    /// the code or the data may be used to interpret the Timing, with the exception
60    /// that .repeat.bounds still applies over the code (and is not contained in the
61    /// code).
62    pub code: Option<super::codeable_concept::CodeableConcept>,
63}
64
65impl super::super::codec::Json for Timing {
66    fn to_json(&self) -> Result<super::super::codec::Object, super::super::codec::EncodeError> {
67        let mut object = super::super::codec::Object::new();
68        if let Some(v) = &self.id {
69            object.insert(
70                std::string::String::from("id"),
71                super::super::codec::Value::String(v.clone()),
72            );
73        }
74        if !self.extension.is_empty() {
75            let mut items = Vec::with_capacity(self.extension.len());
76            for item in &self.extension {
77                items.push(super::super::codec::Value::Object(
78                    super::super::codec::Json::to_json(item)?,
79                ));
80            }
81            object.insert(
82                std::string::String::from("extension"),
83                super::super::codec::Value::Array(items),
84            );
85        }
86        if !self.modifier_extension.is_empty() {
87            let mut items = Vec::with_capacity(self.modifier_extension.len());
88            for item in &self.modifier_extension {
89                items.push(super::super::codec::Value::Object(
90                    super::super::codec::Json::to_json(item)?,
91                ));
92            }
93            object.insert(
94                std::string::String::from("modifierExtension"),
95                super::super::codec::Value::Array(items),
96            );
97        }
98        if !self.event.is_empty() {
99            let (values, elements) = super::super::codec::primitive_arrays(&self.event)?;
100            if let Some(values) = values {
101                object.insert(std::string::String::from("event"), values);
102            }
103            if let Some(elements) = elements {
104                object.insert(std::string::String::from("_event"), elements);
105            }
106        }
107        if let Some(item) = &self.repeat {
108            object.insert(
109                std::string::String::from("repeat"),
110                super::super::codec::Value::Object(super::super::codec::Json::to_json(item)?),
111            );
112        }
113        if let Some(item) = &self.code {
114            object.insert(
115                std::string::String::from("code"),
116                super::super::codec::Value::Object(super::super::codec::Json::to_json(item)?),
117            );
118        }
119        Ok(object)
120    }
121
122    fn from_json(
123        object: &super::super::codec::Object,
124        path: &mut super::super::codec::Path,
125    ) -> Result<Self, super::super::codec::DecodeError> {
126        let mut raw_id: Option<&super::super::codec::Value> = None;
127        let mut raw_extension: Option<&super::super::codec::Value> = None;
128        let mut raw_modifier_extension: Option<&super::super::codec::Value> = None;
129        let mut raw_event: Option<&super::super::codec::Value> = None;
130        let mut raw_event_element: Option<&super::super::codec::Value> = None;
131        let mut raw_repeat: Option<&super::super::codec::Value> = None;
132        let mut raw_code: Option<&super::super::codec::Value> = None;
133        for (key, value) in object {
134            match key.as_str() {
135                "id" => {
136                    raw_id = Some(value);
137                }
138                "extension" => {
139                    raw_extension = Some(value);
140                }
141                "modifierExtension" => {
142                    raw_modifier_extension = Some(value);
143                }
144                "event" => {
145                    raw_event = Some(value);
146                }
147                "_event" => {
148                    raw_event_element = Some(value);
149                }
150                "repeat" => {
151                    raw_repeat = Some(value);
152                }
153                "code" => {
154                    raw_code = Some(value);
155                }
156                other => {
157                    return path.with(other, |path| {
158                        Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
159                    });
160                }
161            }
162        }
163        let field_id = raw_id
164            .map(|value| {
165                path.with("id", |path| {
166                    let value = super::super::codec::expect_single(value, path)?;
167                    super::primitives::checked_string(
168                        super::super::codec::expect_string(value, path)?,
169                        path,
170                    )
171                })
172            })
173            .transpose()?;
174        let mut field_extension = Vec::new();
175        if let Some(raw) = raw_extension {
176            for (index, value) in path
177                .with("extension", |path| {
178                    super::super::codec::expect_array(raw, path)
179                })?
180                .iter()
181                .enumerate()
182            {
183                field_extension.push(path.with_index("extension", index, |path| {
184                    super::super::codec::Json::from_json(
185                        super::super::codec::expect_object(value, path)?,
186                        path,
187                    )
188                })?);
189            }
190        }
191        let mut field_modifier_extension = Vec::new();
192        if let Some(raw) = raw_modifier_extension {
193            for (index, value) in path
194                .with("modifierExtension", |path| {
195                    super::super::codec::expect_array(raw, path)
196                })?
197                .iter()
198                .enumerate()
199            {
200                field_modifier_extension.push(path.with_index(
201                    "modifierExtension",
202                    index,
203                    |path| {
204                        super::super::codec::Json::from_json(
205                            super::super::codec::expect_object(value, path)?,
206                            path,
207                        )
208                    },
209                )?);
210            }
211        }
212        let mut field_event = Vec::new();
213        for (index, (value, element)) in path
214            .with("event", |path| {
215                super::super::codec::pair_arrays(raw_event, raw_event_element, path)
216            })?
217            .into_iter()
218            .enumerate()
219        {
220            field_event.push(path.with_index("event", index, |path| {
221                super::super::codec::Primitive::from_json_parts(value, element, path)
222            })?);
223        }
224        let field_repeat = raw_repeat
225            .map(|value| {
226                path.with("repeat", |path| {
227                    super::super::codec::Json::from_json(
228                        super::super::codec::expect_object(
229                            super::super::codec::expect_single(value, path)?,
230                            path,
231                        )?,
232                        path,
233                    )
234                })
235            })
236            .transpose()?;
237        let field_code = raw_code
238            .map(|value| {
239                path.with("code", |path| {
240                    super::super::codec::Json::from_json(
241                        super::super::codec::expect_object(
242                            super::super::codec::expect_single(value, path)?,
243                            path,
244                        )?,
245                        path,
246                    )
247                })
248            })
249            .transpose()?;
250        Ok(Self {
251            id: field_id,
252            extension: field_extension,
253            modifier_extension: field_modifier_extension,
254            event: field_event,
255            repeat: field_repeat,
256            code: field_code,
257        })
258    }
259}
260
261impl serde::Serialize for Timing {
262    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
263        let mut map = serde::Serializer::serialize_map(serializer, None)?;
264        super::super::codec::element_list_entry(&mut map, "_event", &self.event)?;
265        if let Some(item) = &self.code {
266            serde::ser::SerializeMap::serialize_entry(&mut map, "code", item)?;
267        }
268        super::super::codec::value_list_entry(&mut map, "event", &self.event)?;
269        if !self.extension.is_empty() {
270            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
271        }
272        if let Some(v) = &self.id {
273            serde::ser::SerializeMap::serialize_entry(&mut map, "id", v)?;
274        }
275        if !self.modifier_extension.is_empty() {
276            serde::ser::SerializeMap::serialize_entry(
277                &mut map,
278                "modifierExtension",
279                &self.modifier_extension,
280            )?;
281        }
282        if let Some(item) = &self.repeat {
283            serde::ser::SerializeMap::serialize_entry(&mut map, "repeat", item)?;
284        }
285        serde::ser::SerializeMap::end(map)
286    }
287}
288
289impl<'de> serde::Deserialize<'de> for Timing {
290    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
291        let value = <super::super::codec::Value as serde::Deserialize>::deserialize(deserializer)?;
292        let mut path = super::super::codec::Path::root("Timing");
293        let object =
294            super::super::codec::expect_object(&value, &path).map_err(serde::de::Error::custom)?;
295        super::super::codec::Json::from_json(object, &mut path).map_err(serde::de::Error::custom)
296    }
297}
298
299/// When the event is to occur
300///
301/// A set of rules that describe when the event is scheduled.
302#[derive(Debug, Clone, Default, PartialEq, Eq)]
303pub struct TimingRepeat {
304    /// Unique id for inter-element referencing
305    ///
306    /// Unique id for the element within a resource (for internal references). This
307    /// may be any string value that does not contain spaces.
308    pub id: Option<std::string::String>,
309    /// Additional content defined by implementations
310    ///
311    /// May be used to represent additional information that is not part of the
312    /// basic definition of the element. To make the use of extensions safe and
313    /// managable, there is a strict set of governance applied to the definition and
314    /// use of extensions. Though any implementer can define an extension, there is
315    /// a set of requirements that SHALL be met as part of the definition of the
316    /// extension.
317    pub extension: Vec<super::extension::Extension>,
318    /// Length/Range of lengths, or (Start and/or end) limits
319    ///
320    /// Either a duration for the length of the timing schedule, a range of possible
321    /// length, or outer bounds for start and/or end limits of the timing schedule.
322    pub bounds: Option<TimingRepeatBounds>,
323    /// Number of times to repeat
324    ///
325    /// A total count of the desired number of repetitions across the duration of
326    /// the entire timing specification. If countMax is present, this element
327    /// indicates the lower bound of the allowed range of count values.
328    pub count: Option<super::primitives::PositiveInt>,
329    /// Maximum number of times to repeat
330    ///
331    /// If present, indicates that the count is a range - so to perform the action
332    /// between \[count\] and \[countMax\] times.
333    pub count_max: Option<super::primitives::PositiveInt>,
334    /// How long when it happens
335    ///
336    /// How long this thing happens for when it happens. If durationMax is present,
337    /// this element indicates the lower bound of the allowed range of the duration.
338    pub duration: Option<super::primitives::Decimal>,
339    /// How long when it happens (Max)
340    ///
341    /// If present, indicates that the duration is a range - so to perform the
342    /// action between \[duration\] and \[durationMax\] time length.
343    pub duration_max: Option<super::primitives::Decimal>,
344    /// s | min | h | d | wk | mo | a - unit of time (UCUM)
345    ///
346    /// The units of time for the duration, in UCUM units Normal practice is to use
347    /// the 'mo' code as a calendar month when calculating the next occurrence.
348    pub duration_unit: Option<super::primitives::Code>,
349    /// Indicates the number of repetitions that should occur within a period. I.e.
350    /// Event occurs frequency times per period
351    ///
352    /// The number of times to repeat the action within the specified period. If
353    /// frequencyMax is present, this element indicates the lower bound of the
354    /// allowed range of the frequency.
355    pub frequency: Option<super::primitives::PositiveInt>,
356    /// Event occurs up to frequencyMax times per period
357    ///
358    /// If present, indicates that the frequency is a range - so to repeat between
359    /// \[frequency\] and \[frequencyMax\] times within the period or period range.
360    pub frequency_max: Option<super::primitives::PositiveInt>,
361    /// The duration to which the frequency applies. I.e. Event occurs frequency
362    /// times per period
363    ///
364    /// Indicates the duration of time over which repetitions are to occur; e.g. to
365    /// express "3 times per day", 3 would be the frequency and "1 day" would be the
366    /// period. If periodMax is present, this element indicates the lower bound of
367    /// the allowed range of the period length.
368    pub period: Option<super::primitives::Decimal>,
369    /// Upper limit of period (3-4 hours)
370    ///
371    /// If present, indicates that the period is a range from \[period\] to
372    /// \[periodMax\], allowing expressing concepts such as "do this once every 3-5
373    /// days.
374    pub period_max: Option<super::primitives::Decimal>,
375    /// s | min | h | d | wk | mo | a - unit of time (UCUM)
376    ///
377    /// The units of time for the period in UCUM units Normal practice is to use the
378    /// 'mo' code as a calendar month when calculating the next occurrence.
379    pub period_unit: Option<super::primitives::Code>,
380    /// Events within the repeat period do not start until startOffset has elapsed
381    ///
382    /// Indicates that the events within the period of the repeat do not start until
383    /// startOffset has elapsed. Requires both frequency and period to define the
384    /// repeat cycle. See notes: Periods with start or end offsets.
385    pub start_offset: Option<super::quantity::Quantity>,
386    /// Events within the repeat period stop once endOffset before the end of the
387    /// period
388    ///
389    /// Indicates that the events within the period of the repeat stop endOffset
390    /// before the period ends. Requires both frequency and period to define the
391    /// repeat cycle. See notes: Periods with start or end offsets.
392    pub end_offset: Option<super::quantity::Quantity>,
393    /// mon | tue | wed | thu | fri | sat | sun
394    ///
395    /// If one or more days of week is provided, then the action happens only on the
396    /// specified day(s).
397    pub day_of_week: Vec<super::primitives::Code>,
398    /// Time of day for action
399    ///
400    /// Specified time of day for action to take place.
401    pub time_of_day: Vec<super::primitives::Time>,
402    /// Code for time period of occurrence
403    ///
404    /// An approximate time period during the day, potentially linked to an event of
405    /// daily living that indicates when the action should occur.
406    pub when: Vec<super::primitives::Code>,
407    /// Minutes from event (before or after)
408    ///
409    /// The number of minutes from the event. If the event code does not indicate
410    /// whether the minutes is before or after the event, then the offset is assumed
411    /// to be after the event.
412    pub offset: Option<super::primitives::UnsignedInt>,
413}
414
415impl super::super::codec::Json for TimingRepeat {
416    fn to_json(&self) -> Result<super::super::codec::Object, super::super::codec::EncodeError> {
417        let mut object = super::super::codec::Object::new();
418        if let Some(v) = &self.id {
419            object.insert(
420                std::string::String::from("id"),
421                super::super::codec::Value::String(v.clone()),
422            );
423        }
424        if !self.extension.is_empty() {
425            let mut items = Vec::with_capacity(self.extension.len());
426            for item in &self.extension {
427                items.push(super::super::codec::Value::Object(
428                    super::super::codec::Json::to_json(item)?,
429                ));
430            }
431            object.insert(
432                std::string::String::from("extension"),
433                super::super::codec::Value::Array(items),
434            );
435        }
436        if let Some(item) = &self.bounds {
437            let (suffix, value, element) = item.to_json_parts()?;
438            if let Some(value) = value {
439                object.insert(format!("bounds{suffix}"), value);
440            }
441            if let Some(element) = element {
442                object.insert(format!("_bounds{suffix}"), element);
443            }
444        }
445        if let Some(item) = &self.count {
446            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
447                object.insert(std::string::String::from("count"), v);
448            }
449            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
450                object.insert(std::string::String::from("_count"), e);
451            }
452        }
453        if let Some(item) = &self.count_max {
454            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
455                object.insert(std::string::String::from("countMax"), v);
456            }
457            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
458                object.insert(std::string::String::from("_countMax"), e);
459            }
460        }
461        if let Some(item) = &self.duration {
462            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
463                object.insert(std::string::String::from("duration"), v);
464            }
465            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
466                object.insert(std::string::String::from("_duration"), e);
467            }
468        }
469        if let Some(item) = &self.duration_max {
470            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
471                object.insert(std::string::String::from("durationMax"), v);
472            }
473            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
474                object.insert(std::string::String::from("_durationMax"), e);
475            }
476        }
477        if let Some(item) = &self.duration_unit {
478            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
479                object.insert(std::string::String::from("durationUnit"), v);
480            }
481            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
482                object.insert(std::string::String::from("_durationUnit"), e);
483            }
484        }
485        if let Some(item) = &self.frequency {
486            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
487                object.insert(std::string::String::from("frequency"), v);
488            }
489            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
490                object.insert(std::string::String::from("_frequency"), e);
491            }
492        }
493        if let Some(item) = &self.frequency_max {
494            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
495                object.insert(std::string::String::from("frequencyMax"), v);
496            }
497            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
498                object.insert(std::string::String::from("_frequencyMax"), e);
499            }
500        }
501        if let Some(item) = &self.period {
502            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
503                object.insert(std::string::String::from("period"), v);
504            }
505            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
506                object.insert(std::string::String::from("_period"), e);
507            }
508        }
509        if let Some(item) = &self.period_max {
510            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
511                object.insert(std::string::String::from("periodMax"), v);
512            }
513            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
514                object.insert(std::string::String::from("_periodMax"), e);
515            }
516        }
517        if let Some(item) = &self.period_unit {
518            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
519                object.insert(std::string::String::from("periodUnit"), v);
520            }
521            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
522                object.insert(std::string::String::from("_periodUnit"), e);
523            }
524        }
525        if let Some(item) = &self.start_offset {
526            object.insert(
527                std::string::String::from("startOffset"),
528                super::super::codec::Value::Object(super::super::codec::Json::to_json(item)?),
529            );
530        }
531        if let Some(item) = &self.end_offset {
532            object.insert(
533                std::string::String::from("endOffset"),
534                super::super::codec::Value::Object(super::super::codec::Json::to_json(item)?),
535            );
536        }
537        if !self.day_of_week.is_empty() {
538            let (values, elements) = super::super::codec::primitive_arrays(&self.day_of_week)?;
539            if let Some(values) = values {
540                object.insert(std::string::String::from("dayOfWeek"), values);
541            }
542            if let Some(elements) = elements {
543                object.insert(std::string::String::from("_dayOfWeek"), elements);
544            }
545        }
546        if !self.time_of_day.is_empty() {
547            let (values, elements) = super::super::codec::primitive_arrays(&self.time_of_day)?;
548            if let Some(values) = values {
549                object.insert(std::string::String::from("timeOfDay"), values);
550            }
551            if let Some(elements) = elements {
552                object.insert(std::string::String::from("_timeOfDay"), elements);
553            }
554        }
555        if !self.when.is_empty() {
556            let (values, elements) = super::super::codec::primitive_arrays(&self.when)?;
557            if let Some(values) = values {
558                object.insert(std::string::String::from("when"), values);
559            }
560            if let Some(elements) = elements {
561                object.insert(std::string::String::from("_when"), elements);
562            }
563        }
564        if let Some(item) = &self.offset {
565            if let Some(v) = super::super::codec::Primitive::value_json(item)? {
566                object.insert(std::string::String::from("offset"), v);
567            }
568            if let Some(e) = super::super::codec::Primitive::element_json(item)? {
569                object.insert(std::string::String::from("_offset"), e);
570            }
571        }
572        Ok(object)
573    }
574
575    fn from_json(
576        object: &super::super::codec::Object,
577        path: &mut super::super::codec::Path,
578    ) -> Result<Self, super::super::codec::DecodeError> {
579        let mut raw_id: Option<&super::super::codec::Value> = None;
580        let mut raw_extension: Option<&super::super::codec::Value> = None;
581        let mut raw_bounds = super::super::codec::ChoiceSlot::default();
582        let mut raw_count: Option<&super::super::codec::Value> = None;
583        let mut raw_count_element: Option<&super::super::codec::Value> = None;
584        let mut raw_count_max: Option<&super::super::codec::Value> = None;
585        let mut raw_count_max_element: Option<&super::super::codec::Value> = None;
586        let mut raw_duration: Option<&super::super::codec::Value> = None;
587        let mut raw_duration_element: Option<&super::super::codec::Value> = None;
588        let mut raw_duration_max: Option<&super::super::codec::Value> = None;
589        let mut raw_duration_max_element: Option<&super::super::codec::Value> = None;
590        let mut raw_duration_unit: Option<&super::super::codec::Value> = None;
591        let mut raw_duration_unit_element: Option<&super::super::codec::Value> = None;
592        let mut raw_frequency: Option<&super::super::codec::Value> = None;
593        let mut raw_frequency_element: Option<&super::super::codec::Value> = None;
594        let mut raw_frequency_max: Option<&super::super::codec::Value> = None;
595        let mut raw_frequency_max_element: Option<&super::super::codec::Value> = None;
596        let mut raw_period: Option<&super::super::codec::Value> = None;
597        let mut raw_period_element: Option<&super::super::codec::Value> = None;
598        let mut raw_period_max: Option<&super::super::codec::Value> = None;
599        let mut raw_period_max_element: Option<&super::super::codec::Value> = None;
600        let mut raw_period_unit: Option<&super::super::codec::Value> = None;
601        let mut raw_period_unit_element: Option<&super::super::codec::Value> = None;
602        let mut raw_start_offset: Option<&super::super::codec::Value> = None;
603        let mut raw_end_offset: Option<&super::super::codec::Value> = None;
604        let mut raw_day_of_week: Option<&super::super::codec::Value> = None;
605        let mut raw_day_of_week_element: Option<&super::super::codec::Value> = None;
606        let mut raw_time_of_day: Option<&super::super::codec::Value> = None;
607        let mut raw_time_of_day_element: Option<&super::super::codec::Value> = None;
608        let mut raw_when: Option<&super::super::codec::Value> = None;
609        let mut raw_when_element: Option<&super::super::codec::Value> = None;
610        let mut raw_offset: Option<&super::super::codec::Value> = None;
611        let mut raw_offset_element: Option<&super::super::codec::Value> = None;
612        for (key, value) in object {
613            match key.as_str() {
614                "id" => {
615                    raw_id = Some(value);
616                }
617                "extension" => {
618                    raw_extension = Some(value);
619                }
620                "boundsDuration" => {
621                    raw_bounds.value("Duration", value, path)?;
622                }
623                "_boundsDuration" => {
624                    raw_bounds.element("Duration", value, path)?;
625                }
626                "boundsRange" => {
627                    raw_bounds.value("Range", value, path)?;
628                }
629                "_boundsRange" => {
630                    raw_bounds.element("Range", value, path)?;
631                }
632                "boundsPeriod" => {
633                    raw_bounds.value("Period", value, path)?;
634                }
635                "_boundsPeriod" => {
636                    raw_bounds.element("Period", value, path)?;
637                }
638                "count" => {
639                    raw_count = Some(value);
640                }
641                "_count" => {
642                    raw_count_element = Some(value);
643                }
644                "countMax" => {
645                    raw_count_max = Some(value);
646                }
647                "_countMax" => {
648                    raw_count_max_element = Some(value);
649                }
650                "duration" => {
651                    raw_duration = Some(value);
652                }
653                "_duration" => {
654                    raw_duration_element = Some(value);
655                }
656                "durationMax" => {
657                    raw_duration_max = Some(value);
658                }
659                "_durationMax" => {
660                    raw_duration_max_element = Some(value);
661                }
662                "durationUnit" => {
663                    raw_duration_unit = Some(value);
664                }
665                "_durationUnit" => {
666                    raw_duration_unit_element = Some(value);
667                }
668                "frequency" => {
669                    raw_frequency = Some(value);
670                }
671                "_frequency" => {
672                    raw_frequency_element = Some(value);
673                }
674                "frequencyMax" => {
675                    raw_frequency_max = Some(value);
676                }
677                "_frequencyMax" => {
678                    raw_frequency_max_element = Some(value);
679                }
680                "period" => {
681                    raw_period = Some(value);
682                }
683                "_period" => {
684                    raw_period_element = Some(value);
685                }
686                "periodMax" => {
687                    raw_period_max = Some(value);
688                }
689                "_periodMax" => {
690                    raw_period_max_element = Some(value);
691                }
692                "periodUnit" => {
693                    raw_period_unit = Some(value);
694                }
695                "_periodUnit" => {
696                    raw_period_unit_element = Some(value);
697                }
698                "startOffset" => {
699                    raw_start_offset = Some(value);
700                }
701                "endOffset" => {
702                    raw_end_offset = Some(value);
703                }
704                "dayOfWeek" => {
705                    raw_day_of_week = Some(value);
706                }
707                "_dayOfWeek" => {
708                    raw_day_of_week_element = Some(value);
709                }
710                "timeOfDay" => {
711                    raw_time_of_day = Some(value);
712                }
713                "_timeOfDay" => {
714                    raw_time_of_day_element = Some(value);
715                }
716                "when" => {
717                    raw_when = Some(value);
718                }
719                "_when" => {
720                    raw_when_element = Some(value);
721                }
722                "offset" => {
723                    raw_offset = Some(value);
724                }
725                "_offset" => {
726                    raw_offset_element = Some(value);
727                }
728                other => {
729                    return path.with(other, |path| {
730                        Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty))
731                    });
732                }
733            }
734        }
735        let field_id = raw_id
736            .map(|value| {
737                path.with("id", |path| {
738                    let value = super::super::codec::expect_single(value, path)?;
739                    super::primitives::checked_string(
740                        super::super::codec::expect_string(value, path)?,
741                        path,
742                    )
743                })
744            })
745            .transpose()?;
746        let mut field_extension = Vec::new();
747        if let Some(raw) = raw_extension {
748            for (index, value) in path
749                .with("extension", |path| {
750                    super::super::codec::expect_array(raw, path)
751                })?
752                .iter()
753                .enumerate()
754            {
755                field_extension.push(path.with_index("extension", index, |path| {
756                    super::super::codec::Json::from_json(
757                        super::super::codec::expect_object(value, path)?,
758                        path,
759                    )
760                })?);
761            }
762        }
763        let field_bounds = match raw_bounds.suffix {
764            None => None,
765            Some(suffix) => Some(path.with("bounds", |path| {
766                TimingRepeatBounds::from_json_parts(
767                    suffix,
768                    raw_bounds.value,
769                    raw_bounds.element,
770                    path,
771                )
772            })?),
773        };
774        let field_count = match (raw_count, raw_count_element) {
775            (None, None) => None,
776            (value, element) => Some(path.with("count", |path| {
777                super::super::codec::Primitive::from_json_parts(value, element, path)
778            })?),
779        };
780        let field_count_max = match (raw_count_max, raw_count_max_element) {
781            (None, None) => None,
782            (value, element) => Some(path.with("countMax", |path| {
783                super::super::codec::Primitive::from_json_parts(value, element, path)
784            })?),
785        };
786        let field_duration = match (raw_duration, raw_duration_element) {
787            (None, None) => None,
788            (value, element) => Some(path.with("duration", |path| {
789                super::super::codec::Primitive::from_json_parts(value, element, path)
790            })?),
791        };
792        let field_duration_max = match (raw_duration_max, raw_duration_max_element) {
793            (None, None) => None,
794            (value, element) => Some(path.with("durationMax", |path| {
795                super::super::codec::Primitive::from_json_parts(value, element, path)
796            })?),
797        };
798        let field_duration_unit = match (raw_duration_unit, raw_duration_unit_element) {
799            (None, None) => None,
800            (value, element) => Some(path.with("durationUnit", |path| {
801                super::super::codec::Primitive::from_json_parts(value, element, path)
802            })?),
803        };
804        let field_frequency = match (raw_frequency, raw_frequency_element) {
805            (None, None) => None,
806            (value, element) => Some(path.with("frequency", |path| {
807                super::super::codec::Primitive::from_json_parts(value, element, path)
808            })?),
809        };
810        let field_frequency_max = match (raw_frequency_max, raw_frequency_max_element) {
811            (None, None) => None,
812            (value, element) => Some(path.with("frequencyMax", |path| {
813                super::super::codec::Primitive::from_json_parts(value, element, path)
814            })?),
815        };
816        let field_period = match (raw_period, raw_period_element) {
817            (None, None) => None,
818            (value, element) => Some(path.with("period", |path| {
819                super::super::codec::Primitive::from_json_parts(value, element, path)
820            })?),
821        };
822        let field_period_max = match (raw_period_max, raw_period_max_element) {
823            (None, None) => None,
824            (value, element) => Some(path.with("periodMax", |path| {
825                super::super::codec::Primitive::from_json_parts(value, element, path)
826            })?),
827        };
828        let field_period_unit = match (raw_period_unit, raw_period_unit_element) {
829            (None, None) => None,
830            (value, element) => Some(path.with("periodUnit", |path| {
831                super::super::codec::Primitive::from_json_parts(value, element, path)
832            })?),
833        };
834        let field_start_offset = raw_start_offset
835            .map(|value| {
836                path.with("startOffset", |path| {
837                    super::super::codec::Json::from_json(
838                        super::super::codec::expect_object(
839                            super::super::codec::expect_single(value, path)?,
840                            path,
841                        )?,
842                        path,
843                    )
844                })
845            })
846            .transpose()?;
847        let field_end_offset = raw_end_offset
848            .map(|value| {
849                path.with("endOffset", |path| {
850                    super::super::codec::Json::from_json(
851                        super::super::codec::expect_object(
852                            super::super::codec::expect_single(value, path)?,
853                            path,
854                        )?,
855                        path,
856                    )
857                })
858            })
859            .transpose()?;
860        let mut field_day_of_week = Vec::new();
861        for (index, (value, element)) in path
862            .with("dayOfWeek", |path| {
863                super::super::codec::pair_arrays(raw_day_of_week, raw_day_of_week_element, path)
864            })?
865            .into_iter()
866            .enumerate()
867        {
868            field_day_of_week.push(path.with_index("dayOfWeek", index, |path| {
869                super::super::codec::Primitive::from_json_parts(value, element, path)
870            })?);
871        }
872        let mut field_time_of_day = Vec::new();
873        for (index, (value, element)) in path
874            .with("timeOfDay", |path| {
875                super::super::codec::pair_arrays(raw_time_of_day, raw_time_of_day_element, path)
876            })?
877            .into_iter()
878            .enumerate()
879        {
880            field_time_of_day.push(path.with_index("timeOfDay", index, |path| {
881                super::super::codec::Primitive::from_json_parts(value, element, path)
882            })?);
883        }
884        let mut field_when = Vec::new();
885        for (index, (value, element)) in path
886            .with("when", |path| {
887                super::super::codec::pair_arrays(raw_when, raw_when_element, path)
888            })?
889            .into_iter()
890            .enumerate()
891        {
892            field_when.push(path.with_index("when", index, |path| {
893                super::super::codec::Primitive::from_json_parts(value, element, path)
894            })?);
895        }
896        let field_offset = match (raw_offset, raw_offset_element) {
897            (None, None) => None,
898            (value, element) => Some(path.with("offset", |path| {
899                super::super::codec::Primitive::from_json_parts(value, element, path)
900            })?),
901        };
902        Ok(Self {
903            id: field_id,
904            extension: field_extension,
905            bounds: field_bounds,
906            count: field_count,
907            count_max: field_count_max,
908            duration: field_duration,
909            duration_max: field_duration_max,
910            duration_unit: field_duration_unit,
911            frequency: field_frequency,
912            frequency_max: field_frequency_max,
913            period: field_period,
914            period_max: field_period_max,
915            period_unit: field_period_unit,
916            start_offset: field_start_offset,
917            end_offset: field_end_offset,
918            day_of_week: field_day_of_week,
919            time_of_day: field_time_of_day,
920            when: field_when,
921            offset: field_offset,
922        })
923    }
924}
925
926impl serde::Serialize for TimingRepeat {
927    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
928        let mut map = serde::Serializer::serialize_map(serializer, None)?;
929        if let Some(item) = &self.count {
930            super::super::codec::element_entry(&mut map, "_count", item)?;
931        }
932        if let Some(item) = &self.count_max {
933            super::super::codec::element_entry(&mut map, "_countMax", item)?;
934        }
935        super::super::codec::element_list_entry(&mut map, "_dayOfWeek", &self.day_of_week)?;
936        if let Some(item) = &self.duration {
937            super::super::codec::element_entry(&mut map, "_duration", item)?;
938        }
939        if let Some(item) = &self.duration_max {
940            super::super::codec::element_entry(&mut map, "_durationMax", item)?;
941        }
942        if let Some(item) = &self.duration_unit {
943            super::super::codec::element_entry(&mut map, "_durationUnit", item)?;
944        }
945        if let Some(item) = &self.frequency {
946            super::super::codec::element_entry(&mut map, "_frequency", item)?;
947        }
948        if let Some(item) = &self.frequency_max {
949            super::super::codec::element_entry(&mut map, "_frequencyMax", item)?;
950        }
951        if let Some(item) = &self.offset {
952            super::super::codec::element_entry(&mut map, "_offset", item)?;
953        }
954        if let Some(item) = &self.period {
955            super::super::codec::element_entry(&mut map, "_period", item)?;
956        }
957        if let Some(item) = &self.period_max {
958            super::super::codec::element_entry(&mut map, "_periodMax", item)?;
959        }
960        if let Some(item) = &self.period_unit {
961            super::super::codec::element_entry(&mut map, "_periodUnit", item)?;
962        }
963        super::super::codec::element_list_entry(&mut map, "_timeOfDay", &self.time_of_day)?;
964        super::super::codec::element_list_entry(&mut map, "_when", &self.when)?;
965        match &self.bounds {
966            Some(TimingRepeatBounds::Duration(inner)) => {
967                serde::ser::SerializeMap::serialize_entry(
968                    &mut map,
969                    "boundsDuration",
970                    inner.as_ref(),
971                )?;
972            }
973            Some(TimingRepeatBounds::Period(inner)) => {
974                serde::ser::SerializeMap::serialize_entry(
975                    &mut map,
976                    "boundsPeriod",
977                    inner.as_ref(),
978                )?;
979            }
980            Some(TimingRepeatBounds::Range(inner)) => {
981                serde::ser::SerializeMap::serialize_entry(&mut map, "boundsRange", inner.as_ref())?;
982            }
983            None => {}
984        }
985        if let Some(item) = &self.count {
986            super::super::codec::value_entry(&mut map, "count", item)?;
987        }
988        if let Some(item) = &self.count_max {
989            super::super::codec::value_entry(&mut map, "countMax", item)?;
990        }
991        super::super::codec::value_list_entry(&mut map, "dayOfWeek", &self.day_of_week)?;
992        if let Some(item) = &self.duration {
993            super::super::codec::value_entry(&mut map, "duration", item)?;
994        }
995        if let Some(item) = &self.duration_max {
996            super::super::codec::value_entry(&mut map, "durationMax", item)?;
997        }
998        if let Some(item) = &self.duration_unit {
999            super::super::codec::value_entry(&mut map, "durationUnit", item)?;
1000        }
1001        if let Some(item) = &self.end_offset {
1002            serde::ser::SerializeMap::serialize_entry(&mut map, "endOffset", item)?;
1003        }
1004        if !self.extension.is_empty() {
1005            serde::ser::SerializeMap::serialize_entry(&mut map, "extension", &self.extension)?;
1006        }
1007        if let Some(item) = &self.frequency {
1008            super::super::codec::value_entry(&mut map, "frequency", item)?;
1009        }
1010        if let Some(item) = &self.frequency_max {
1011            super::super::codec::value_entry(&mut map, "frequencyMax", item)?;
1012        }
1013        if let Some(v) = &self.id {
1014            serde::ser::SerializeMap::serialize_entry(&mut map, "id", v)?;
1015        }
1016        if let Some(item) = &self.offset {
1017            super::super::codec::value_entry(&mut map, "offset", item)?;
1018        }
1019        if let Some(item) = &self.period {
1020            super::super::codec::value_entry(&mut map, "period", item)?;
1021        }
1022        if let Some(item) = &self.period_max {
1023            super::super::codec::value_entry(&mut map, "periodMax", item)?;
1024        }
1025        if let Some(item) = &self.period_unit {
1026            super::super::codec::value_entry(&mut map, "periodUnit", item)?;
1027        }
1028        if let Some(item) = &self.start_offset {
1029            serde::ser::SerializeMap::serialize_entry(&mut map, "startOffset", item)?;
1030        }
1031        super::super::codec::value_list_entry(&mut map, "timeOfDay", &self.time_of_day)?;
1032        super::super::codec::value_list_entry(&mut map, "when", &self.when)?;
1033        serde::ser::SerializeMap::end(map)
1034    }
1035}
1036
1037impl<'de> serde::Deserialize<'de> for TimingRepeat {
1038    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1039        let value = <super::super::codec::Value as serde::Deserialize>::deserialize(deserializer)?;
1040        let mut path = super::super::codec::Path::root("TimingRepeat");
1041        let object =
1042            super::super::codec::expect_object(&value, &path).map_err(serde::de::Error::custom)?;
1043        super::super::codec::Json::from_json(object, &mut path).map_err(serde::de::Error::custom)
1044    }
1045}
1046
1047/// The \`bounds\[x\]\` choice of \`TimingRepeat\`.
1048///
1049/// Either a duration for the length of the timing schedule, a range of possible
1050/// length, or outer bounds for start and/or end limits of the timing schedule.
1051#[derive(Debug, Clone, PartialEq, Eq)]
1052pub enum TimingRepeatBounds {
1053    /// The `Duration` form.
1054    Duration(Box<super::duration::Duration>),
1055    /// The `Range` form.
1056    Range(Box<super::range::Range>),
1057    /// The `Period` form.
1058    Period(Box<super::period::Period>),
1059}
1060
1061impl TimingRepeatBounds {
1062    /// The key suffix, the value part, and the `_name` part of this form.
1063    ///
1064    /// # Errors
1065    ///
1066    /// Returns [`super::super::codec::EncodeError`] when a held value has no JSON form.
1067    pub fn to_json_parts(
1068        &self,
1069    ) -> Result<
1070        (
1071            &'static str,
1072            Option<super::super::codec::Value>,
1073            Option<super::super::codec::Value>,
1074        ),
1075        super::super::codec::EncodeError,
1076    > {
1077        match self {
1078            Self::Duration(inner) => Ok((
1079                "Duration",
1080                Some(super::super::codec::Value::Object(
1081                    super::super::codec::Json::to_json(inner.as_ref())?,
1082                )),
1083                None,
1084            )),
1085            Self::Range(inner) => Ok((
1086                "Range",
1087                Some(super::super::codec::Value::Object(
1088                    super::super::codec::Json::to_json(inner.as_ref())?,
1089                )),
1090                None,
1091            )),
1092            Self::Period(inner) => Ok((
1093                "Period",
1094                Some(super::super::codec::Value::Object(
1095                    super::super::codec::Json::to_json(inner.as_ref())?,
1096                )),
1097                None,
1098            )),
1099        }
1100    }
1101
1102    /// Decodes the form named by `suffix` from its value and `_name` parts.
1103    ///
1104    /// # Errors
1105    ///
1106    /// Returns [`super::super::codec::DecodeError`] for an unknown suffix or a malformed part.
1107    pub fn from_json_parts(
1108        suffix: &str,
1109        value: Option<&super::super::codec::Value>,
1110        element: Option<&super::super::codec::Value>,
1111        path: &mut super::super::codec::Path,
1112    ) -> Result<Self, super::super::codec::DecodeError> {
1113        match suffix {
1114            "Duration" => {
1115                if element.is_some() {
1116                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
1117                        expected: "no underscore form for a complex type",
1118                    }));
1119                }
1120                let value = value.ok_or_else(|| {
1121                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
1122                })?;
1123                let inner = super::super::codec::Json::from_json(
1124                    super::super::codec::expect_object(
1125                        super::super::codec::expect_single(value, path)?,
1126                        path,
1127                    )?,
1128                    path,
1129                )?;
1130                Ok(Self::Duration(Box::new(inner)))
1131            }
1132            "Range" => {
1133                if element.is_some() {
1134                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
1135                        expected: "no underscore form for a complex type",
1136                    }));
1137                }
1138                let value = value.ok_or_else(|| {
1139                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
1140                })?;
1141                let inner = super::super::codec::Json::from_json(
1142                    super::super::codec::expect_object(
1143                        super::super::codec::expect_single(value, path)?,
1144                        path,
1145                    )?,
1146                    path,
1147                )?;
1148                Ok(Self::Range(Box::new(inner)))
1149            }
1150            "Period" => {
1151                if element.is_some() {
1152                    return Err(path.error(super::super::codec::DecodeErrorKind::WrongType {
1153                        expected: "no underscore form for a complex type",
1154                    }));
1155                }
1156                let value = value.ok_or_else(|| {
1157                    path.error(super::super::codec::DecodeErrorKind::MissingProperty)
1158                })?;
1159                let inner = super::super::codec::Json::from_json(
1160                    super::super::codec::expect_object(
1161                        super::super::codec::expect_single(value, path)?,
1162                        path,
1163                    )?,
1164                    path,
1165                )?;
1166                Ok(Self::Period(Box::new(inner)))
1167            }
1168            _ => Err(path.error(super::super::codec::DecodeErrorKind::UnknownProperty)),
1169        }
1170    }
1171}