jnioche / carbonintensity-api

A simple Rust library to retrieve data from https://api.carbonintensity.org.uk/
Apache License 2.0
10 stars 1 forks source link

`Region` enum and other improvements (breaking changes) #11

Closed xoen closed 1 month ago

xoen commented 1 month ago

Introduced a Region enum which deals with the mapping between numbers (u8) and region ids. Introducing this new type means Rust can check at compile time that no invalid values can be passed to functions dealing with regions (e.g. no need to check region id is within the valid range).

The Region enum allows for parsing from strings, e.g. "4" would be parsed to Region::NorthEastEngland.

The Target enum also got revamped to encapsulate the user input. This means for example that Target::Postcode would contain the postcode String the user provided. This is nice when matching this enum as destructuring can be used to access this value directly, instead of having to parse the user input again.

I've also tweaked the handle_result() function to work with any value that can be displayed (using the std::fmt::Display trait which is used when using to_string() or using macros like println!(). This uses dynamic dispatch but I think for the cli part of the crate this is acceptable. As Region implements this standard Display trait the net effect is that the output would show the human-friendly name of the region, e.g.

xoen$ cargo run -- 13
[...]

Carbon intensity for region London: 82

PS: I've run this locally and it seems to work but please double-check I haven't accidentally broken anything in the process of moving things around :)

NOTE: This is a breaking change - as the public functions signatures changed - so the minor version should be bumped when re-releasing the crate.

xoen commented 1 month ago

Also, if any of the changes don't quite make sense let me know ;)

jnioche commented 1 month ago

This is great @xoen, a far more elegant approach!