Implement ToPyObject for HashMap->dict conversion.

This commit is contained in:
Dmitry Trofimov 2015-07-17 22:07:37 +02:00
parent f6718a271b
commit 144d14f8c4
1 changed files with 20 additions and 0 deletions

View File

@ -21,6 +21,9 @@ use python::{Python, ToPythonPointer, PythonObject};
use conversion::ToPyObject;
use objects::{PyObject, PyList};
use err::{self, PyResult, PyErr};
use std::collections::HashMap;
use std::hash::Hash;
use std::cmp::Eq;
/// Represents a Python `dict`.
pub struct PyDict<'p>(PyObject<'p>);
@ -112,3 +115,20 @@ impl <'p> PyDict<'p> {
}
}
}
// TODO: use macros to make implementations for different maps
impl <'p, K, V> ToPyObject<'p> for HashMap<K, V> where K: Hash+Eq+ToPyObject<'p>, V: ToPyObject<'p> {
type ObjectType = PyDict<'p>;
fn to_py_object(&self, py: Python<'p>) -> PyDict<'p> {
let ptr = unsafe { ffi::PyDict_New() };
let t = unsafe { err::cast_from_owned_ptr_or_panic(py, ptr) };
for (key, value) in self.iter() {
key.with_borrowed_ptr(py, move |key|
value.with_borrowed_ptr(py, |value| unsafe {
ffi::PyDict_SetItem(ptr, key, value);
}))
};
t
}
}