Debian Codegraph @

src/lib.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use std::collections::HashMap;
2
3 use quick_xml::events::Event;
4 use quick_xml::reader::Reader;
5
6 pub type ExchangeRates = HashMap<String, f64>;
7
8 pub fn parse_exchange_rates(xml_content: &str) -> Option<ExchangeRates> {
9 let mut rates = ExchangeRates::default();
10
11 let mut reader = Reader::from_str(xml_content);
12 loop {
13 match reader.read_event().ok()? {
14 Event::Eof => break,
15 Event::Empty(e) => {
16 if e.local_name().as_ref() != b"Cube" {
17 continue;
18 }
19 let currency = &e
20 .try_get_attribute("currency")
21 .ok()??
22 .unescape_value()
23 .ok()?;
24 let rate = &e.try_get_attribute("rate").ok()??.unescape_value().ok()?;
25 let rate = rate.parse().ok()?;
26
27 rates.insert(currency.to_string(), rate);
28 }
29 _ => {}
30 }
31 }
32
33 Some(rates)
34 }
35
36 #[cfg(feature = "fetch-exchangerates")]
37 const ECB_XML_URL: &str = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
38
39 #[cfg(feature = "fetch-exchangerates")]
40 fn fetch_ecb_xml() -> Option<String> {
•41 reqwest::blocking::get(ECB_XML_URL).ok()?.text().ok()
42 }
43
44 #[cfg(feature = "fetch-exchangerates")]
45 pub fn fetch_exchange_rates() -> Option<ExchangeRates> {
46 let xml_content = fetch_ecb_xml()?;
47 parse_exchange_rates(&xml_content)
48 }
49
50 #[cfg(test)]
51 #[cfg(feature = "fetch-exchangerates")]
52 mod tests {
53 use super::*;
54
55 #[test]
56 fn fetch_exchange_rates_works() {
57 fetch_exchange_rates();
58 }
59 }