Tools

Struct Tools 

Source
pub struct Tools {
    pub number_parser: NumberParser,
    pub string_parser: StringParser,
    pub string_encoder: StringEncoder,
    pub keyword_parser: KeywordParser,
}
Expand description

Provide quick access to some simple utilities without having to create a parser, etc.

To use this, make an instance. If you want a particular string standard, use Self::set_string_standard to select it. If you need deeper configuration, then directly access the fields.

Fields§

§number_parser: NumberParser

The number decoder to use.

§string_parser: StringParser

The string parser to use.

§string_encoder: StringEncoder

The string encoder to use.

§keyword_parser: KeywordParser

The keyword parsers to use.

Implementations§

Source§

impl Tools

Source

pub fn new() -> Self

Make a new instance.

Examples found in repository?
examples/book_cookbook_number.rs (line 4)
3pub fn main() -> ParseResult<()> {
4    let tools = Tools::new();
5
6    // Parse floats in various bases.
7    assert_eq!(tools.parse_f64("0.525")?, 0.525);
8    assert_eq!(tools.parse_f64("+0x0.82")?, 0.5078125);
9    assert_eq!(tools.parse_f64("-0b0.1e-2")?, -0.125);
10
11    // Parse some integers. Only 128-bit signed and unsigned integers are parsed by tools
12    // at present, and leading plus signs (`+`) are not allowed.
13    assert_eq!(tools.parse_u128("101")?, 101);
14    assert_eq!(tools.parse_u128("0x101")?, 257);
15    assert_eq!(tools.parse_i128("-101")?, -101);
16    Ok(())
17}
More examples
Hide additional examples
examples/book_cookbook_json.rs (line 17)
3pub fn main() {
4    let example = r##"
5        [{"color":"red","value":"#f00"},{"color":"green","value":"#0f0"},
6        {"color":"blue","value":"#00f"},{"color":"cyan","value":"#0ff"},
7        {"color":"magenta","value":"#f0f"},
8        {
9                "color":
10                    "yellow",
11                "value":
12                    "#ff0"
13        },
14        {   "color": "black",
15            "value": "#000" }]
16    "##;
17    let tools = Tools::new();
18    let json = tools.parse_json(example).unwrap();
19    println!("Internal:\n{:?}\n", json);
20    println!("JSON:\n{}", json);
21}
examples/book_cookbook_datetime.rs (line 14)
3pub fn main() {
4    let samples = &[
5        "1905-05-27",             // Start of Battle of Tsushima.
6        "1937-08-07",             // Japan invades China.
7        "1941-06-22",             // Germany invades Russia.
8        "11:11",                  // Time to turn the clocks upside-down.
9        "00:00:00.001",           // One millisecond past midnight.
10        "1941-12-07T07:48-10:00", // Japan bombs Pearl Harbor.
11        "1954-02-28 18:45Z",      // US Castle Bravo test.
12        "1968-01-22T03:00-05:00", // Random date.
13    ];
14    let tools = Tools::new();
15    for sample in samples {
16        println!("Input:    {}", sample);
17        let datetime = tools.parse_date_time(sample).unwrap().unwrap();
18        println!("Internal: {:?}", datetime);
19        println!("Output:   {}", datetime);
20        println!();
21    }
22}
examples/book_cookbook_string.rs (line 7)
6pub fn main() -> ParseResult<()> {
7    let mut tools = Tools::new();
8    let pystring = r#"This is a \"string\" with a \N{black heart suit}."#;
9    println!("Original: \"{}\"", pystring);
10
11    // Set the string standard to Python and parse the string.
12    tools.set_string_standard(trivet::strings::StringStandard::Python);
13    let raw = tools.parse_string(pystring)?;
14    println!("Raw:      {}", raw);
15
16    // Set the string standard to JSON and force characters above ASCII to be encoded as hex.
17    // Then encode the string.
18    tools.set_string_standard(trivet::strings::StringStandard::JSON);
19    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
20    let second = tools.encode_string(&raw);
21    println!("JSON:     \"{}\"", second);
22
23    // Now convert back. Note that changing the standard resets all other options, so we
24    // have to set the encoding standard again to encode above ASCII. We also force the use
25    // of Unicode code point names. It's not default because most languages don't support
26    // them directly and it takes longer.
27    tools.set_string_standard(trivet::strings::StringStandard::Python);
28    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
29    tools.string_encoder.use_names = true;
30    let third = tools.encode_string(&raw);
31    println!("Python:   \"{}\"", third);
32    Ok(())
33}
Source

