-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathheaders.rs
More file actions
51 lines (47 loc) · 1.64 KB
/
headers.rs
File metadata and controls
51 lines (47 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use pyo3::{
Bound, Python,
types::{PyAnyMethods, PyDict},
};
use crate::exceptions::rust_err::NatsrpyResult;
pub trait NatsrpyHeadermapExt: Sized {
fn from_pydict(pydict: Bound<PyDict>) -> NatsrpyResult<Self>;
fn to_pydict<'py>(&self, py: Python<'py>) -> NatsrpyResult<Bound<'py, PyDict>>;
}
impl NatsrpyHeadermapExt for async_nats::HeaderMap {
fn from_pydict(pydict: Bound<PyDict>) -> NatsrpyResult<Self> {
let mut headermap = Self::new();
for (name, val) in pydict {
let rs_name = name.extract::<&str>()?;
if let Ok(parsed_str) = val.extract::<&str>() {
headermap.insert(rs_name, parsed_str);
continue;
}
if let Ok(parsed_list) = val.extract::<Vec<String>>() {
for inner in parsed_list {
headermap.append(rs_name, inner);
}
continue;
}
headermap.insert(rs_name, val.to_string());
}
Ok(headermap)
}
fn to_pydict<'py>(&self, py: Python<'py>) -> NatsrpyResult<Bound<'py, PyDict>> {
let dict = PyDict::new(py);
for (header_name, header_val) in self.iter() {
let py_val = header_val
.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<_>>();
if py_val.is_empty() {
continue;
}
if py_val.len() == 1 {
dict.set_item(header_name.to_string(), py_val.first())?;
continue;
}
dict.set_item(header_name.to_string(), py_val)?;
}
Ok(dict)
}
}