Skip to content

Commit

Permalink
Oldest valid date initialised only once!
Browse files Browse the repository at this point in the history
**NOTE**: This uses `LazyLock` which was stabilised recently in Rust 1.80.
This means we're effectively pushing the MSRV (minimum supported Rust
version) to 1.80+ which is relatively fresh ([July 2024]).

I'm not too keen on [the alternatives]:
1. No nothing: Create a new datetime every time the `validate_date()` is
   called
   - possibly slow/unnecesary, although maybe not a tragedy
2. Use a dependency just for this (either `lazy_static` or `once_cell`)
  - just seems wrong to use a crate when this is now in the standard library

I think `LazyLock` is just too good to pass on and we should keep it simple
and just use it. From local testing we require 1.74+ anyway so we're "just"
pushing the MSRV 6 Rust releases ahead. And update Rust with `rustup update`
is trivial.

[July 2024]: https://blog.rust-lang.org/2024/07/25/Rust-1.80.0.html
[the alternatives]: rust-lang-nursery/lazy-static.rs#214
  • Loading branch information
xoen committed Oct 6, 2024
1 parent f9d614c commit 11376ae
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! API for retrieving data from the Carbon Intensity API
//! <https://api.carbonintensity.org.uk/>
use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime};
use futures::future;
use std::sync::LazyLock;

use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime};
use reqwest::{Client, StatusCode};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use thiserror::Error;
Expand All @@ -13,6 +15,14 @@ mod target;
pub use region::Region;
pub use target::Target;

// oldest entry available for 2018-05-10 23:30:00
static OLDEST_VALID_DATE: LazyLock<NaiveDateTime> = LazyLock::new(|| {
NaiveDate::from_ymd_opt(2018, 5, 10)
.unwrap()
.and_hms_opt(23, 30, 0)
.unwrap()
});

/// An error communicating with the Carbon Intensity API.
#[derive(Debug, Error)]
pub enum ApiError {
Expand Down Expand Up @@ -231,14 +241,8 @@ fn to_tuples(data: Vec<Data>) -> Result<Vec<IntensityForDate>> {
///
/// Otherwise an `Ok` value with the input datetime is returned
fn validate_date(date: NaiveDateTime) -> Result<NaiveDateTime> {
// oldest entry available for 2018-05-10 23:30:00
let oldest_date = NaiveDate::from_ymd_opt(2018, 5, 10)
.unwrap()
.and_hms_opt(23, 30, 0)
.unwrap();

// check if date is too old
if date < oldest_date {
if date < *OLDEST_VALID_DATE {
return Err(ApiError::DateTooOld);
}

Expand Down

0 comments on commit 11376ae

Please sign in to comment.