Skip to content

Commit

Permalink
Fix divide by zero panic (#54)
Browse files Browse the repository at this point in the history
* don't divide by step-size if it's zero

* reorder
  • Loading branch information
remkop22 authored Jul 6, 2023
1 parent c26006b commit e9f6a33
Showing 1 changed file with 27 additions and 20 deletions.
47 changes: 27 additions & 20 deletions ocpi-tariffs/src/pricer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,16 +207,20 @@ impl StepSize {
billed_volume: &mut HoursDecimal,
step_size: u64,
) -> HoursDecimal {
let total_seconds = total.as_num_seconds_decimal();
let step_size = Number::from(step_size);
if step_size > 0 {
let total_seconds = total.as_num_seconds_decimal();
let step_size = Number::from(step_size);

let priced_total_seconds = (total_seconds / step_size).ceil() * step_size;
let priced_total =
HoursDecimal::from_seconds_decimal(priced_total_seconds).expect("overflow");
let priced_total_seconds = (total_seconds / step_size).ceil() * step_size;
let priced_total =
HoursDecimal::from_seconds_decimal(priced_total_seconds).expect("overflow");

*billed_volume += priced_total - total;
*billed_volume += priced_total - total;

priced_total
priced_total
} else {
total
}
}

fn apply_time(&self, periods: &mut [PeriodReport], total: HoursDecimal) -> HoursDecimal {
Expand Down Expand Up @@ -257,24 +261,27 @@ impl StepSize {

fn apply_energy(&self, periods: &mut [PeriodReport], total: Kwh) -> Kwh {
if let Some((energy_index, price)) = &self.energy {
let period = &mut periods[*energy_index];
if price.step_size > 0 {
let period = &mut periods[*energy_index];
let step_size = Number::from(price.step_size);

let volume = period
.dimensions
.energy
.billed_volume
.as_mut()
.expect("dimension should have a volume");
let volume = period
.dimensions
.energy
.billed_volume
.as_mut()
.expect("dimension should have a volume");

let step_size = Number::from(price.step_size);
let billed = Kwh::from_watt_hours((total.watt_hours() / step_size).ceil() * step_size);
let billed =
Kwh::from_watt_hours((total.watt_hours() / step_size).ceil() * step_size);

*volume += billed - total;
*volume += billed - total;

billed
} else {
total
return billed;
}
}

total
}
}

Expand Down

0 comments on commit e9f6a33

Please sign in to comment.