Skip to content

Commit

Permalink
Add to_hashmap().
Browse files Browse the repository at this point in the history
  • Loading branch information
vikpe committed May 2, 2024
1 parent 6c2aaa5 commit 1c45e1d
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "quake_infostring"
description = "Parse QuakeWorld info strings."
categories = ["parsing"]
keywords = ["quake", "quakeworld"]
repository = "https://github.com/vikpe/quake_infostring"
authors = ["Viktor Persson <viktor.persson@arcsin.se>"]
version = "0.1.0"
edition = "2021"
license = "MIT"
include = [
"/Cargo.toml",
"/README.md",
"/benches/**",
"/src/**",
]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dev-dependencies]
pretty_assertions = "1.4.0"
49 changes: 49 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use std::collections::HashMap;

mod util;

pub const DELIMITER: char = '\\';

pub fn to_hashmap(serverinfo: &str) -> HashMap<String, String> {
let serverinfo_ = util::clean(serverinfo);
let mut iter = serverinfo_
.trim_matches(DELIMITER)
.split(DELIMITER)
.map(|v| v.to_string());
let mut result = HashMap::new();

while let Some(key) = iter.next() {
if let Some(value) = iter.next() {
result.insert(key, value);
}
}

result
}

#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;

use super::*;

#[test]
fn test_to_hashmap() {
// unbalanced string
{
let result = to_hashmap(r#"\maxfps\77"#);
assert_eq!(result.get("maxfps"), Some(&"77".to_string()));
assert_eq!(result.get("matchtag"), None);
}

// valid string
{
let result = to_hashmap(r#"\maxfps\77\matchtag\kombat\epoch\123456"#);
assert_eq!(result.get("maxfps"), Some(&"77".to_string()));
assert_eq!(result.get("matchtag"), Some(&"kombat".to_string()));
assert_eq!(result.get("epoch"), Some(&"123456".to_string()));

assert_eq!(result.get("MISSING_KEY"), None);
}
}
}
27 changes: 27 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use crate::DELIMITER;

pub fn clean(serverinfo: &str) -> String {
serverinfo
.trim()
.trim_end_matches(r#"\n"#)
.replace(r#"\\"#, &DELIMITER.to_string())
.replace('"', "")
.trim_end_matches(DELIMITER)
.to_string()
}


#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;

use super::*;

#[test]
fn test_clean() {
assert_eq!(clean(r#"\\maxfps\\77"#), r#"\maxfps\77"#); // double slashes
assert_eq!(clean(r#"\maxfps\77\"#), r#"\maxfps\77"#); // trailing slash
assert_eq!(clean(r#" \needpass\1\\\n "#), r#"\needpass\1"#); // whitespace
assert_eq!(clean(r#"\max"fps\77""#), r#"\maxfps\77"#); // quotes
}
}

0 comments on commit 1c45e1d

Please sign in to comment.