use std::collections::HashMap;
use std::ffi::c_void;
#[derive(Debug, Clone, PartialEq)]
pub enum OptionValue {
String(String),
U32(u32),
Map(Box<OptionMap>),
}
pub type OptionMap = HashMap<String, OptionValue>;
pub struct OptionView<'a> {
inner: &'a OptionMap,
}
impl<'a> OptionView<'a> {
pub fn new(inner: &'a OptionMap) -> Self {
Self { inner }
}
pub unsafe fn from_raw_ptr(ptr: *const c_void) -> Option<Self> {
if ptr.is_null() {
return None;
}
let inner: &'a OptionMap = unsafe { &*(ptr as *const OptionMap) };
Some(Self { inner })
}
pub fn get_str(&self, key: &str) -> Option<&str> {
match self.inner.get(key)? {
OptionValue::String(s) => Some(s.as_str()),
_ => None,
}
}
pub fn get_u32(&self, key: &str) -> Option<u32> {
match self.inner.get(key)? {
OptionValue::U32(n) => Some(*n),
_ => None,
}
}
pub fn get_map(&self, key: &str) -> Option<OptionView<'_>> {
match self.inner.get(key)? {
OptionValue::Map(m) => Some(OptionView::new(m.as_ref())),
_ => None,
}
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> OptionMap {
let mut m = OptionMap::new();
m.insert(
"algorithm".to_string(),
OptionValue::String("sha-256".to_string()),
);
m.insert("output_size".to_string(), OptionValue::U32(32));
let mut nested = OptionMap::new();
nested.insert(
"encoding".to_string(),
OptionValue::String("pem".to_string()),
);
m.insert("keyfmt".to_string(), OptionValue::Map(Box::new(nested)));
m
}
#[test]
fn reads_string_value() {
let m = sample();
let view = OptionView::new(&m);
assert_eq!(view.get_str("algorithm"), Some("sha-256"));
}
#[test]
fn reads_u32_value() {
let m = sample();
let view = OptionView::new(&m);
assert_eq!(view.get_u32("output_size"), Some(32));
}
#[test]
fn reads_nested_map() {
let m = sample();
let view = OptionView::new(&m);
let nested = view.get_map("keyfmt").expect("nested map present");
assert_eq!(nested.get_str("encoding"), Some("pem"));
}
#[test]
fn missing_key_returns_none() {
let m = sample();
let view = OptionView::new(&m);
assert_eq!(view.get_str("missing"), None);
assert_eq!(view.get_u32("missing"), None);
assert!(view.get_map("missing").is_none());
}
#[test]
fn wrong_type_returns_none() {
let m = sample();
let view = OptionView::new(&m);
assert_eq!(view.get_u32("algorithm"), None);
assert!(view.get_map("algorithm").is_none());
}
#[test]
fn null_pointer_yields_none() {
let view = unsafe { OptionView::from_raw_ptr(std::ptr::null()) };
assert!(view.is_none());
}
}