Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Comments¶
The serde_yaml crate is the best tool for parsing YAML in Rust.
:sccache 1
:dep serde = ">=1.0.137"
:dep serde_yaml = ">=0.8.24"sccache: true
use std::fs
use std::collections::BTreeMap;let mut map = BTreeMap::new();
map.insert("x".to_string(), 1.0);
map.insert("y".to_string(), f64::NAN);
map{"x": 1.0, "y": NaN}Serialize the above BTreeMap to a YAML string.
let s = serde_yaml::to_string(&map).unwrap();
println!("{s}");---
x: 1.0
y: .nan
Deserialize the above string back to a Rust type.
let deserialized_map: BTreeMap<String, f64> = serde_yaml::from_str(&s)?;
deserialized_map{"x": 1.0, "y": NaN}let s = fs::read_to_string("tests.yaml").unwrap();
println!("{s}");_11_highcard:
- - 9d
- 8d Ah 3c 2s 7h
- 2c Kc Qc Jc Tc
- .nan
- - 2j
- 8d Qs 3c 2s 7h
- 2c Kc Qc Jc Tc
- .nan
_11_other:
- - Ac
- 6d 5c 3c 2s 3j
- Qc Jh Td 9d 2j
- .nan
- - 2j
- 8d 6h 5c 4s 7h
- 2c Kc Qc Jc Tc
- .nan
_11_pair:
- - Ac
- Td 5c 3c 2s Th
- Qc Jh Ts 9d 2j
- .nan
- - Ac
- 5d 5c 3c 2s Th
- Qc Jh Ts 9d 2j
- .nan
let deserialized_map: BTreeMap<String, Vec<(String, String, String, f64)>> = serde_yaml::from_str(&s).unwrap();
deserialized_map{"_11_highcard": [("9d", "8d Ah 3c 2s 7h", "2c Kc Qc Jc Tc", NaN), ("2j", "8d Qs 3c 2s 7h", "2c Kc Qc Jc Tc", NaN)], "_11_other": [("Ac", "6d 5c 3c 2s 3j", "Qc Jh Td 9d 2j", NaN), ("2j", "8d 6h 5c 4s 7h", "2c Kc Qc Jc Tc", NaN)], "_11_pair": [("Ac", "Td 5c 3c 2s Th", "Qc Jh Ts 9d 2j", NaN), ("Ac", "5d 5c 3c 2s Th", "Qc Jh Ts 9d 2j", NaN)]}let s = serde_yaml::to_string(&deserialized_map).unwrap();
println!("{s}");---
_11_highcard:
- - 9d
- 8d Ah 3c 2s 7h
- 2c Kc Qc Jc Tc
- .nan
- - 2j
- 8d Qs 3c 2s 7h
- 2c Kc Qc Jc Tc
- .nan
_11_other:
- - Ac
- 6d 5c 3c 2s 3j
- Qc Jh Td 9d 2j
- .nan
- - 2j
- 8d 6h 5c 4s 7h
- 2c Kc Qc Jc Tc
- .nan
_11_pair:
- - Ac
- Td 5c 3c 2s Th
- Qc Jh Ts 9d 2j
- .nan
- - Ac
- 5d 5c 3c 2s Th
- Qc Jh Ts 9d 2j
- .nan
use std::fs::File;
use std::io::{BufWriter, Write};
let f = File::create("out.yaml").expect("Unable to create the file out.yaml");
let mut bw = BufWriter::new(f);
serde_yaml::to_writer(bw, &deserialized_map).unwrap();