rink_core/
helpers.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use crate::{
6    loader::gnu_units,
7    output::{QueryError, QueryReply},
8    parsing::text_query,
9    Context,
10};
11
12#[cfg(feature = "bundle-files")]
13pub static DEFAULT_FILE: Option<&'static str> = Some(include_str!("../definitions.units"));
14#[cfg(not(feature = "bundle-files"))]
15pub static DEFAULT_FILE: Option<&'static str> = None;
16
17#[cfg(feature = "bundle-files")]
18pub static DATES_FILE: Option<&'static str> = Some(include_str!("../datepatterns.txt"));
19#[cfg(not(feature = "bundle-files"))]
20pub static DATES_FILE: Option<&'static str> = None;
21
22#[cfg(feature = "bundle-files")]
23pub static CURRENCY_FILE: Option<&'static str> = Some(include_str!("../currency.units"));
24#[cfg(not(feature = "bundle-files"))]
25pub static CURRENCY_FILE: Option<&'static str> = None;
26
27pub fn eval(ctx: &mut Context, line: &str) -> Result<QueryReply, QueryError> {
28    ctx.update_time();
29    let mut iter = text_query::TokenIterator::new(line.trim()).peekable();
30    let expr = text_query::parse_query(&mut iter);
31    let res = ctx.eval_query(&expr)?;
32    if ctx.save_previous_result {
33        if let QueryReply::Number(ref number_parts) = res {
34            if let Some(ref raw) = number_parts.raw_value {
35                ctx.previous_result = Some(raw.clone());
36            }
37        }
38    }
39    Ok(res)
40}
41
42/// A version of eval() that converts results and errors into strings.
43pub fn one_line(ctx: &mut Context, line: &str) -> Result<String, String> {
44    eval(ctx, line)
45        .as_ref()
46        .map(ToString::to_string)
47        .map_err(ToString::to_string)
48}
49
50/// Tries to create a context that has core definitions only (contents
51/// of definitions.units), will fail if the bundle-files feature isn't enabled.
52/// Mainly intended for unit testing.
53pub fn simple_context() -> Result<Context, String> {
54    let message = "bundle-files feature not enabled, cannot create simple context.";
55
56    let units = DEFAULT_FILE.ok_or(message.to_owned())?;
57    let mut iter = gnu_units::TokenIterator::new(&*units).peekable();
58    let units = gnu_units::parse(&mut iter);
59
60    let dates = DATES_FILE.ok_or(message.to_owned())?;
61    let dates = crate::parsing::datetime::parse_datefile(dates);
62
63    let mut ctx = Context::new();
64    ctx.load(units)?;
65    ctx.load_dates(dates);
66
67    Ok(ctx)
68}
69
70// Returns `env!("CARGO_PKG_VERSION")`, a string in `x.y.z` format.
71pub fn version() -> &'static str {
72    env!("CARGO_PKG_VERSION")
73}