1use crate::wire::ScaledNumber;
10use std::collections::{BTreeMap, BTreeSet};
11
12pub const MAX_PARTICIPANTS: usize = 256;
14pub const MAX_PARTICIPANT_ID_BYTES: usize = 256;
16
17#[derive(Debug, PartialEq, Eq, thiserror::Error)]
19pub enum AggregateError {
20 #[error("a nonempty set of controllable devices is required")]
21 Empty,
22 #[error("too many participants or samples")]
23 Capacity,
24 #[error("participant ID is empty or exceeds the byte limit")]
25 InvalidId,
26 #[error("participant appears more than once")]
27 DuplicateParticipant,
28 #[error("sample belongs to an unprovisioned participant")]
29 UnexpectedParticipant,
30 #[error("more than one sample was supplied for a participant")]
31 DuplicateSample,
32 #[error("exact total is outside the wire scaled-number representation")]
33 Unrepresentable,
34}
35
36pub fn controllable_total_power(
59 expected: &[&str],
60 samples: &[(&str, Option<ScaledNumber>)],
61) -> Result<Option<ScaledNumber>, AggregateError> {
62 if expected.is_empty() {
63 return Err(AggregateError::Empty);
64 }
65 if expected.len() > MAX_PARTICIPANTS || samples.len() > MAX_PARTICIPANTS {
66 return Err(AggregateError::Capacity);
67 }
68 let mut participants = BTreeSet::new();
69 for &id in expected {
70 check_id(id)?;
71 if !participants.insert(id) {
72 return Err(AggregateError::DuplicateParticipant);
73 }
74 }
75 let mut seen = BTreeSet::new();
76 for (id, _) in samples {
77 check_id(id)?;
78 if !participants.contains(id) {
79 return Err(AggregateError::UnexpectedParticipant);
80 }
81 if !seen.insert(id) {
82 return Err(AggregateError::DuplicateSample);
83 }
84 }
85 if seen.len() != participants.len() || samples.iter().any(|(_, value)| value.is_none()) {
86 return Ok(None);
87 }
88 let values = samples.iter().filter_map(|(_, v)| v.as_ref());
89 exact_sum(values).map(Some)
90}
91
92fn check_id(id: &str) -> Result<(), AggregateError> {
93 if id.is_empty() || id.len() > MAX_PARTICIPANT_ID_BYTES {
94 return Err(AggregateError::InvalidId);
95 }
96 Ok(())
97}
98
99fn exact_sum<'a>(
100 values: impl Iterator<Item = &'a ScaledNumber>,
101) -> Result<ScaledNumber, AggregateError> {
102 let mut columns = BTreeMap::<i32, i128>::new();
103 let mut finest = i16::MAX;
104 for value in values {
105 finest = finest.min(value.scale);
106 *columns.entry(i32::from(value.scale)).or_default() += i128::from(value.number);
107 }
108
109 let mut digits = Vec::new();
114 while let Some((place, coefficient)) = columns.pop_first() {
115 let digit = coefficient % 10;
116 if digit != 0 {
117 digits.push((place, digit));
118 }
119 let carry = coefficient / 10;
120 if carry != 0 {
121 *columns.entry(place + 1).or_default() += carry;
122 }
123 }
124 let Some(&(lowest, _)) = digits.first() else {
125 return Ok(ScaledNumber {
126 number: 0,
127 scale: finest,
128 });
129 };
130 let mut scale = lowest.min(i32::from(i16::MAX)) as i16;
132 let mut previous = digits.last().expect("nonempty digits").0;
133 let mut coefficient = 0i128;
134 for (place, digit) in digits.into_iter().rev().chain([(i32::from(scale), 0)]) {
135 let factor = 10i128
136 .checked_pow((previous - place) as u32)
137 .ok_or(AggregateError::Unrepresentable)?;
138 coefficient = coefficient
139 .checked_mul(factor)
140 .and_then(|n| n.checked_add(digit))
141 .ok_or(AggregateError::Unrepresentable)?;
142 previous = place;
143 }
144 let mut number = i64::try_from(coefficient).map_err(|_| AggregateError::Unrepresentable)?;
145 while scale > finest {
146 let Some(shifted) = number.checked_mul(10) else {
147 break;
148 };
149 number = shifted;
150 scale -= 1;
151 }
152 Ok(ScaledNumber { number, scale })
153}