From 82e2b2f5afb6d37b6d3dee34b67cc0fe192893e6 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 19 Mar 2016 22:06:44 -0700 Subject: [PATCH] Add preserve_order feature to use LinkedHashMap instead of BTreeMap --- saphyr/Cargo.toml | 4 ++++ saphyr/src/lib.rs | 3 +++ saphyr/src/yaml.rs | 15 ++++++++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/saphyr/Cargo.toml b/saphyr/Cargo.toml index 46d8c7a..c5e70fd 100644 --- a/saphyr/Cargo.toml +++ b/saphyr/Cargo.toml @@ -8,5 +8,9 @@ license = "MIT/Apache-2.0" description = "The missing YAML 1.2 parser for rust" repository = "https://github.com/chyh1990/yaml-rust" +[features] +preserve_order = ["linked-hash-map"] + [dependencies] clippy = { version = "^0.*", optional = true } +linked-hash-map = { version = "0.0.9", optional = true } diff --git a/saphyr/src/lib.rs b/saphyr/src/lib.rs index dc66adc..6bdde1f 100644 --- a/saphyr/src/lib.rs +++ b/saphyr/src/lib.rs @@ -42,6 +42,9 @@ #![cfg_attr(feature="clippy", warn(cyclomatic_complexity))] #![cfg_attr(feature="clippy", allow(match_same_arms))] +#[cfg(feature = "preserve_order")] +extern crate linked_hash_map; + pub mod yaml; pub mod scanner; pub mod parser; diff --git a/saphyr/src/yaml.rs b/saphyr/src/yaml.rs index ef98e50..d840a30 100644 --- a/saphyr/src/yaml.rs +++ b/saphyr/src/yaml.rs @@ -23,7 +23,7 @@ use scanner::{TScalarStyle, ScanError, TokenType}; /// assert!(v.as_i64().is_some()); /// } /// ``` -#[derive(Clone, PartialEq, PartialOrd, Debug, Eq, Ord)] +#[derive(Clone, PartialEq, PartialOrd, Debug, Eq, Ord, Hash)] pub enum Yaml { /// Float types are stored as String and parsed on demand. /// Note that f64 does NOT implement Eq trait and can NOT be stored in BTreeMap. @@ -37,6 +37,15 @@ pub enum Yaml { /// YAML array, can be accessed as a `Vec`. Array(self::Array), /// YAML hash, can be accessed as a `BTreeMap`. + /// + /// If the order of keys is meaningful, enable the `preserve_order` feature to + /// store hashes as a `LinkedHashMap` intead of `BTreeMap`. When using a + /// `LinkedHashMap`, the itertion order will match the order of insertion into + /// the map. + /// + /// ```toml + /// yaml-rust = { version = "*", features = ["preserve_order"] } + /// ``` Hash(self::Hash), /// Alias, not fully supported yet. Alias(usize), @@ -49,7 +58,11 @@ pub enum Yaml { } pub type Array = Vec; + +#[cfg(not(feature = "preserve_order"))] pub type Hash = BTreeMap; +#[cfg(feature = "preserve_order")] +pub type Hash = ::linked_hash_map::LinkedHashMap; pub struct YamlLoader { docs: Vec,