use resource_timeline::envelope::{
Envelope, Flexible, FlexibleState, StateEnvelope, StateVerdict, Verdict,
};
use resource_timeline::{ActivityId, Error, Impact, StateImpact, StateTimeline, Timeline, Window};
const OFF: u32 = 0;
const STEAM: u32 = 1;
const DRY: u32 = 2;
const DISHWASHER: ActivityId = ActivityId(0);
const BREAD: ActivityId = ActivityId(1);
const ROAST: ActivityId = ActivityId(2);
const FRYER: ActivityId = ActivityId(3);
const fn draw(minutes: i64, kw: i64) -> Impact {
Impact::Claim {
start: 0,
end: minutes,
amount: kw,
}
}
const fn mode(minutes: i64, mode: u32) -> [StateImpact; 2] {
[
StateImpact::Set { at: 0, value: mode },
StateImpact::Require {
start: 0,
end: minutes,
value: mode,
},
]
}
fn check(windows: [Window; 3]) -> Result<(Verdict, StateVerdict), Error> {
let mut circuit = Timeline::claimable(0, 11, 8)?;
circuit.add(
DISHWASHER,
Impact::Claim {
start: 0,
end: 60,
amount: 4,
},
)?;
let (bread, roast, fryer) = ([draw(25, 6)], [draw(40, 6)], [draw(15, 5)]);
let jobs = [
Flexible {
activity: BREAD,
window: windows[0],
impacts: &bread,
},
Flexible {
activity: ROAST,
window: windows[1],
impacts: &roast,
},
Flexible {
activity: FRYER,
window: windows[2],
impacts: &fryer,
},
];
let power = Envelope::new(&circuit, &jobs)?;
println!(
" free kW at minute 30: {} to {}",
power.lower_at(30)?,
power.upper_at(30)?
);
let oven = StateTimeline::new(0, OFF, 8);
let (steam, dry) = (mode(25, STEAM), mode(40, DRY));
let modes = [
FlexibleState {
activity: BREAD,
window: windows[0],
impacts: &steam,
},
FlexibleState {
activity: ROAST,
window: windows[1],
impacts: &dry,
},
];
let oven_check = StateEnvelope::new(&oven, &modes)?.check()?;
Ok((power.check()?, oven_check))
}
fn main() -> Result<(), Error> {
println!("First windows: bread 10-50, roast 20-80, fryer 0-60.");
let first = [
Window::new(10, 50)?,
Window::new(20, 80)?,
Window::new(0, 60)?,
];
let (power, oven) = check(first)?;
println!(" circuit: {power:?}");
println!(" oven: {oven:?}");
match &power {
Verdict::Possible(violation) => {
assert_eq!((violation.at, violation.level), (10, -4));
assert_eq!(violation.contributors, [DISHWASHER, BREAD, FRYER]);
}
other => panic!("expected a possible overload, got {other:?}"),
}
assert!(matches!(oven, StateVerdict::Possible(_)));
println!("Narrowed windows: bread 10-30, roast 55-80, fryer 60-90.");
let narrowed = [
Window::new(10, 30)?,
Window::new(55, 80)?,
Window::new(60, 90)?,
];
let (power, oven) = check(narrowed)?;
println!(" circuit: {power:?}");
println!(" oven: {oven:?}");
assert_eq!(power, Verdict::Safe);
assert_eq!(oven, StateVerdict::Safe);
Ok(())
}