printobserver_core/bounds.rs
1//! The effective bounds: the configured envelope intersected with the manifest.
2//!
3//! A manifest may only narrow. The rule has three arms and one refusal, and
4//! every one of them is here rather than spread over the callers:
5//!
6//! * An adjustable the manifest names **narrower** than the envelope takes the
7//! manifest's range.
8//! * An adjustable the manifest names **wider** than the envelope is narrowed
9//! to the envelope's, and the narrowing is recorded on the print so nobody
10//! has to wonder later which bound applied.
11//! * An adjustable the manifest is **silent** about takes the envelope's own
12//! range, because inheriting the envelope is what silence means.
13//! * An adjustable the **envelope** does not name is no bound at all: it is not
14//! one this printer has, and a request for it is refused as such rather than
15//! acquiring a bound from nowhere.
16
17use std::collections::BTreeMap;
18
19use crate::records::{EffectiveBounds, JobManifest, ManifestNarrowing, SafetyEnvelope};
20use printobserver_printer_api::Adjustable;
21use printobserver_types::Range;
22
23/// The bounds in force for one print, and what the manifest asked for.
24#[derive(Debug, Clone, PartialEq)]
25pub struct Bounds {
26 /// The range each adjustable may be set to, inclusive.
27 pub effective: EffectiveBounds,
28 /// Every manifest range that was wider than the envelope's, in order.
29 pub narrowings: Vec<ManifestNarrowing>,
30}
31
32impl Bounds {
33 /// The range one adjustable may be set to, or absent when this printer has
34 /// no such adjustable.
35 #[must_use]
36 pub fn range(&self, adjustable: Adjustable) -> Option<Range> {
37 self.effective.allowed.get(&adjustable).copied()
38 }
39}
40
41/// The envelope intersected with the manifest, and the narrowings it took.
42///
43/// The envelope is the whole set of adjustables this printer has: an entry the
44/// manifest names and the envelope does not is deliberately absent from the
45/// answer rather than carried into it.
46#[must_use]
47pub fn effective_bounds(envelope: &SafetyEnvelope, manifest: Option<&JobManifest>) -> Bounds {
48 let mut allowed = BTreeMap::new();
49 let mut narrowings = Vec::new();
50 for (adjustable, permitted) in &envelope.allowed {
51 let Some(asked_for) = manifest.and_then(|held| held.allowed.get(adjustable)) else {
52 allowed.insert(*adjustable, *permitted);
53 continue;
54 };
55 let applied = Range::new(
56 permitted.min.max(asked_for.min),
57 permitted.max.min(asked_for.max),
58 );
59 if asked_for.min < permitted.min || asked_for.max > permitted.max {
60 narrowings.push(ManifestNarrowing {
61 adjustable: *adjustable,
62 requested: *asked_for,
63 applied,
64 });
65 }
66 allowed.insert(*adjustable, applied);
67 }
68 Bounds {
69 effective: EffectiveBounds { allowed },
70 narrowings,
71 }
72}