hmrc-rates 0.3.1

HMRC exchange rates (monthly, spot, yearly average, weekly) with bundled history and GBP conversion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use alloc::vec::Vec;

use chrono::{Datelike, NaiveDate};
use rust_decimal::Decimal;

use crate::error::LookupError;
use crate::rate::Rate;
use crate::store::{self, Entry, Series, WeekIdx, Weeks};
use crate::types::{Currency, Period, RateType, YearEnd, YearMonth};

// chrono counts day 1 = 0001-01-01; our day 0 = 1970-01-01
const CE_EPOCH_OFFSET: i32 = 719_163;

fn date_to_day(date: NaiveDate) -> i32 {
    date.num_days_from_ce() - CE_EPOCH_OFFSET
}

fn day_to_date(day: i32) -> Option<NaiveDate> {
    NaiveDate::from_num_days_from_ce_opt(day.checked_add(CE_EPOCH_OFFSET)?)
}

/// The validity range of a weekly index row as a `Period`.
fn week_period(week: &WeekIdx) -> Option<Period> {
    Some(Period::Week {
        start: day_to_date(week.start_day)?,
        end: day_to_date(week.end_day)?,
    })
}

/// £1 = £1 for any period, published or not.
fn gbp_identity(code: &str, period: Period) -> Option<Rate> {
    (Currency::normalize(code) == Some(Currency::GBP.code()))
        .then(|| Rate::new(Decimal::ONE, Currency::GBP, period))
}

/// All HMRC rate tables: bundled data plus (with the `http` feature) fetched periods.
///
/// `Send + Sync`: cloning is cheap, bundled data is shared statics.
///
/// Start with [`Rates::new`].
#[derive(Clone)]
pub struct Rates {
    monthly: Series,
    spot: Series,
    average: Series,
    weeks: Weeks,
}

impl core::fmt::Debug for Rates {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Rates")
            .field("months", &self.monthly.keys().len())
            .field("spot_periods", &self.spot.keys().len())
            .field("average_periods", &self.average.keys().len())
            .field("weeks", &self.weeks.index().len())
            .finish()
    }
}

#[cfg(feature = "bundled")]
impl Default for Rates {
    fn default() -> Rates {
        Rates::new()
    }
}

impl Rates {
    /// The bundled dataset.
    /// Infallible and effectively free.
    /// The tables live in the binary's read-only data, nothing is parsed or allocated.
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::Rates;
    ///
    /// let rates = Rates::new();
    /// assert!(rates.months().count() > 100);
    /// ```
    #[cfg(feature = "bundled")]
    pub fn new() -> Rates {
        Rates {
            monthly: Series::new(crate::bundled::MONTHLY),
            spot: Series::new(crate::bundled::SPOT),
            average: Series::new(crate::bundled::AVERAGE),
            weeks: Weeks::new(crate::bundled::WEEKLY),
        }
    }

    /// A `Rates` with no data at all.
    #[cfg(test)]
    pub(crate) fn empty() -> Rates {
        Rates {
            monthly: Series::new(store::EMPTY_SERIES),
            spot: Series::new(store::EMPTY_SERIES),
            average: Series::new(store::EMPTY_SERIES),
            weeks: Weeks::new(store::EMPTY_WEEKS),
        }
    }

    #[cfg(feature = "http")]
    pub(crate) fn set_period(&mut self, table: RateType, key: i32, entries: Vec<Entry>) {
        match table {
            RateType::Monthly => self.monthly.set(key, entries),
            RateType::Spot => self.spot.set(key, entries),
            RateType::Average => self.average.set(key, entries),
            _ => {}
        }
    }

    /// The monthly rate for `code`, strictly for that month.
    ///
    /// Accepts anything convertible to [`YearMonth`], including `chrono::NaiveDate`.
    /// `"GBP"` (any case) returns the identity rate for any month.
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::Rates;
    /// use rust_decimal::Decimal;
    ///
    /// let rates = Rates::new();
    /// let date = chrono::NaiveDate::from_ymd_opt(2025, 8, 15).unwrap();
    /// let rate = rates.monthly_rate("USD", date)?;
    /// let gbp = rate.to_gbp(Decimal::from(100));
    /// # Ok::<(), hmrc_rates::LookupError>(())
    /// ```
    pub fn monthly_rate(
        &self,
        code: &str,
        year_month: impl Into<YearMonth>,
    ) -> Result<Rate, LookupError> {
        self.monthly_rate_or_earlier(code, year_month, 0)
    }

