Skip to content

Instantly share code, notes, and snippets.

@git314
Last active March 30, 2021 10:17
Show Gist options
  • Save git314/ea2f2b842406273c015f674e52b13396 to your computer and use it in GitHub Desktop.
Save git314/ea2f2b842406273c015f674e52b13396 to your computer and use it in GitHub Desktop.
Make a Hashmap in Rust
use toml::Value;
use pad::{PadStr, Alignment};
use std::collections::BTreeMap;
use console::style;
fn main() {
//toml_hash is a `BTreeMap<std::string::String, Vec<Value>>`
let toml_hash: BTreeMap<String, Vec<toml::Value>> = toml::from_str(r#"
foo = [1,nan,3]
bar = ["a","b","c"]
baz = [2021-03-29, 2020-03-29, 2020-03-29]
barbaz = [1.0, 2.2, 3.3]
"#).unwrap();
//th is a `BTreeMap<std::string::String, Vec<std::string::String>>`
let value_types: BTreeMap<String, Vec<String>> = toml_hash
.into_iter()
.map(|(k, v)| (k, v.into_iter().map(|v|
match v {
Value::String(_v) => format!("<str>"),
Value::Integer(_v) => format!("<int>"),
Value::Float(_v) => format!("<dbl>"),
Value::Boolean(_v) => format!("<lgl>"),
Value::Datetime(_v) => format!("<dttm>"),
_ => format!("None")})
.collect()))
.collect();
let all_keys = value_types.keys().cloned().collect::<Vec<String>>();
let first_values = value_types.values().filter_map(|vec| vec.first()).collect::<Vec<&String>>(); //first() give and Option<&Item>
let max_value: Option<usize> = all_keys.iter().map(|x| x.len()).max();
let names_with_white_space: Vec<_> = all_keys
.iter()
.map(|x| x.pad_to_width_with_alignment(max_value.unwrap(), Alignment::Right))
.collect();
let types_with_white_space: Vec<_> = first_values
.iter()
.map(|x| x.pad_to_width_with_alignment(max_value.unwrap(), Alignment::Right))
.collect();
let title = names_with_white_space.join(" ");
let types = types_with_white_space.join(" ");
let left_margin = "\t";
let title_formated:String = format!("{}{}",left_margin ,title);
let types_formated:String = format!("{}{}",left_margin ,types);
println!("{}",style(title_formated.clone()).bold());
println!("{}",style(types_formated.clone()).bright().black());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment