trivet 3.1.0

The trivet Parser Library
Documentation
use trivet::strings::EncodingStandard;
use trivet::ParseResult;
use trivet::Tools;

/// Convert from a string written for the Python standard to one written for the the JSON standard.
pub fn main() -> ParseResult<()> {
    let mut tools = Tools::new();
    let pystring = r#"This is a \"string\" with a \N{black heart suit}."#;
    println!("Original: \"{}\"", pystring);

    // Set the string standard to Python and parse the string.
    tools.set_string_standard(trivet::strings::StringStandard::Python);
    let raw = tools.parse_string(pystring)?;
    println!("Raw:      {}", raw);

    // Set the string standard to JSON and force characters above ASCII to be encoded as hex.
    // Then encode the string.
    tools.set_string_standard(trivet::strings::StringStandard::JSON);
    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
    let second = tools.encode_string(&raw);
    println!("JSON:     \"{}\"", second);

    // Now convert back. Note that changing the standard resets all other options, so we
    // have to set the encoding standard again to encode above ASCII. We also force the use
    // of Unicode code point names. It's not default because most languages don't support
    // them directly and it takes longer.
    tools.set_string_standard(trivet::strings::StringStandard::Python);
    tools.string_encoder.encoding_standard = EncodingStandard::ASCII;
    tools.string_encoder.use_names = true;
    let third = tools.encode_string(&raw);
    println!("Python:   \"{}\"", third);
    Ok(())
}