    /// Like [`Rates::monthly_rate`], but walks back to the nearest earlier
    /// published month, at most `max_months_back` steps.
    ///
    /// This is the crate's only fallback, and it is opt-in.
    /// [`Rate::period`] reveals which month was actually used.
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::{Period, Rates};
    ///
    /// let rates = Rates::new();
    /// let next = rates.months().next_back().unwrap().next(); // not published yet
    /// assert!(rates.monthly_rate("USD", next).is_err()); // strict lookup fails
    /// let rate = rates.monthly_rate_or_earlier("USD", next, 1)?;
    /// assert_ne!(rate.period(), Period::YearMonth(next)); // the substitution is visible
    /// # Ok::<(), hmrc_rates::LookupError>(())
    /// ```
    pub fn monthly_rate_or_earlier(
        &self,
        code: &str,
        year_month: impl Into<YearMonth>,
        max_months_back: u32,
    ) -> Result<Rate, LookupError> {
        let requested = year_month.into();
        // GBP resolves for the requested month itself — no substitution
        if let Some(rate) = gbp_identity(code, Period::YearMonth(requested)) {
            return Ok(rate);
        }
        let mut candidate = requested;
        for _ in 0..=max_months_back {
            if self.monthly.table(candidate.key()).is_some() {
                return self.monthly(candidate)?.rate(code);
            }
            candidate = candidate.prev();
        }
        Err(self.period_missing(RateType::Monthly, Period::YearMonth(requested)))
    }

    /// The whole monthly table for one month.
    pub fn monthly(&self, year_month: impl Into<YearMonth>) -> Result<Table<'_>, LookupError> {
        let year_month = year_month.into();
        let period = Period::YearMonth(year_month);
        match self.monthly.table(year_month.key()) {
            Some(entries) => Ok(Table {
                rate_type: RateType::Monthly,
                period,
                entries,
                known: Known::Series(&self.monthly),
            }),
            None => Err(self.period_missing(RateType::Monthly, period)),
        }
    }

    /// The spot table for a 31 March / 31 December period.
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::{Rates, YearEnd};
    ///
    /// let rates = Rates::new();
    /// let usd = rates.spot(YearEnd::december(2024))?.rate("USD")?;
    /// # Ok::<(), hmrc_rates::LookupError>(())
    /// ```
    pub fn spot(&self, period: YearEnd) -> Result<Table<'_>, LookupError> {
        self.year_end_table(&self.spot, RateType::Spot, period)
    }

    /// The yearly-average table for a 31 March / 31 December period.
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::{Rates, YearEnd};
    ///
    /// let rates = Rates::new();
    /// // Self Assessment style: the average for the year to 31 March 2025.
    /// let eur = rates.average(YearEnd::march(2025))?.rate("EUR")?;
    /// # Ok::<(), hmrc_rates::LookupError>(())
    /// ```
    pub fn average(&self, period: YearEnd) -> Result<Table<'_>, LookupError> {
        self.year_end_table(&self.average, RateType::Average, period)
    }

    /// The weekly-amendment table whose validity range contains `date`.
    ///
    /// Weekly files list only the currencies HMRC amended that week
    /// (series ran 2014-01 to 2016-04, then was discontinued).
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::Rates;
    ///
    /// let rates = Rates::new();
    /// let date = chrono::NaiveDate::from_ymd_opt(2014, 1, 10).unwrap();
    /// let lira = rates.weekly(date)?.rate("TRY")?;
    /// # Ok::<(), hmrc_rates::LookupError>(())
    /// ```
    pub fn weekly(&self, date: NaiveDate) -> Result<Table<'_>, LookupError> {
        let day = date_to_day(date);
        if let Some((week, entries)) = self.weeks.containing(day) {
            if let Some(period) = week_period(&week) {
                return Ok(Table {
                    rate_type: RateType::Weekly,
                    period,
                    entries,
                    known: Known::Weeks(&self.weeks),
                });
            }
        }
        Err(LookupError::PeriodNotAvailable {
            table: RateType::Weekly,
            period: Period::Week {
                start: date,
                end: date,
            },
            available: self.available(RateType::Weekly),
        })
    }

    /// All published months, ascending.
    pub fn months(&self) -> impl DoubleEndedIterator<Item = YearMonth> + use<'_> {
        self.monthly.keys().into_iter().map(YearMonth::from_key)
    }

    /// All published spot periods, ascending.
    pub fn spot_periods(&self) -> impl DoubleEndedIterator<Item = YearEnd> + use<'_> {
        self.spot.keys().into_iter().map(YearEnd::from_key)
    }

    /// All published yearly-average periods, ascending.
    pub fn average_periods(&self) -> impl DoubleEndedIterator<Item = YearEnd> + use<'_> {
        self.average.keys().into_iter().map(YearEnd::from_key)
    }

    /// All weekly-amendment validity ranges, ascending, as [`Period::Week`] items.
    pub fn weeks(&self) -> impl DoubleEndedIterator<Item = Period> + use<'_> {
        self.weeks.index().iter().filter_map(week_period)
    }

    /// Every currency that appears anywhere in the given series, ascending.
    pub fn currencies(&self, table: RateType) -> impl Iterator<Item = Currency> + use<'_> {
        let codes = match table {
            RateType::Monthly => self.monthly.codes(),
            RateType::Spot => self.spot.codes(),
            RateType::Average => self.average.codes(),
            RateType::Weekly => self.weekly_codes(),
        };
        codes.into_iter().map(Currency::from_code)
    }

    fn weekly_codes(&self) -> Vec<[u8; 3]> {
        let mut codes: Vec<[u8; 3]> = self.weeks.arena().iter().map(|e| e.code).collect();
        codes.sort_unstable();
        codes.dedup();
        codes
    }

    fn year_end_table<'a>(
        &'a self,
        series: &'a Series,
        rate_type: RateType,
        period: YearEnd,
    ) -> Result<Table<'a>, LookupError> {
        match series.table(period.key()) {
            Some(entries) => Ok(Table {
                rate_type,
                period: Period::YearEnd(period),
                entries,
                known: Known::Series(series),
            }),
            None => Err(self.period_missing(rate_type, Period::YearEnd(period))),
        }
    }

    /// The loaded range of a series, for `PeriodNotAvailable` messages.
    fn available(&self, table: RateType) -> Option<(Period, Period)> {
        match table {
            RateType::Monthly => self.monthly.first_last().map(|(f, l)| {
                (
                    Period::YearMonth(YearMonth::from_key(f)),
                    Period::YearMonth(YearMonth::from_key(l)),
                )
            }),
            RateType::Spot | RateType::Average => {
                let series = if table == RateType::Spot {
                    &self.spot
                } else {
                    &self.average
                };
                series.first_last().map(|(f, l)| {
                    (
                        Period::YearEnd(YearEnd::from_key(f)),
                        Period::YearEnd(YearEnd::from_key(l)),
                    )
                })
            }
            RateType::Weekly => {
                let idx = self.weeks.index();
                Some((week_period(idx.first()?)?, week_period(idx.last()?)?))
            }
        }
    }

    fn period_missing(&self, table: RateType, period: Period) -> LookupError {
        LookupError::PeriodNotAvailable {
            table,
            period,
            available: self.available(table),
        }
    }
}