pub fn set_string_standard(&mut self, std: StringStandard) -> &mut Self

Set the string standard.

Examples found in repository?
examples/book_cookbook_string.rs (line 12)
6pub fn main() -> ParseResult<()> {
7    let mut tools = Tools::new();
8    let pystring = r#"This is a \"string\" with a \N{black heart suit}."#;
9    println!("Original: \"{}\"", pystring);
10
11    // Set the string standard to Python and parse the string.
12    tools.set_string_standard(trivet::strings::StringStandard::Python);
13    let raw = tools.parse_string(pystring)?;
14    println!("Raw:      {}", raw);
15
16    // Set the string standard to JSON and force characters above ASCII to be encoded as hex.
17    // Then encode the string.
18    tools.set_string_standard(trivet::strings::StringStandard::JSON);
19    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
20    let second = tools.encode_string(&raw);
21    println!("JSON:     \"{}\"", second);
22
23    // Now convert back. Note that changing the standard resets all other options, so we
24    // have to set the encoding standard again to encode above ASCII. We also force the use
25    // of Unicode code point names. It's not default because most languages don't support
26    // them directly and it takes longer.
27    tools.set_string_standard(trivet::strings::StringStandard::Python);
28    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
29    tools.string_encoder.use_names = true;
30    let third = tools.encode_string(&raw);
31    println!("Python:   \"{}\"", third);
32    Ok(())
33}
Source

pub fn parse_string(&self, body: &str) -> ParseResult<String>

Parse the argument as a string, processing escapes, etc. The entire content of the string is parsed. For details on this, see the crate::strings::StringParser struct. Think of this as converting a \n into a newline.

