1use super::Rect;
22
23pub const MAX_METER_MARKERS: usize = 16;
25pub const MAX_METER_SEGMENTS: usize = 64;
28
29#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum MeterValue {
32 Known { current: f64, capacity: f64 },
33 Empty,
34 Unknown,
35}
36impl MeterValue {
37 pub fn fraction(self) -> Result<Option<f64>, MeterError> {
40 match self {
41 Self::Known { current, capacity } => {
42 if !current.is_finite()
43 || !capacity.is_finite()
44 || capacity <= 0.
45 || current < 0.
46 || current > capacity
47 {
48 return Err(MeterError::InvalidValue);
49 }
50 let fraction = current / capacity;
51 if current > 0. && fraction == 0. {
52 return Err(MeterError::InvalidValue);
53 }
54 Ok(Some(fraction))
55 }
56 Self::Empty => Ok(Some(0.)),
57 Self::Unknown => Ok(None),
58 }
59 }
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum SegmentValue {
66 Known { filled: usize, capacity: usize },
67 Empty,
68 Unknown { capacity: usize },
69}
70impl SegmentValue {
71 pub fn count(self) -> Result<usize, MeterError> {
73 let count = match self {
74 Self::Known { filled, capacity } => {
75 if capacity == 0 || filled > capacity {
76 return Err(MeterError::InvalidValue);
77 }
78 capacity
79 }
80 Self::Empty => 0,
81 Self::Unknown { capacity } => capacity,
82 };
83 if count > MAX_METER_SEGMENTS {
84 return Err(MeterError::Capacity);
85 }
86 Ok(count)
87 }
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum MeterError {
93 InvalidValue,
94 InvalidGeometry,
95 Capacity,
96}
97impl std::fmt::Display for MeterError {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 f.write_str(match self {
100 Self::InvalidValue => "invalid meter telemetry",
101 Self::InvalidGeometry => "invalid or unrepresentable meter geometry",
102 Self::Capacity => "meter capacity exceeded",
103 })
104 }
105}
106impl std::error::Error for MeterError {}
107
108#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct MeterGeometry {
112 bounds: Rect,
113 value: MeterValue,
114 fill: Option<Rect>,
115}
116impl MeterGeometry {
117 pub fn new(bounds: Rect, value: MeterValue) -> Result<Self, MeterError> {
118 valid(bounds)?;
119 let fill = value
120 .fraction()?
121 .map(|fraction| {
122 let width = (f64::from(bounds.size[0]) * fraction) as f32;
123 if fraction > 0. && bounds.size[0] > 0. && width == 0. {
124 return Err(MeterError::InvalidGeometry);
125 }
126 let rect = Rect {
127 size: [width, bounds.size[1]],
128 ..bounds
129 };
130 inside(bounds, rect)?;
131 Ok(rect)
132 })
133 .transpose()?;
134 Ok(Self {
135 bounds,
136 value,
137 fill,
138 })
139 }
140 pub fn bounds(self) -> Rect {
141 self.bounds
142 }
143 pub fn value(self) -> MeterValue {
144 self.value
145 }
146 pub fn fill(self) -> Option<Rect> {
147 self.fill
148 }
149
150 pub fn markers_into(
156 self,
157 fractions: &[f64],
158 width: f32,
159 output: &mut [Rect],
160 ) -> Result<usize, MeterError> {
161 if fractions.len() > MAX_METER_MARKERS || output.len() < fractions.len() {
162 return Err(MeterError::Capacity);
163 }
164 if !width.is_finite()
165 || width <= 0.
166 || (!fractions.is_empty() && width > self.bounds.size[0])
167 {
168 return Err(MeterError::InvalidGeometry);
169 }
170 let mut checked = [self.bounds; MAX_METER_MARKERS];
171 for (i, &fraction) in fractions.iter().enumerate() {
172 if !fraction.is_finite() || !(0. ..=1.).contains(&fraction) {
173 return Err(MeterError::InvalidValue);
174 }
175 let offset = (f64::from(self.bounds.size[0]) * fraction - f64::from(width) / 2.)
176 .max(0.)
177 .min(f64::from(self.bounds.size[0] - width));
178 let r = Rect {
179 min: [
180 (f64::from(self.bounds.min[0]) + offset) as f32,
181 self.bounds.min[1],
182 ],
183 size: [width, self.bounds.size[1]],
184 };
185 inside(self.bounds, r)?;
186 checked[i] = r;
187 }
188 output[..fractions.len()].copy_from_slice(&checked[..fractions.len()]);
189 Ok(fractions.len())
190 }
191}
192
193#[derive(Clone, Copy, Debug, PartialEq)]
196pub struct SegmentRect {
197 pub bounds: Rect,
198 pub filled: bool,
199}
200
201#[derive(Clone, Copy, Debug, PartialEq)]
215pub struct SegmentGeometry {
216 bounds: Rect,
217 value: SegmentValue,
218 gap: f32,
219 count: usize,
220}
221impl SegmentGeometry {
222 pub fn new(bounds: Rect, value: SegmentValue, gap: f32) -> Result<Self, MeterError> {
223 valid(bounds)?;
224 let count = value.count()?;
225 if !gap.is_finite() || gap < 0. {
226 return Err(MeterError::InvalidGeometry);
227 }
228 let result = Self {
229 bounds,
230 value,
231 gap,
232 count,
233 };
234 for i in 0..count {
236 result.cell(i)?;
237 }
238 Ok(result)
239 }
240 pub fn bounds(self) -> Rect {
241 self.bounds
242 }
243 pub fn value(self) -> SegmentValue {
244 self.value
245 }
246 pub fn count(self) -> usize {
247 self.count
248 }
249 pub fn write_into(self, output: &mut [SegmentRect]) -> Result<usize, MeterError> {
252 if output.len() < self.count {
253 return Err(MeterError::Capacity);
254 }
255 for (i, dest) in output[..self.count].iter_mut().enumerate() {
256 *dest = self.cell(i).expect("validated immutable segment geometry");
258 }
259 Ok(self.count)
260 }
261 fn cell(self, index: usize) -> Result<SegmentRect, MeterError> {
262 let width = (f64::from(self.bounds.size[0])
263 - f64::from(self.gap) * (self.count - 1) as f64)
264 / self.count as f64;
265 if width <= 0. || !width.is_finite() {
266 return Err(MeterError::InvalidGeometry);
267 }
268 let left =
269 (f64::from(self.bounds.min[0]) + (width + f64::from(self.gap)) * index as f64) as f32;
270 let right = if index + 1 == self.count {
271 self.bounds.min[0] + self.bounds.size[0]
272 } else {
273 (f64::from(self.bounds.min[0]) + (width + f64::from(self.gap)) * index as f64 + width)
274 as f32
275 };
276 let bounds = Rect {
277 min: [left, self.bounds.min[1]],
278 size: [right - left, self.bounds.size[1]],
279 };
280 if bounds.size[0] <= 0. {
281 return Err(MeterError::InvalidGeometry);
282 }
283 inside(self.bounds, bounds)?;
284 Ok(SegmentRect {
285 bounds,
286 filled: matches!(self.value, SegmentValue::Known { filled, .. } if index < filled),
287 })
288 }
289}
290
291fn valid(rect: Rect) -> Result<(), MeterError> {
292 if !rect.valid()
293 || (0..2).any(|i| rect.size[i] > 0. && rect.min[i] + rect.size[i] <= rect.min[i])
294 {
295 Err(MeterError::InvalidGeometry)
296 } else {
297 Ok(())
298 }
299}
300fn inside(parent: Rect, rect: Rect) -> Result<(), MeterError> {
301 valid(rect)?;
302 if (0..2).any(|i| {
303 rect.min[i] < parent.min[i] || rect.min[i] + rect.size[i] > parent.min[i] + parent.size[i]
304 }) {
305 Err(MeterError::InvalidGeometry)
306 } else {
307 Ok(())
308 }
309}