Skip to content

Commit c0366ec

Browse files
committed
Add Display impl for Bounds with tests
Renders bounds as `[lower, upper]`, formatting either side as `None` when unset. Signed-off-by: Sahas Subramanian <sahas.subramanian@proton.me>
1 parent dc9e24f commit c0366ec

2 files changed

Lines changed: 47 additions & 1 deletion

File tree

RELEASE_NOTES.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
## New Features
1212

13-
<!-- Here goes the main new features and examples or instructions on how to use them -->
13+
- `Bounds<Q>` now implements `Display`, rendering as `[lower, upper]` and showing `None` for either side when unset (e.g. `[-1 kW, 2 kW]`, `[None, 5]`).
1414

1515
## Bug Fixes
1616

src/bounds.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,18 @@ pub struct Bounds<Q: Quantity> {
1717
upper: Option<Q>,
1818
}
1919

20+
impl<Q: Quantity> std::fmt::Display for Bounds<Q> {
21+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22+
f.write_fmt(format_args!(
23+
"[{}, {}]",
24+
self.lower
25+
.map_or_else(|| String::from("None"), |x| x.to_string()),
26+
self.upper
27+
.map_or_else(|| String::from("None"), |x| x.to_string()),
28+
))
29+
}
30+
}
31+
2032
impl<Q: Quantity> Bounds<Q> {
2133
/// Creates a new `Bounds` with the given lower and upper bounds.
2234
pub fn new(lower: Option<Q>, upper: Option<Q>) -> Self {
@@ -235,6 +247,7 @@ fn squash_bounds_sets<Q: Quantity>(mut input: Vec<Bounds<Q>>) -> Vec<Bounds<Q>>
235247
#[cfg(test)]
236248
mod tests {
237249
use super::{Bounds, combine_parallel_sets, intersect_bounds_sets};
250+
use crate::quantity::Power;
238251

239252
#[test]
240253
fn test_bounds_addition() {
@@ -398,4 +411,37 @@ mod tests {
398411
let b = Bounds::<f32>::new(None, None);
399412
assert_eq!(a.combine_parallel(&b), vec![Bounds::new(None, None)]);
400413
}
414+
415+
#[test]
416+
fn display_renders_both_bounds() {
417+
let b = Bounds::new(Some(-5.0_f32), Some(5.0_f32));
418+
assert_eq!(b.to_string(), "[-5, 5]");
419+
}
420+
421+
#[test]
422+
fn display_renders_missing_lower_as_none() {
423+
let b = Bounds::new(None, Some(5.0_f32));
424+
assert_eq!(b.to_string(), "[None, 5]");
425+
}
426+
427+
#[test]
428+
fn display_renders_missing_upper_as_none() {
429+
let b = Bounds::new(Some(-5.0_f32), None);
430+
assert_eq!(b.to_string(), "[-5, None]");
431+
}
432+
433+
#[test]
434+
fn display_renders_fully_unbounded_as_none_none() {
435+
let b = Bounds::<f32>::new(None, None);
436+
assert_eq!(b.to_string(), "[None, None]");
437+
}
438+
439+
#[test]
440+
fn display_uses_inner_quantity_formatting() {
441+
let b = Bounds::new(
442+
Some(Power::from_kilowatts(-1.0)),
443+
Some(Power::from_kilowatts(2.0)),
444+
);
445+
assert_eq!(b.to_string(), "[-1 kW, 2 kW]");
446+
}
401447
}

0 commit comments

Comments
 (0)