Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Human-readable time durations #327

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/datetime_human_tests.nbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
assert((0 second // human) == "0 seconds")
assert((1 second // human) == "1 second")
assert((5 second // human) == "5 seconds")
assert((1.5 second // human) == "1.500 seconds")

assert((60 seconds // human) == "1 minute")
assert((73 seconds // human) == "1 minute + 13 seconds")
assert((120 seconds // human) == "2 minutes")
assert((60.1 seconds // human) == "1 minute + 0.100 seconds")
assert((1 minute // human) == "1 minute")
assert((1.25 minute // human) == "1 minute + 15 seconds")
assert((2.5 minute // human) == "2 minutes + 30 seconds")

assert((1 hour // human) == "1 hour")
assert((1.5 hour // human) == "1 hour + 30 minutes")
assert((2 hour // human) == "2 hours")
assert((1 hour + 1 sec // human) == "1 hour + 1 second")

assert((1 day // human) == "1 day")
assert((1.37 day // human) == "1 day + 8 hours + 52 minutes + 48 seconds")

assert((1 week // human) == "7 days")
assert((1.5 weeks // human) == "10 days + 12 hours")
assert((2 weeks // human) == "14 days")

assert((1 sidereal_day // human) == "23 hours + 56 minutes + 4.090500 seconds")

assert((10000 days // human) == "10000 days")
assert((50 million days // human) == "50_000_000 days")

assert((1e12 days // human) == "1_000_000_000_000 days")
assert((1e15 days // human) == "1.0e+15 days")

assert((1 ms // human) == "0.001 seconds")
assert((1 µs // human) == "0.000001 seconds")
assert((1 ns // human) == "0.000000001 seconds")
assert((1234 ns // human) == "0.000001234 seconds")
assert((1s + 1234 ns // human) == "1.000001234 seconds")
9 changes: 0 additions & 9 deletions examples/format_time.nbt

This file was deleted.

36 changes: 36 additions & 0 deletions numbat/modules/datetime/human.nbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use core::functions
use core::strings
use units::si
use datetime::functions

fn _human_num_days(time: Time) -> Scalar = floor(time / day)

fn _human_join(a: String, b: String) -> String =
if str_slice(a, 0, 2) == "0 " then b else if str_slice(b, 0, 2) == "0 " then a else "{a} + {b}"

fn _remove_plural_suffix(str: String) -> String =
if str_slice(str, 0, 2) == "1 " then str_slice(str, 0, str_length(str) - 1) else str

fn _human_seconds(dt: DateTime) -> String =
_remove_plural_suffix(format_datetime("%-S%.f seconds", dt))

fn _human_minutes(dt: DateTime) -> String =
_remove_plural_suffix(format_datetime("%-M minutes", dt))

fn _human_hours(dt: DateTime) -> String =
_remove_plural_suffix(format_datetime("%-H hours", dt))

fn _human_days(num_days: Scalar) -> String =
_remove_plural_suffix("{num_days} days")

fn _human_readable_duration(time: Time, dt: DateTime, num_days: Scalar) -> String =
_human_join(_human_join(_human_join(_human_days(_human_num_days(time)), _human_hours(dt)), _human_minutes(dt)), _human_seconds(dt))

# Implementation details:
# we skip hours/minutes/seconds for durations larger than 1000 days because:
# (a) we run into floating point precision problems at the nanosecond level at this point
# (b) for much larger numbers, we can't convert to DateTimes anymore
fn human(time: Time) =
if _human_num_days(time) > 1000
then "{_human_num_days(time)} days"
else _human_readable_duration(time, parse_datetime("0001-01-01T00:00:00Z") + time, _human_num_days(time))
1 change: 1 addition & 0 deletions numbat/modules/prelude.nbt
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ use physics::constants
use physics::temperature_conversion

use datetime::functions
use datetime::human
4 changes: 2 additions & 2 deletions numbat/src/bytecode_interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ impl BytecodeInterpreter {
Op::DiffDateTime
} else {
match operator {
BinaryOperator::Add => Op::AddDateTime,
BinaryOperator::Sub => Op::SubDateTime,
BinaryOperator::Add => Op::AddToDateTime,
BinaryOperator::Sub => Op::SubFromDateTime,
BinaryOperator::ConvertTo => Op::ConvertDateTime,
_ => unreachable!("{operator:?} is not valid with a DateTime"), // should be unreachable, because the typechecker will error first
}
Expand Down
4 changes: 4 additions & 0 deletions numbat/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ pub enum RuntimeError {
DateParsingError(chrono::ParseError),
#[error("Unknown timezone: {0}")]
UnknownTimezone(String),
#[error("Exceeded maximum size for time durations")]
DurationOutOfRange,
#[error("DateTime out of range")]
DateTimeOutOfRange,
}

#[derive(Debug, PartialEq, Eq)]
Expand Down
25 changes: 15 additions & 10 deletions numbat/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ pub enum Op {
LogicalNeg,

/// Similar to Add, but has DateTime on the LHS and a quantity on the RHS
AddDateTime,
AddToDateTime,
/// Similar to Sub, but has DateTime on the LHS and a quantity on the RHS
SubDateTime,
SubFromDateTime,
/// Computes the difference between two DateTimes
DiffDateTime,
/// Converts a DateTime value to another timezone
Expand Down Expand Up @@ -122,9 +122,9 @@ impl Op {
Op::Negate
| Op::Factorial
| Op::Add
| Op::AddDateTime
| Op::AddToDateTime
| Op::Subtract
| Op::SubDateTime
| Op::SubFromDateTime
| Op::DiffDateTime
| Op::ConvertDateTime
| Op::Multiply
Expand Down Expand Up @@ -157,9 +157,9 @@ impl Op {
Op::Negate => "Negate",
Op::Factorial => "Factorial",
Op::Add => "Add",
Op::AddDateTime => "AddDateTime",
Op::AddToDateTime => "AddDateTime",
Op::Subtract => "Subtract",
Op::SubDateTime => "SubDateTime",
Op::SubFromDateTime => "SubDateTime",
Op::DiffDateTime => "DiffDateTime",
Op::ConvertDateTime => "ConvertDateTime",
Op::Multiply => "Multiply",
Expand Down Expand Up @@ -649,23 +649,28 @@ impl Vm {
};
self.push_quantity(result.map_err(RuntimeError::QuantityError)?);
}
op @ (Op::AddDateTime | Op::SubDateTime) => {
op @ (Op::AddToDateTime | Op::SubFromDateTime) => {
let rhs = self.pop_quantity();
let lhs = self.pop_datetime();

// for time, the base unit is in seconds
let base = rhs.to_base_unit_representation();
let seconds_f = base.unsafe_value().to_f64();

let duration = chrono::Duration::seconds(seconds_f.trunc() as i64)
let duration = chrono::Duration::try_seconds(seconds_f.trunc() as i64)
.ok_or(RuntimeError::DurationOutOfRange)?
+ chrono::Duration::nanoseconds(
(seconds_f.fract() * 1_000_000_000f64).round() as i64,
);

self.push(Value::DateTime(
match op {
Op::AddDateTime => lhs + duration,
Op::SubDateTime => lhs - duration,
Op::AddToDateTime => lhs
.checked_add_signed(duration)
.ok_or(RuntimeError::DateTimeOutOfRange)?,
Op::SubFromDateTime => lhs
.checked_sub_signed(duration)
.ok_or(RuntimeError::DateTimeOutOfRange)?,
_ => unreachable!(),
},
chrono::Local::now().offset().fix(),
Expand Down