book_cookbook_string/
book_cookbook_string.rs

1use trivet::strings::EncodingStandard;
2use trivet::ParseResult;
3use trivet::Tools;
4
5/// Convert from a string written for the Python standard to one written for the the JSON standard.
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}