6 Commits

Author SHA1 Message Date
75f73e5d5e bump to version 1.1.0 2025-12-17 22:35:09 +01:00
980ae6f8cb breakout async_main 2025-12-17 22:33:31 +01:00
364875a84e Bump MSRV and cleanup with clippy 2025-12-17 22:20:31 +01:00
f388c31594 Don't specify the license twice 2025-12-17 22:14:20 +01:00
Love
837a8e9851 Merge pull request #3 from lov3b/feature/smol-str
Use smolstr since we only expect small strings
2025-12-17 22:12:35 +01:00
0f930271c7 Use smolstr since we only expect small strings 2025-12-17 22:10:46 +01:00
17 changed files with 144 additions and 108 deletions

44
Cargo.lock generated
View File

@@ -91,6 +91,15 @@ version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
[[package]]
name = "borsh"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1da5ab77c1437701eeff7c88d968729e7766172279eab0676857b3d63af7a6f"
dependencies = [
"cfg_aliases",
]
[[package]]
name = "bumpalo"
version = "3.19.1"
@@ -119,6 +128,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chrono"
version = "0.4.42"
@@ -217,7 +232,7 @@ dependencies = [
[[package]]
name = "ecb-rates"
version = "1.0.1"
version = "1.1.0"
dependencies = [
"anyhow",
"chrono",
@@ -227,6 +242,7 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
"smol_str",
"tokio",
]
@@ -961,9 +977,9 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
version = "1.13.1"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "708c0f9d5f54ba0272468c1d306a52c495b31fa155e91bc25371e6df7996908c"
checksum = "21e6f2ab2928ca4291b86736a8bd920a277a399bba1589409d72154ff87c1282"
dependencies = [
"zeroize",
]
@@ -1096,6 +1112,16 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "smol_str"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3498b0a27f93ef1402f20eefacfaa1691272ac4eca1cdc8c596cb0a245d6cbf5"
dependencies = [
"borsh",
"serde_core",
]
[[package]]
name = "socket2"
version = "0.6.1"
@@ -1210,21 +1236,9 @@ dependencies = [
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-native-tls"
version = "0.3.1"

View File

@@ -1,11 +1,10 @@
[package]
name = "ecb-rates"
description = "Query exchange rates from the European Central Bank (ECB)"
version = "1.0.1"
edition = "2021"
version = "1.1.0"
edition = "2024"
authors = ["Love Billenius <lovebillenius@disroot.org>"]
license = "Zlib"
license-file = "LICENSE"
keywords = [
"ECB",
"Bank",
@@ -14,7 +13,7 @@ keywords = [
"rates",
]
repository = "https://github.com/lov3b/ecb-rates"
rust-version = "1.83"
rust-version = "1.92"
categories = ["finance", "command-line-utilities"]
[profile.release]
@@ -34,4 +33,5 @@ quick-xml = { version = "0.38", features = ["async-tokio", "tokio"] }
reqwest = "0.12"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.48", features = ["macros"] }
smol_str = { version = "0.3", features = ["serde"] }
tokio = "1.48"

View File

@@ -3,8 +3,8 @@ use std::io::{BufReader, BufWriter};
use std::path::{Path, PathBuf};
use super::CacheLine;
use crate::os::Os;
use crate::View;
use crate::os::Os;
#[derive(Debug)]
pub struct Cache {

View File

@@ -4,8 +4,8 @@ use chrono::serde::ts_seconds;
use chrono::{DateTime, Datelike, FixedOffset, Local, NaiveDate, TimeDelta, Utc, Weekday};
use serde::{Deserialize, Serialize};
use crate::models::ExchangeRateResult;
use crate::Hollidays;
use crate::models::ExchangeRateResult;
const CET: FixedOffset = unsafe { FixedOffset::east_opt(3600).unwrap_unchecked() };

View File

@@ -1,14 +1,14 @@
use clap::{arg, Parser, ValueEnum};
use clap::{Parser, ValueEnum};
use smol_str::SmolStr;
use super::{ShowDays, SortBy};
#[derive(Debug, Parser)]
#[command(author, version, about)]
pub struct Cli {
/// Which currencies do you want to fetch rates for?
#[arg(long = "currencies", short = 'c')]
pub currencies: Vec<String>,
pub currencies: Vec<SmolStr>,
#[arg(value_enum, default_value_t = FormatOption::Plain)]
pub command: FormatOption,
@@ -35,13 +35,13 @@ pub struct Cli {
/// Recalculate to the perspective from an included currency
#[arg(long = "perspective", short = 'p')]
pub perspective: Option<String>,
pub perspective: Option<SmolStr>,
/// Invert the rate
#[arg(long = "invert", short = 'i')]
pub should_invert: bool,
//// Max decimals to keep in price.
/// Max decimals to keep in price.
#[arg(long = "max-decimals", short = 'd', default_value_t = 5)]
pub max_decimals: u8,

View File

@@ -9,7 +9,7 @@ pub enum SortBy {
impl SortBy {
pub fn get_comparer(&self) -> fn(&(&str, f64), &(&str, f64)) -> std::cmp::Ordering {
match self {
Self::Currency => |a, b| a.0.cmp(&b.0),
Self::Currency => |a, b| a.0.cmp(b.0),
Self::Rate => |a, b| a.1.total_cmp(&b.1),
}
}

View File

@@ -7,6 +7,12 @@ pub struct HeaderDescription<'a> {
header_description: [&'a str; 2],
}
impl<'a> Default for HeaderDescription<'a> {
fn default() -> Self {
Self::new()
}
}
impl<'a> HeaderDescription<'a> {
pub fn new() -> Self {
Self {

View File

@@ -134,14 +134,14 @@ mod tests {
#[should_panic]
fn test_year_too_low() {
disable_panic_stack_trace();
let _ = Hollidays::new(1000);
let _ = Hollidays::new(1000);
}
#[test]
#[should_panic]
fn test_year_too_high() {
disable_panic_stack_trace();
let _ = Hollidays::new(9999);
let _ = Hollidays::new(9999);
}
fn disable_panic_stack_trace() {

View File

@@ -1,4 +1,4 @@
pub mod cache;
pub mod caching;
pub mod cli;
mod header_description;
mod holiday;
@@ -13,16 +13,15 @@ pub use header_description::HeaderDescription;
pub use holiday::Hollidays;
pub use view::View;
const APP_NAME: &'static str = "ECB-rates";
const APP_NAME: &str = "ECB-rates";
const DEFAULT_WIDTH: usize = 20;
pub mod ecb_url {
pub const TODAY: &'static str = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
pub const TODAY: &str = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
pub mod hist {
pub const DAYS_ALL: &'static str =
"https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml";
pub const DAYS_90: &'static str =
pub const DAYS_ALL: &str = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml";
pub const DAYS_90: &str =
"https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml";
}
}

View File

@@ -1,7 +1,9 @@
use anyhow::Context;
use clap::Parser as _;
use ecb_rates::cache::{Cache, CacheLine};
use ecb_rates::caching::{Cache, CacheLine};
use ecb_rates::HeaderDescription;
use reqwest::{Client, IntoUrl};
use smol_str::StrExt;
use std::process::ExitCode;
use ecb_rates::cli::{Cli, FormatOption};
@@ -16,22 +18,40 @@ async fn get_and_parse(url: impl IntoUrl) -> anyhow::Result<Vec<ExchangeRateResu
parse(&xml_content)
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> ExitCode {
let mut cli = Cli::parse();
fn main() -> ExitCode {
let cli = Cli::parse();
let runtime = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(runtime) => runtime,
Err(e) => {
eprintln!("Failed to initialize asynchronous runtime: {:?}", e);
return ExitCode::FAILURE;
}
};
match runtime.block_on(async_main(cli)) {
Ok(_) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("Fatal: {:?}", e);
ExitCode::FAILURE
}
}
}
async fn async_main(mut cli: Cli) -> anyhow::Result<()> {
if cli.force_color {
colored::control::set_override(true);
}
let mut header_description = HeaderDescription::new();
let use_cache = !cli.no_cache;
let view = match cli.show_days.to_view() {
Some(v) => v,
None => {
eprintln!("It doesn't make any sence to fetch 0 days right?");
return ExitCode::SUCCESS;
}
};
let view = cli
.show_days
.to_view()
.context("It doesn't make any sence to fetch 0 days right?")?;
let mut cache = if use_cache { Cache::load(&view) } else { None };
let cache_ok = cache.as_ref().map_or_else(
|| false,
@@ -47,14 +67,9 @@ async fn main() -> ExitCode {
.exchange_rate_results
.clone()
} else {
let parsed = match get_and_parse(view.to_ecb_url()).await {
Ok(k) => k,
Err(e) => {
eprintln!("Failed to get/parse data from ECB: {}", e);
return ExitCode::FAILURE;
}
};
let parsed = get_and_parse(view.to_ecb_url())
.await
.context("Failed to get/parse data from ECB")?;
if !cache_ok {
let not_equal_cache = cache.as_ref().map_or_else(
|| true,
@@ -65,27 +80,20 @@ async fn main() -> ExitCode {
},
);
if not_equal_cache {
if let Some(cache_safe) = cache.as_mut() {
let cache_line = CacheLine::new(parsed.clone());
cache_safe.set_cache_line(cache_line);
if let Err(e) = cache_safe.save() {
eprintln!("Failed to save to cache with: {:?}", e);
}
}
if not_equal_cache && let Some(cache_safe) = cache.as_mut() {
let cache_line = CacheLine::new(parsed.clone());
cache_safe.set_cache_line(cache_line);
cache_safe.save()?;
}
}
parsed
};
cli.perspective = cli.perspective.map(|s| s.to_uppercase());
cli.perspective = cli.perspective.map(|s| s.to_uppercase_smolstr());
if let Some(currency) = cli.perspective.as_ref() {
header_description.replace_eur(&currency);
let error_occured = change_perspective(&mut parsed, &currency).is_none();
if error_occured {
eprintln!("The currency wasn't in the data from the ECB!");
return ExitCode::FAILURE;
}
header_description.replace_eur(currency);
change_perspective(&mut parsed, currency)
.context("The currency wasn't in the data from the ECB!")?;
}
if cli.should_invert {
@@ -99,7 +107,7 @@ async fn main() -> ExitCode {
let currencies = cli
.currencies
.iter()
.map(|x| x.to_uppercase())
.map(|x| x.to_uppercase_smolstr())
.collect::<Vec<_>>();
filter_currencies(&mut parsed, &currencies);
@@ -160,5 +168,5 @@ async fn main() -> ExitCode {
};
println!("{}", &output);
ExitCode::SUCCESS
Ok(())
}

View File

@@ -1,8 +1,9 @@
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct ExchangeRateResult {
pub time: String,
pub rates: HashMap<String, f64>,
pub time: SmolStr,
pub rates: HashMap<SmolStr, f64>,
}

View File

@@ -1,38 +1,45 @@
use std::collections::HashMap;
use quick_xml::events::Event;
use quick_xml::Reader;
use quick_xml::events::Event;
use smol_str::SmolStr;
use crate::models::ExchangeRateResult;
fn smol_from_utf8(bytes: &[u8]) -> SmolStr {
str::from_utf8(bytes)
.map(SmolStr::new)
.unwrap_or_else(|_| SmolStr::new(String::from_utf8_lossy(bytes)))
}
pub fn parse(xml: &str) -> anyhow::Result<Vec<ExchangeRateResult>> {
let mut reader = Reader::from_str(xml);
reader.config_mut().trim_text(true);
let mut results = Vec::new();
let mut current_time: Option<String> = None;
let mut current_time: Option<SmolStr> = None;
let mut inside_cube_time = false;
let mut current_rates = HashMap::new();
fn handle_cube_element(
e: &quick_xml::events::BytesStart,
current_time: &mut Option<String>,
current_time: &mut Option<SmolStr>,
inside_cube_time: &mut bool,
current_rates: &mut HashMap<String, f64>,
current_rates: &mut HashMap<SmolStr, f64>,
results: &mut Vec<ExchangeRateResult>,
) -> anyhow::Result<()> {
if e.name().local_name().as_ref() != b"Cube" {
return Ok(());
}
let mut time_attr: Option<String> = None;
let mut currency_attr: Option<String> = None;
let mut rate_attr: Option<String> = None;
let mut time_attr: Option<SmolStr> = None;
let mut currency_attr: Option<SmolStr> = None;
let mut rate_attr: Option<SmolStr> = None;
for attr_result in e.attributes() {
let attr = attr_result?;
let key = attr.key.as_ref();
let val = String::from_utf8_lossy(attr.value.as_ref()).to_string();
let val = smol_from_utf8(attr.value.as_ref());
match key {
b"time" => {
@@ -61,11 +68,9 @@ pub fn parse(xml: &str) -> anyhow::Result<Vec<ExchangeRateResult>> {
*inside_cube_time = true;
}
if *inside_cube_time {
if let (Some(c), Some(r_str)) = (currency_attr, rate_attr) {
let r = r_str.parse::<f64>()?;
current_rates.insert(c, r);
}
if *inside_cube_time && let (Some(c), Some(r_str)) = (currency_attr, rate_attr) {
let r = r_str.parse::<f64>()?;
current_rates.insert(c, r);
}
Ok(())

View File

@@ -1,11 +1,10 @@
mod table_display;
mod table_getter;
mod table_owned;
mod table_ref;
mod table_trait;
mod table_display;
pub use table_getter::TableGet;
pub use table_owned::Table;
pub use table_ref::TableRef;
pub use table_trait::TableTrait;

View File

@@ -1,27 +1,29 @@
use std::fmt::Display;
use smol_str::SmolStr;
use crate::DEFAULT_WIDTH;
use crate::cli::SortBy;
use crate::models::ExchangeRateResult;
use crate::DEFAULT_WIDTH;
use super::table_display::helper_table_print;
use super::{TableGet, TableTrait};
pub struct Table {
pub(super) header: Option<String>,
pub(super) column_left: String,
pub(super) column_right: String,
pub(super) rows: Vec<(String, f64)>,
pub(super) header: Option<SmolStr>,
pub(super) column_left: SmolStr,
pub(super) column_right: SmolStr,
pub(super) rows: Vec<(SmolStr, f64)>,
pub color: bool,
pub width: usize,
pub left_offset: usize,
}
impl<'a> TableTrait<'a> for Table {
type Header = String;
type ColumnLeft = String;
type ColumnRight = String;
type RowLeft = String;
type Header = SmolStr;
type ColumnLeft = SmolStr;
type ColumnRight = SmolStr;
type RowLeft = SmolStr;
fn new(
header: Option<Self::Header>,
@@ -59,8 +61,8 @@ impl<'a> TableTrait<'a> for Table {
}
impl TableGet for Table {
type RowLeftRef = String;
type RowRightRef = String;
type RowLeftRef = SmolStr;
type RowRightRef = SmolStr;
fn get_header(&self) -> Option<&str> {
self.header.as_deref()
@@ -77,7 +79,7 @@ impl TableGet for Table {
fn get_width(&self) -> usize {
self.width
}
fn get_left_offset(&self) -> usize {
self.left_offset
}
@@ -85,7 +87,7 @@ impl TableGet for Table {
impl From<ExchangeRateResult> for Table {
fn from(value: ExchangeRateResult) -> Self {
let mut table = Table::new(Some(value.time), "Currency".to_string(), "Rate".to_string());
let mut table = Table::new(Some(value.time), "Currency".into(), "Rate".into());
for (key, val) in value.rates.into_iter() {
table.add_row(key, val);
}

View File

@@ -1,13 +1,13 @@
use std::fmt::Display;
use crate::DEFAULT_WIDTH;
use crate::cli::SortBy;
use crate::models::ExchangeRateResult;
use crate::DEFAULT_WIDTH;
use super::Table;
use super::table_display::helper_table_print;
use super::table_getter::TableGet;
use super::table_trait::TableTrait;
use super::Table;
pub struct TableRef<'a> {
header: Option<&'a str>,
@@ -78,7 +78,7 @@ impl<'a> TableGet for TableRef<'a> {
fn get_width(&self) -> usize {
self.width
}
fn get_left_offset(&self) -> usize {
self.left_offset
}

View File

@@ -1,10 +1,12 @@
use std::{borrow::BorrowMut, collections::HashMap, ops::Deref};
use smol_str::SmolStr;
use crate::models::ExchangeRateResult;
pub fn filter_currencies(exchange_rate_results: &mut [ExchangeRateResult], currencies: &[String]) {
pub fn filter_currencies(exchange_rate_results: &mut [ExchangeRateResult], currencies: &[SmolStr]) {
for exchange_rate in exchange_rate_results {
let rates_ptr: *mut HashMap<String, f64> = &mut exchange_rate.rates;
let rates_ptr: *mut HashMap<_, _> = &mut exchange_rate.rates;
exchange_rate
.rates
.keys()
@@ -32,7 +34,7 @@ pub fn change_perspective(
*iter_rate = eur_rate * iter_rate.deref();
}
rate_res.rates.insert("EUR".to_string(), eur_rate);
rate_res.rates.insert("EUR".into(), eur_rate);
}
Some(())
}