#[derive(Copy, Clone)]
enum Known<'a> {
    Series(&'a Series),
    Weeks(&'a Weeks),
}

impl Known<'_> {
    fn knows(&self, code: [u8; 3]) -> bool {
        match self {
            Known::Series(s) => s.knows(code),
            Known::Weeks(w) => w.knows(code),
        }
    }
}

/// A borrowed view of one period's table — resolve once, convert many times.
#[derive(Copy, Clone)]
pub struct Table<'a> {
    rate_type: RateType,
    period: Period,
    entries: &'a [Entry],
    known: Known<'a>,
}

impl core::fmt::Debug for Table<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Table")
            .field("rate_type", &self.rate_type)
            .field("period", &self.period)
            .field("len", &self.entries.len())
            .finish()
    }
}

impl<'a> Table<'a> {
    /// The period this table was published for.
    pub fn period(&self) -> Period {
        self.period
    }

    /// The series this table belongs to.
    pub fn rate_type(&self) -> RateType {
        self.rate_type
    }

    /// The rate for `code` in this period. `"GBP"` always resolves to the identity rate.
    ///
    /// Errors distinguish a code the series has never published
    /// ([`LookupError::UnknownCurrency`]) from one merely absent this period
    /// ([`LookupError::NotInPeriod`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use hmrc_rates::{YearMonth, Rates};
    /// use rust_decimal::Decimal;
    ///
    /// let rates = Rates::new();
    /// let table = rates.monthly(YearMonth::new(2025, 8).unwrap())?;
    /// let eur = table.rate("EUR")?;
    /// let total: Decimal = [1200, 450, 80]
    ///     .into_iter()
    ///     .map(|amount| eur.to_gbp(Decimal::from(amount)))
    ///     .sum();
    /// # Ok::<(), hmrc_rates::LookupError>(())
    /// ```
    pub fn rate(&self, code: &str) -> Result<Rate, LookupError> {
        if let Some(rate) = gbp_identity(code, self.period) {
            return Ok(rate);
        }
        let Some(normalized) = Currency::normalize(code) else {
            return Err(LookupError::UnknownCurrency {
                code: code.trim().into(),
                table: self.rate_type,
            });
        };
        match store::lookup(self.entries, normalized) {
            Some(entry) => Ok(Rate::new(
                entry.decimal(),
                Currency::from_code(normalized),
                self.period,
            )),
            None if self.known.knows(normalized) => Err(LookupError::NotInPeriod {
                currency: Currency::from_code(normalized),
                table: self.rate_type,
                period: self.period,
            }),
            None => Err(LookupError::UnknownCurrency {
                code: code.trim().into(),
                table: self.rate_type,
            }),
        }
    }

