1use std::collections::BTreeMap;
16use std::convert::Infallible;
17use crate::JsString;
18use crate::input::{DataFingerprintInput, PropertyEntryInput, PropertySetInput, QuantitySetInput, TypeAssignmentInput};
19use crate::js_json::{stable_hash_json, utf16_length, JsonValue};
20use crate::projections::sorted_string_list;
21use crate::sparse_collection::SparseCollection;
22use super::{core_attributes, set_to_json, sorted_entries, sorted_property_sets, sorted_quantity_sets,
23 sorted_type_assignments, string_array, with_holes};
24
25fn accept_all<T>(result: Result<T, Infallible>) -> T {
26 match result { Ok(value) => value, Err(never) => match never {} }
27}
28pub(super) fn has_holes(input: &DataFingerprintInput) -> bool {
29 input.property_sets.holes() > 0 || input.quantity_sets.holes() > 0 || input.type_assignments.holes() > 0
30 || input.property_sets.present().any(|set| set.properties.holes() > 0)
31 || input.quantity_sets.present().any(|set| set.quantities.holes() > 0)
32}
33
34fn check_sets<S, E>(sets: &SparseCollection<S>, part: impl Fn(&S) -> (&JsString, &SparseCollection<PropertyEntryInput>),
40 key: &str, components: bool, check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
41 if !sets.present().any(|set| part(set).1.holes() > 0) { return Ok(()); }
42 let mut names: Vec<&JsString> = sets.present().map(|set| part(set).0).collect();
43 names.sort();
44 let shared = |name: &JsString| names.partition_point(|other| *other < name) + 1 < names.partition_point(|other| *other <= name);
45 let (mut tiebreak, mut members) = (None::<u64>, None::<u64>);
46 for (name, entries) in sets.present().map(&part).filter(|(_, entries)| entries.holes() > 0) {
47 let entries = sorted_entries(entries);
48 if shared(name) {
49 tiebreak = tiebreak.max(Some(utf16_length(&set_to_json(name, key, &entries), true)));
50 }
51 if components {
52 members = members.max(Some(utf16_length(&JsonValue::Array(entries), false)));
53 }
54 }
55 tiebreak.map_or(Ok(()), &mut *check)?;
56 members.map_or(Ok(()), check)
57}
58pub fn check_property_sets<E>(sets: &SparseCollection<PropertySetInput>, components: bool,
62 check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
63 check_sets(sets, |set| (&set.name, &set.properties), "properties", components, check)
64}
65pub fn check_quantity_sets<E>(sets: &SparseCollection<QuantitySetInput>, components: bool,
67 check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
68 check_sets(sets, |set| (&set.name, &set.quantities), "quantities", components, check)
69}
70pub fn check_type_assignments<E>(types: &SparseCollection<TypeAssignmentInput>, components: bool,
73 check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
74 if !components || types.holes() == 0 { return Ok(()); }
75 check(utf16_length(&JsonValue::Array(sorted_type_assignments(types)), false))
76}
77
78pub fn build_data_fingerprint(input: &DataFingerprintInput) -> String {
85 accept_all(build_data_fingerprint_checked(input, |_| Ok(())))
86}
87
88pub fn build_data_fingerprint_checked<E>(input: &DataFingerprintInput,
91 mut check: impl FnMut(u64) -> Result<(), E>) -> Result<String, E> {
92 check_property_sets(&input.property_sets, false, &mut check)?;
93 check_quantity_sets(&input.quantity_sets, false, &mut check)?;
94 let (value, _) = project_data(input);
95 if has_holes(input) { check(utf16_length(&value, false))?; }
96 Ok(stable_hash_json(&value))
97}
98
99pub(super) fn project_data(input: &DataFingerprintInput) -> (JsonValue, usize) {
100 let mut object = core_attributes(input);
101 let core_len = object.len();
102
103 object.push((
104 "TypeAssignments".into(),
105 JsonValue::Array(sorted_type_assignments(&input.type_assignments)),
106 ));
107 object.push((
108 "PropertySets".into(),
109 JsonValue::Array(with_holes(sorted_property_sets(input).into_iter().map(|(_, v)| v).collect(), input.property_sets.holes())),
110 ));
111 object.push((
112 "QuantitySets".into(),
113 JsonValue::Array(with_holes(sorted_quantity_sets(input).into_iter().map(|(_, v)| v).collect(), input.quantity_sets.holes())),
114 ));
115
116 let materials = sorted_string_list(&input.materials);
117 if !materials.is_empty() {
118 object.push(("Materials".into(), string_array(&materials)));
119 }
120 let classifications = sorted_string_list(&input.classifications);
121 if !classifications.is_empty() {
122 object.push(("Classifications".into(), string_array(&classifications)));
123 }
124
125 (JsonValue::Object(object), core_len)
126
127}
128
129pub fn build_component_fingerprints(input: &DataFingerprintInput) -> BTreeMap<JsString, String> {
146 build_component_fingerprint_entries(input).into_iter().collect()
147}
148
149pub fn build_component_fingerprint_entries(input: &DataFingerprintInput) -> Vec<(JsString, String)> {
156 accept_all(build_component_fingerprint_entries_checked(input, |_| Ok(())))
157}
158
159pub fn build_component_fingerprint_entries_checked<E>(input: &DataFingerprintInput,
163 mut check: impl FnMut(u64) -> Result<(), E>) -> Result<Vec<(JsString, String)>, E> {
164 let mut components = OrderedComponents(Vec::new());
165
166 components.insert(
167 "attr:core".into(),
168 stable_hash_json(&JsonValue::Object(core_attributes(input))),
169 );
170
171 check_property_sets(&input.property_sets, true, &mut check)?;
172 assert_eq!(input.property_sets.holes(), 0, "component property sets require present records");
173 let mut ordinals = SetOrdinals::default();
174 for (name, set) in sorted_property_sets(input) {
175 let members = member_array(set, "properties");
176 components.insert(ordinals.key("pset", &name), stable_hash_json(&members));
177 }
178 check_quantity_sets(&input.quantity_sets, true, &mut check)?;
179 assert_eq!(input.quantity_sets.holes(), 0, "component quantity sets require present records");
180 let mut ordinals = SetOrdinals::default();
181 for (name, set) in sorted_quantity_sets(input) {
182 let members = member_array(set, "quantities");
183 components.insert(ordinals.key("qset", &name), stable_hash_json(&members));
184 }
185
186 check_type_assignments(&input.type_assignments, true, &mut check)?;
187 let type_assignments = sorted_type_assignments(&input.type_assignments);
188 if !type_assignments.is_empty() {
189 let value = JsonValue::Array(type_assignments);
190 components.insert("type-assignment".into(), stable_hash_json(&value));
191 }
192
193 let materials = sorted_string_list(&input.materials);
194 if !materials.is_empty() {
195 components.insert(
196 "material".into(),
197 stable_hash_json(&string_array(&materials)),
198 );
199 }
200 let classifications = sorted_string_list(&input.classifications);
201 if !classifications.is_empty() {
202 components.insert(
203 "classification".into(),
204 stable_hash_json(&string_array(&classifications)),
205 );
206 }
207
208 Ok(components.0)
209}
210
211#[derive(Default)]
218pub(super) struct SetOrdinals { last: Option<JsString>, ordinal: u32 }
219impl SetOrdinals {
220 pub(super) fn key(&mut self, kind: &str, name: &JsString) -> JsString {
221 if self.last.as_ref() == Some(name) { self.ordinal += 1; }
222 else { self.last = Some(name.clone()); self.ordinal = 1; }
223 if self.ordinal == 1 { JsString::surround(&format!("{kind}:"), name, "") }
224 else { JsString::surround(&format!("{kind}#{}:", self.ordinal), name, "") }
225 }
226}
227
228pub(super) struct OrderedComponents(pub(super) Vec<(JsString, String)>);
229impl OrderedComponents {
230 pub(super) fn insert(&mut self, key: JsString, value: String) {
231 if let Some((_, old)) = self.0.iter_mut().find(|(name, _)| *name == key) { *old = value; }
232 else { self.0.push((key, value)); }
233 }
234}
235
236fn member_array(set: JsonValue, members_key: &str) -> JsonValue {
241 if let JsonValue::Object(entries) = set {
242 for (key, value) in entries {
243 if key == members_key {
244 return value;
245 }
246 }
247 }
248 JsonValue::Array(Vec::new())
249}