philiplinden / spacetime

a real(istic) time simulator
https://philiplinden.github.io/spacetime/
Mozilla Public License 2.0
8 stars 0 forks source link

`lofitime` rewrite to use From<T> and Into<T> instead of custom traits #32

Closed philiplinden closed 2 months ago

philiplinden commented 2 months ago

Example

Here's an example I'm using to adapt hifitime::Epochs into egui's DatePickerButton, which only works with chrono::NaiveDates.

In this case I don't care about the loss of precision. I want to use the button to select a date and then use this new date as the starting epoch for a precision timer.

  1. Wrap the hifitime::Epoch with HifiEpoch to enable simple type conversions to chrono types.
  2. Convert the precision epoch to a loose timezone-naive chrono::NaiveDateTime with a simple .into(). This keeps precision up to chrono's limits, which is in the millisecond range. Note that this is no longer inside a wrapper, it's an actual chrono type.
  3. Manipulate the struct as a chrono type as if it were chrono all along.
  4. Wrap the chrono::DateTime with LofiDateTime to enable simple type conversions back to hifitime types.
  5. Use .into() to get the datetime back as a hifitime::Epoch. At this point the epoch only has the precision of chrono but from now on we can use it as a precision epoch with hifitime as if it were an epoch all along.
ui.menu_button("Epoch...", |ui| {
    let hifi_epoch = HifiEpoch(coordinate_time.epoch());
    let chrono_datetime: chrono::NaiveDateTime = hifi_epoch.into(); // convert precision epoch to timezone-aware `chrono::DateTime`
    let mut selected_date = chrono_datetime.date();
    if DatePickerButton::new(&mut selected_date).ui(ui).changed() {
        // Update the Time resource with the selected date
        let new_time = selected_date.and_time(chrono::NaiveTime::from_hms_milli_opt(0, 0, 0, 0).unwrap());
        let new_datetime = new_time.and_utc();
        let lofi_datetime = LofiDateTime(new_datetime);
        coordinate_time.start_epoch = Some(lofi_datetime.into()); // convert new date back to `hifitime::Epoch`
    }
});