    /// Like [`Table::rate`] but `None` on any miss, for when absence isn't exceptional.
    pub fn get(&self, code: &str) -> Option<Rate> {
        self.rate(code).ok()
    }

    /// All `(currency, rate)` pairs in this table, ascending by code.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (Currency, Rate)> + use<'a> {
        let period = self.period;
        self.entries.iter().map(move |e| {
            let currency = Currency::from_code(e.code);
            (currency, Rate::new(e.decimal(), currency, period))
        })
    }

    /// The number of currencies in this table.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// `true` if the table has no entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

#[cfg(test)]
mod empty_tests {
    use super::*;

    #[test]
    fn empty_rates_report_no_data_loaded() {
        let rates = Rates::empty();
        let year_month = YearMonth::new(2025, 8);
        let Some(year_month) = year_month else { return };
        let result = rates.monthly_rate("USD", year_month);
        assert!(
            matches!(
                result,
                Err(LookupError::PeriodNotAvailable {
                    available: None,
                    ..
                })
            ),
            "unexpected: {result:?}"
        );
        assert!(rates.months().next().is_none());
        assert_eq!(rates.currencies(RateType::Spot).count(), 0);
        // GBP identity still holds with no data at all
        assert!(rates.monthly_rate("GBP", year_month).is_ok());
    }
}

#[cfg(all(test, feature = "bundled"))]
#[allow(clippy::unwrap_used)]
mod bundled_tests {
    use super::*;

    #[test]
    fn statics_hold_codegen_invariants() {
        for series in [
            &crate::bundled::MONTHLY,
            &crate::bundled::SPOT,
            &crate::bundled::AVERAGE,
        ] {
            let mut start = 0usize;
            for pair in series.index.windows(2) {
                assert!(
                    pair[0].key < pair[1].key,
                    "index keys not strictly ascending"
                );
            }
            for idx in series.index {
                let table = &series.arena[start..idx.end as usize];
                start = idx.end as usize;
                assert!(!table.is_empty());
                for entry in table {
                    assert!(entry.mantissa > 0);
                    assert!(entry.scale <= 9);
                    assert!(entry.code.iter().all(u8::is_ascii_uppercase));
                }
                for pair in table.windows(2) {
                    assert!(pair[0].code < pair[1].code, "codes not sorted/deduped");
                }
            }
            assert_eq!(start, series.arena.len(), "index does not cover the arena");
        }
        for pair in crate::bundled::WEEKLY.index.windows(2) {
            assert!(pair[0].end_day < pair[1].start_day, "overlapping weeks");
        }
    }

    // Round-trip: the generated statics must match a fresh parse of the source file
    #[cfg(feature = "std")]
    #[test]
    fn codegen_matches_fresh_parse() {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/data/monthly/2025-08.xml");
        let bytes = std::fs::read(path).unwrap();
        let ((year, month), raw) = crate::parse::parse_monthly_xml(&bytes).unwrap();
        let parsed = crate::parse::dedup_majority(raw).unwrap();

        let rates = Rates::new();
        let table = rates.monthly(YearMonth::new(year, month).unwrap()).unwrap();
        assert_eq!(table.len(), parsed.len());
        for rate in &parsed {
            let entry = crate::store::lookup(table.entries, rate.code).unwrap();
            assert_eq!((entry.mantissa, entry.scale), (rate.mantissa, rate.scale));
        }

        // Same for a year-end series: pins build.rs's YearEnd key encoding
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/data/average/2024-12.csv");
        let bytes = std::fs::read(path).unwrap();
        let parsed =
            crate::parse::dedup_majority(crate::parse::parse_rates_csv(&bytes).unwrap()).unwrap();
        let table = rates.average(YearEnd::december(2024)).unwrap();
        assert_eq!(table.len(), parsed.len());
        for rate in &parsed {
            let entry = crate::store::lookup(table.entries, rate.code).unwrap();
            assert_eq!((entry.mantissa, entry.scale), (rate.mantissa, rate.scale));
        }
    }
}