Kv Parser — parses whitespace-separated key-value lines from strings or files into a hash map
A Rust library for parsing simple key-value text into HashMap<Box<str>, Box<str>>.
Format
Each non-empty line contains a key-value pair separated by whitespace:
- Keys and values are separated by the first whitespace character on each line
- Keys cannot contain whitespace
- Values can contain any characters including whitespace (leading/trailing whitespace is trimmed)
- Empty lines and lines without whitespace are ignored
- Keys must be unique (duplicate keys result in an error)
Usage
Add to your Cargo.toml:
[]
= "0.3.0"
text_to_key_value_map parses a string, file_to_key_value_map reads a file and parses its contents:
use Path;
use ;
Error Handling
Both functions return Result<HashMap<Box<str>, Box<str>>, Error> where Error can be:
Error::OpeningFile- Failed to open the fileError::ReadingFile- I/O error while reading the fileError::MultipleKeys(key)- Duplicate key found
text_to_key_value_map takes a string that is already in memory, so it only ever returns Error::MultipleKeys.
Example
Given a file savedata.sav:
current-level vulcano
start-point 3
player-upgrades super-jump climbing lava-suit bombs
The parsed result:
use ;
use file_to_key_value_map;
let mut expected = new;
expected.insert;
expected.insert;
expected.insert;
let result = file_to_key_value_map?;
assert_eq!;
Performance
- Uses
Box<str>instead ofStringfor reduced memory overhead - Early termination on duplicate keys or I/O errors