use std::collections::HashMap;
pub fn cookie_to_json(cookie: &str) -> HashMap<String, String> {
let mut map = HashMap::new();
if cookie.is_empty() {
return map;
}
for item in cookie.split(';') {
let parts: Vec<&str> = item.splitn(2, '=').collect();
if parts.len() == 2 {
map.insert(parts[0].trim().to_string(), parts[1].trim().to_string());
}
}
map
}
pub fn cookie_obj_to_string(cookie: &HashMap<String, String>) -> String {
cookie
.iter()
.map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
.collect::<Vec<_>>()
.join("; ")
}
pub fn get_cookie_value(cookie: &HashMap<String, String>, key: &str) -> Option<String> {
cookie.get(key).cloned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cookie_to_json() {
let cookie = "name=value; foo=bar; empty=";
let map = cookie_to_json(cookie);
assert_eq!(map.get("name").unwrap(), "value");
assert_eq!(map.get("foo").unwrap(), "bar");
assert_eq!(map.get("empty").unwrap(), "");
}
#[test]
fn test_cookie_to_json_empty() {
let map = cookie_to_json("");
assert!(map.is_empty());
}
#[test]
fn test_cookie_obj_to_string() {
let mut map = HashMap::new();
map.insert("name".to_string(), "value".to_string());
let s = cookie_obj_to_string(&map);
assert!(s.contains("name=value"));
}
}