1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
//! `keyvalues-parser` uses [`pest`](https://lib.rs/crates/pest) to parse //! [VDF text v1 and v2](https://developer.valvesoftware.com/wiki/KeyValues) //! files to an untyped Rust structure to ease manipulation and navigation. The //! parser provides an untyped `Vdf` representation as well as a linear //! `TokenStream` //! //! The library is primarily used in conjunction with //! [`keyvalues-serde`](https://github.com/LovecraftianHorror/vdf-rs/tree/main/keyvalues-serde) //! which provides a more ergonommic (yet more limiting) means of dealing with VDF //! text //! //! # Installation //! //! **Note: this requires at least Rust `1.42.0`** //! //! Just add the library to your `Cargo.toml` //! //! ```toml //! [dependencies] //! keyvalues-parser = "0.1.0" //! ``` //! //! # Usage //! //! There is documentation available //! [here](https://docs.rs/keyvalues-parser/0.1.0/keyvalues_parser/) and there are //! examples available in the //! [examples directory](https://github.com/LovecraftianHorror/vdf-rs/tree/main/keyvalues-parser/examples) //! //! ## Quickstart //! //! `loginusers.vdf` //! //! ```text //! "users" //! { //! "12345678901234567" //! { //! "AccountName" "ACCOUNT_NAME" //! "PersonaName" "PERSONA_NAME" //! "RememberPassword" "1" //! "MostRecent" "1" //! "Timestamp" "1234567890" //! } //! } //! ``` //! //! `main.rs` //! //! ```no_run //! use keyvalues_parser::Vdf; //! //! let vdf_text = std::fs::read_to_string("loginusers.vdf")?; //! let vdf = Vdf::parse(&vdf_text)?; //! assert_eq!( //! "12345678901234567", //! vdf.value.unwrap_obj().keys().next().unwrap() //! ); //! # Ok::<(), Box<dyn std::error::Error>>(()) //! ``` //! //! # Limitations //! //! VDF text is drastically underspecified. This leads to the following liberties //! being taken //! //! - Not respecting the ordering of key-value pairs, where the pairs are stored in a `BTreeMap` that sorts the values based on the key //! - Because of limitations in representing sequences, an empty `Vec` of values will be rendered as a missing keyvalue pair //! //! # Benchmarks //! //! A set of basic benchmarks can be found in the //! [benches directory](https://github.com/LovecraftianHorror/vdf-rs/tree/main/keyvalues-parser/benches) //! //! These just test timing and throughput for both parsing and rendering of a //! fairly typical VDF file use std::{borrow::Cow, collections::BTreeMap}; pub mod error; mod text; #[cfg(feature = "unstable")] pub mod tokens; /// A Key is simply an alias for `Cow<str>` pub type Key<'a> = Cow<'a, str>; /// An `Obj` is represented as a `BTreeMap` which maps keys to their corresponding values /// /// The values in this case is a `Vec` since a single key can map to multiple values to form a /// sequence. This is represented as the same key being used within an object to map to different /// values. pub type Obj<'a> = BTreeMap<Key<'a>, Vec<Value<'a>>>; /// A loosely typed representation of VDF text /// /// `Vdf` is represented as a single [`Key`][Key] mapped to a single [`Value`][Value] /// /// ## Parse /// /// `Vdf`s will generally be created through the use of [`Vdf::parse()`][Vdf::parse] which takes a /// string representing VDF text and attempts to parse it to a `Vdf` representation. /// /// ## Mutate /// /// From there you can manipulate/extract from the representation as desired by using the standard /// conventions on the internal types (plain old `BTreeMap`s, `Vec`s, and `Cow`s all the way down) /// /// ## Render /// /// The `Vdf` can also be rendered back to its text form through its `Display` implementation /// /// ## Example /// /// ``` /// use keyvalues_parser::Vdf; /// /// // Parse /// let vdf_text = r#" /// "Outer Key" /// { /// "Inner Key" "Inner Value" /// "Inner Key" /// { /// } /// } /// "#; /// let mut parsed = Vdf::parse(vdf_text)?; /// /// // Mutate: i.e. remove the last "Inner Key" pair /// parsed /// .value /// .get_mut_obj() /// .unwrap() /// .get_mut("Inner Key") /// .unwrap() /// .pop(); /// /// // Render: prints /// // "Outer Key" /// // { /// // "Inner Key" "Inner Value" /// // } /// println!("{}", parsed); /// # Ok::<(), keyvalues_parser::error::Error>(()) /// ``` #[cfg_attr(test, derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Vdf<'a> { pub key: Key<'a>, pub value: Value<'a>, } impl<'a> Vdf<'a> { /// Creates a [`Vdf`][Vdf] using a provided key and value /// /// ``` /// use keyvalues_parser::{Vdf, Value}; /// use std::borrow::Cow; /// /// let vdf = Vdf::new(Cow::from("Much Key"), Value::Str(Cow::from("Such Wow"))); /// // prints /// // "Much Key" "Such Wow" /// println!("{}", vdf); /// ``` pub fn new(key: Key<'a>, value: Value<'a>) -> Self { Self { key, value } } } /// Enum representing all valid VDF values /// /// VDF is composed of [`Key`s][Key] and their respective [`Value`s][Value] where this represents /// the latter. A value is either going to be a `Str(Cow<str>)`, or an `Obj(Obj)` that contains a /// list of keys and values. #[cfg_attr(test, derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Value<'a> { Str(Cow<'a, str>), Obj(Obj<'a>), } impl<'a> Value<'a> { /// Returns if the current value is the `Str` variant pub fn is_str(&self) -> bool { self.get_str().is_some() } /// Returns if the current value is the `Obj` variant pub fn is_obj(&self) -> bool { self.get_obj().is_some() } /// Gets the inner `&str` if this is a `Value::Str` pub fn get_str(&self) -> Option<&str> { if let Value::Str(s) = self { Some(s) } else { None } } /// Gets the inner `&Obj` if this value is a `Value::Obj` pub fn get_obj(&self) -> Option<&Obj> { if let Value::Obj(obj) = self { Some(obj) } else { None } } /// Gets the inner `&mut str` if this is a `Value::Str` pub fn get_mut_str(&mut self) -> Option<&mut Cow<'a, str>> { if let Value::Str(s) = self { Some(s) } else { None } } /// Gets the inner `&mut Obj` if this is a `Value::Obj` pub fn get_mut_obj(&mut self) -> Option<&mut Obj<'a>> { if let Value::Obj(obj) = self { Some(obj) } else { None } } /// Unwraps the `Cow<str>` from the `Value::Str` /// /// # Panics /// /// If the variant was `Value::Obj` /// /// # Examples /// /// ``` /// use keyvalues_parser::Value; /// use std::borrow::Cow; /// /// let value = Value::Str(Cow::from("Sample text")); /// assert_eq!(value.unwrap_str(), "Sample text"); /// ``` /// /// ```should_panic /// use keyvalues_parser::Value; /// use std::collections::BTreeMap; /// /// let value = Value::Obj(BTreeMap::new()); /// value.unwrap_str(); // <-- panics /// ``` pub fn unwrap_str(self) -> Cow<'a, str> { self.expect_str("Called `unwrap_str` on a `Value::Obj` variant") } /// Unwraps the [`Obj`][Obj] from the `Value::Obj` /// /// # Panics /// /// If the variant was `Value::Str` /// /// # Examples /// /// ``` /// use keyvalues_parser::Value; /// use std::collections::BTreeMap; /// /// let empty_map = BTreeMap::new(); /// let value = Value::Obj(empty_map.clone()); /// assert_eq!(value.unwrap_obj(), empty_map); /// ``` /// /// ```should_panic /// use keyvalues_parser::Value; /// use std::borrow::Cow; /// /// let value = Value::Str(Cow::from("D'Oh")); /// value.unwrap_obj(); // <-- panics /// ``` pub fn unwrap_obj(self) -> Obj<'a> { self.expect_obj("Called `unwrap_obj` on a `Value::Str` variant") } /// Refer to [Value::unwrap_str]. Same situation, but with a custom message pub fn expect_str(self, msg: &str) -> Cow<'a, str> { if let Value::Str(s) = self { s } else { panic!("{}", msg) } } /// Refer to [Value::unwrap_obj]. Same situation, but with a custom message pub fn expect_obj(self, msg: &str) -> Obj<'a> { if let Value::Obj(obj) = self { obj } else { panic!("{}", msg) } } }