Skip to content

Commit d64bf0e

Browse files
committed
refactor: Improve suffix handling for add and sub ops
1 parent d6dec5f commit d64bf0e

File tree

3 files changed

+27
-8
lines changed

3 files changed

+27
-8
lines changed

crates/stackable-operator/src/quantity/mod.rs

+19
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,25 @@ impl Quantity {
142142
}
143143
}
144144
}
145+
146+
/// Either sets the suffix of `self` to `rhs` or scales `rhs` if `self` has a value other than
147+
/// zero.
148+
///
149+
/// This function is currently used for the [`std::ops::Add`] and [`std::ops::Sub`]
150+
/// implementations.
151+
pub fn set_suffix_or_scale_rhs(self, rhs: Self) -> (Self, Self) {
152+
if self.value == 0.0 {
153+
(
154+
Self {
155+
suffix: rhs.suffix,
156+
..self
157+
},
158+
rhs,
159+
)
160+
} else {
161+
(self, rhs.scale_to(self.suffix))
162+
}
163+
}
145164
}
146165

147166
#[cfg(test)]

crates/stackable-operator/src/quantity/ops.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ impl Add for Quantity {
66
type Output = Quantity;
77

88
fn add(self, rhs: Quantity) -> Self::Output {
9-
let rhs = rhs.scale_to(self.suffix);
9+
let (this, rhs) = self.set_suffix_or_scale_rhs(rhs);
1010

1111
Self {
12-
value: self.value + rhs.value,
13-
..self
12+
value: this.value + rhs.value,
13+
suffix: this.suffix,
1414
}
1515
}
1616
}
@@ -25,11 +25,11 @@ impl Sub for Quantity {
2525
type Output = Quantity;
2626

2727
fn sub(self, rhs: Quantity) -> Self::Output {
28-
let rhs = rhs.scale_to(self.suffix);
28+
let (this, rhs) = self.set_suffix_or_scale_rhs(rhs);
2929

3030
Self {
31-
value: self.value - rhs.value,
32-
..self
31+
value: this.value - rhs.value,
32+
suffix: this.suffix,
3333
}
3434
}
3535
}

crates/stackable-operator/src/quantity/suffix.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,12 @@ impl Suffix {
5858

5959
pub fn scale_down(self) -> Option<Self> {
6060
match self {
61-
Suffix::DecimalMultiple(s) => todo!(),
61+
Suffix::DecimalMultiple(_s) => todo!(),
6262
Suffix::BinaryMultiple(s) => match s.scale_down() {
6363
Some(s) => Some(Self::BinaryMultiple(s)),
6464
None => Some(Self::DecimalMultiple(DecimalMultiple::Milli)),
6565
},
66-
Suffix::DecimalExponent(s) => todo!(),
66+
Suffix::DecimalExponent(_s) => todo!(),
6767
}
6868
}
6969
}

0 commit comments

Comments
 (0)