let result = trivet::Tools::new().parse_string(r#"\u{2020}\r\n"#)?;
assert_eq!(result, "†\r\n");
Examples found in repository?
examples/book_cookbook_string.rs (line 13)
6pub fn main() -> ParseResult<()> {
7    let mut tools = Tools::new();
8    let pystring = r#"This is a \"string\" with a \N{black heart suit}."#;
9    println!("Original: \"{}\"", pystring);
10
11    // Set the string standard to Python and parse the string.
12    tools.set_string_standard(trivet::strings::StringStandard::Python);
13    let raw = tools.parse_string(pystring)?;
14    println!("Raw:      {}", raw);
15
16    // Set the string standard to JSON and force characters above ASCII to be encoded as hex.
17    // Then encode the string.
18    tools.set_string_standard(trivet::strings::StringStandard::JSON);
19    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
20    let second = tools.encode_string(&raw);
21    println!("JSON:     \"{}\"", second);
22
23    // Now convert back. Note that changing the standard resets all other options, so we
24    // have to set the encoding standard again to encode above ASCII. We also force the use
25    // of Unicode code point names. It's not default because most languages don't support
26    // them directly and it takes longer.
27    tools.set_string_standard(trivet::strings::StringStandard::Python);
28    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
29    tools.string_encoder.use_names = true;
30    let third = tools.encode_string(&raw);
31    println!("Python:   \"{}\"", third);
32    Ok(())
33}
Source

pub fn encode_string(&self, body: &str) -> String

Encode the argument as a string, expanding characters into escape codes as needed. The entire content of the string is encoded. See crate::strings::StringEncoder for details. Think of this as turning a newline into \n.

let result = trivet::Tools::new().encode_string("\u{2020}\r\n");
assert_eq!(result, r#"†\r\n"#);
Examples found in repository?
examples/book_cookbook_string.rs (line 20)
6pub fn main() -> ParseResult<()> {
7    let mut tools = Tools::new();
8    let pystring = r#"This is a \"string\" with a \N{black heart suit}."#;
9    println!("Original: \"{}\"", pystring);
10
11    // Set the string standard to Python and parse the string.
12    tools.set_string_standard(trivet::strings::StringStandard::Python);
13    let raw = tools.parse_string(pystring)?;
14    println!("Raw:      {}", raw);
15
16    // Set the string standard to JSON and force characters above ASCII to be encoded as hex.
17    // Then encode the string.
18    tools.set_string_standard(trivet::strings::StringStandard::JSON);
19    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
20    let second = tools.encode_string(&raw);
21    println!("JSON:     \"{}\"", second);
22
23    // Now convert back. Note that changing the standard resets all other options, so we
24    // have to set the encoding standard again to encode above ASCII. We also force the use
25    // of Unicode code point names. It's not default because most languages don't support
26    // them directly and it takes longer.
27    tools.set_string_standard(trivet::strings::StringStandard::Python);
28    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
29    tools.string_encoder.use_names = true;
30    let third = tools.encode_string(&raw);
31    println!("Python:   \"{}\"", third);
32    Ok(())
33}
Source

pub fn parse_i128(&self, body: &str) -> ParseResult<i128>

Parse the string as an i128. If a radix indicator is present at the start, then the string is parsed in that radix.

let value = trivet::Tools::new().parse_i128("-0xe021_18f0")?;
assert_eq!(value, -0xe021_18f0);
Examples found in repository?
examples/book_cookbook_number.rs (line 15)
3pub fn main() -> ParseResult<()> {
4    let tools = Tools::new();
5
6    // Parse floats in various bases.
7    assert_eq!(tools.parse_f64("0.525")?, 0.525);
8    assert_eq!(tools.parse_f64("+0x0.82")?, 0.5078125);
9    assert_eq!(tools.parse_f64("-0b0.1e-2")?, -0.125);
10
11    // Parse some integers. Only 128-bit signed and unsigned integers are parsed by tools
12    // at present, and leading plus signs (`+`) are not allowed.
13    assert_eq!(tools.parse_u128("101")?, 101);
14    assert_eq!(tools.parse_u128("0x101")?, 257);
15    assert_eq!(tools.parse_i128("-101")?, -101);
16    Ok(())
17}
Source

pub fn parse_u128(&self, body: &str) -> ParseResult<u128>

Parse the string as a u128. If a radix indicator is present at the start, then the string is parsed in that radix.

let value = trivet::Tools::new().parse_u128("0xe021_18f0")?;
assert_eq!(value, 0xe021_18f0);
Examples found in repository?
examples/book_cookbook_number.rs (line 13)
3pub fn main() -> ParseResult<()> {
4    let tools = Tools::new();
5
6    // Parse floats in various bases.
7    assert_eq!(tools.parse_f64("0.525")?, 0.525);
8    assert_eq!(tools.parse_f64("+0x0.82")?, 0.5078125);
9    assert_eq!(tools.parse_f64("-0b0.1e-2")?, -0.125);
10
11    // Parse some integers. Only 128-bit signed and unsigned integers are parsed by tools
12    // at present, and leading plus signs (`+`) are not allowed.
13    assert_eq!(tools.parse_u128("101")?, 101);
14    assert_eq!(tools.parse_u128("0x101")?, 257);
15    assert_eq!(tools.parse_i128("-101")?, -101);
16    Ok(())
17}
Source

pub fn parse_f64(&self, body: &str) -> ParseResult<f64>

Parse the string as an f64. If a radix indicator is present at the start, then the string is parsed in that radix.

let value = trivet::Tools::new().parse_f64("0.65e-14")?;
assert_eq!(value, 0.65e-14);
Examples found in repository?
examples/book_cookbook_number.rs (line 7)
3pub fn main() -> ParseResult<()> {
4    let tools = Tools::new();
5
6    // Parse floats in various bases.
7    assert_eq!(tools.parse_f64("0.525")?, 0.525);
8    assert_eq!(tools.parse_f64("+0x0.82")?, 0.5078125);
9    assert_eq!(tools.parse_f64("-0b0.1e-2")?, -0.125);
10
11    // Parse some integers. Only 128-bit signed and unsigned integers are parsed by tools
12    // at present, and leading plus signs (`+`) are not allowed.
13    assert_eq!(tools.parse_u128("101")?, 101);
14    assert_eq!(tools.parse_u128("0x101")?, 257);
15    assert_eq!(tools.parse_i128("-101")?, -101);
16    Ok(())
17}
Source

pub fn parse_keyword(&self, body: &str) -> ParseResult<String>

Parse a keyword.

let value = trivet::Tools::new().parse_keyword("james_madison")?;
assert_eq!(value, "james_madison");
Source

pub fn parse_date_time(&self, body: &str) -> ParseResult<Option<DateTime>>

Parse the string as a date and/or time.

use trivet::parsers::datetime::{DateTime, Date};
let value = trivet::Tools::new().parse_date_time("2015-05-15")?;
let date = DateTime::Date(Date { year: 2015, month: 5, day: 15});
assert_eq!(value.unwrap(), date);
Examples found in repository?
examples/book_cookbook_datetime.rs (line 17)
3pub fn main() {
4    let samples = &[
5        "1905-05-27",             // Start of Battle of Tsushima.
6        "1937-08-07",             // Japan invades China.
7        "1941-06-22",             // Germany invades Russia.
8        "11:11",                  // Time to turn the clocks upside-down.
9        "00:00:00.001",           // One millisecond past midnight.
10        "1941-12-07T07:48-10:00", // Japan bombs Pearl Harbor.
11        "1954-02-28 18:45Z",      // US Castle Bravo test.
12        "1968-01-22T03:00-05:00", // Random date.
13    ];
14    let tools = Tools::new();
15    for sample in samples {
16        println!("Input:    {}", sample);
17        let datetime = tools.parse_date_time(sample).unwrap().unwrap();
18        println!("Internal: {:?}", datetime);
19        println!("Output:   {}", datetime);
20        println!();
21    }
22}
Source

pub fn parse_json(&self, body: &str) -> ParseResult<JSON>

Parse the string as a JSON value.

use trivet::parsers::json::JSON;
let value = trivet::Tools::new().parse_json(r#" { "Python": 1, "C": 2, "Rust": 20 } "#)?;
if let JSON::Object(map) = value {
    if let Some(JSON::Number(position)) = map.get("Rust") {
        assert_eq!(*position, 20.0)
    } else {
        panic!("Expected a number")
    }
} else {
    panic!("Expected a object")
}
Examples found in repository?
examples/book_cookbook_json.rs (line 18)
3pub fn main() {
4    let example = r##"
5        [{"color":"red","value":"#f00"},{"color":"green","value":"#0f0"},
6        {"color":"blue","value":"#00f"},{"color":"cyan","value":"#0ff"},
7        {"color":"magenta","value":"#f0f"},
8        {
9                "color":
10                    "yellow",
11                "value":
12                    "#ff0"
13        },
14        {   "color": "black",
15            "value": "#000" }]
16    "##;
17    let tools = Tools::new();
18    let json = tools.parse_json(example).unwrap();
19    println!("Internal:\n{:?}\n", json);
20    println!("JSON:\n{}", json);
21}

Trait Implementations§

Source§

impl Default for Tools

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Tools

§

impl !RefUnwindSafe for Tools

§

impl !Send for Tools

§

impl !Sync for Tools

§

impl Unpin for Tools

§

impl !UnwindSafe for Tools

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.