hotfix_message/
parts.rs

1use crate::field_map::{Field, FieldMap};
2use std::collections::HashSet;
3
4mod body;
5mod header;
6mod repeating_group;
7mod trailer;
8
9use hotfix_dictionary::{IsFieldDefinition, TagU32};
10
11use crate::encoding::FieldValueError;
12use crate::{FieldType, HardCodedFixFieldDefinition};
13pub(crate) use body::Body;
14pub(crate) use header::Header;
15pub use repeating_group::RepeatingGroup;
16pub(crate) use trailer::Trailer;
17
18// TODO: what a rubbish name.. but can't think of anything better that's not overloaded with fefix names
19pub trait Part {
20    fn get_field_map(&self) -> &FieldMap;
21    fn get_field_map_mut(&mut self) -> &mut FieldMap;
22
23    fn set<'a, V>(&'a mut self, field_definition: &HardCodedFixFieldDefinition, value: V)
24    where
25        V: FieldType<'a>,
26    {
27        let tag = TagU32::new(field_definition.tag).unwrap();
28        let field = Field::new(tag, value.to_bytes());
29
30        self.store_field(field);
31    }
32
33    fn store_field(&mut self, field: Field) {
34        self.get_field_map_mut().insert(field)
35    }
36
37    #[inline]
38    fn get<'a, V>(
39        &'a self,
40        field: &HardCodedFixFieldDefinition,
41    ) -> Result<V, FieldValueError<V::Error>>
42    where
43        V: FieldType<'a>,
44    {
45        self.get_raw(field)
46            .map(V::deserialize)
47            .transpose()
48            .map_err(FieldValueError::Invalid)
49            .and_then(|opt| opt.ok_or(FieldValueError::Missing))
50    }
51
52    #[inline]
53    fn get_raw(&self, field: &HardCodedFixFieldDefinition) -> Option<&[u8]> {
54        self.get_field_map().get_raw(field.tag())
55    }
56
57    fn pop(&mut self, field: &HardCodedFixFieldDefinition) -> Option<Field> {
58        self.get_field_map_mut().fields.shift_remove(&field.tag())
59    }
60
61    fn set_groups(&mut self, groups: Vec<RepeatingGroup>) {
62        let tags: HashSet<(TagU32, TagU32)> = groups
63            .iter()
64            .map(|g| (g.start_tag, g.delimiter_tag))
65            .collect();
66        assert_eq!(tags.len(), 1);
67        let (start_tag, _) = tags.into_iter().next().unwrap();
68        self.get_field_map_mut().set_groups(start_tag, groups);
69    }
70
71    fn get_group(&self, start_tag: TagU32, index: usize) -> Option<&RepeatingGroup> {
72        self.get_field_map().get_group(start_tag, index)
73    }
74
75    fn calculate_length(&self) -> usize {
76        self.get_field_map().calculate_length(&[])
77    }
78}