1use fixed::Fixed;
2use fnv::FnvHashMap;
3use std::{slice, str};
4
5#[repr(C)]
7pub struct Context {
8 class: Fixed<ContextClass>,
9 config: FnvHashMap<String, String>,
10}
11
12impl Context {
13 pub fn new(config: FnvHashMap<String, String>) -> Context {
15 Self {
16 class: CONTEXT_CLASS.clone(),
17 config,
18 }
19 }
20
21 pub fn get_config(&self, key: &str) -> &str {
23 let mut len = key.len() as u64;
24 let data = (self.class.get_config)(self, key.as_ptr(), &mut len);
25 unsafe { str::from_utf8_unchecked(slice::from_raw_parts(data, len as usize)) }
26 }
27}
28
29#[repr(C)]
30pub struct ContextClass {
31 get_config: extern "C" fn(*const Context, *const u8, *mut u64) -> *const u8,
32}
33
34impl ContextClass {
35 fn new() -> ContextClass {
36 Self {
37 get_config: abi_get_config,
38 }
39 }
40}
41
42extern "C" fn abi_get_config(ctx: *const Context, data: *const u8, len: *mut u64) -> *const u8 {
43 unsafe {
44 let key = str::from_utf8_unchecked(slice::from_raw_parts(data, *len as usize));
45 let val = (*ctx).config.get(key).map(|s| s.as_str()).unwrap_or("");
46 *len = val.len() as u64;
47 val.as_ptr()
48 }
49}
50
51lazy_static! {
52 static ref CONTEXT_CLASS: Fixed<ContextClass> = Fixed::new(ContextClass::new());
53}