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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use ffi;
use object::PyObject;
use python::{Python, ToPyPointer};
use conversion::{ToPyObject, IntoPyObject, ToBorrowedObject, PyTryFrom};
pub struct PyBool(PyObject);
pyobject_convert!(PyBool);
pyobject_nativetype!(PyBool, PyBool_Type, PyBool_Check);
impl PyBool {
#[inline]
pub fn new(py: Python, val: bool) -> &PyBool {
unsafe {
py.from_borrowed_ptr(if val { ffi::Py_True() } else { ffi::Py_False() })
}
}
#[inline]
pub fn is_true(&self) -> bool {
self.as_ptr() == unsafe { ::ffi::Py_True() }
}
}
impl ToPyObject for bool {
#[inline]
fn to_object(&self, py: Python) -> PyObject {
unsafe {
PyObject::from_borrowed_ptr(
py, if *self { ffi::Py_True() } else { ffi::Py_False() })
}
}
}
impl ToBorrowedObject for bool {
#[inline]
fn with_borrowed_ptr<F, R>(&self, _py: Python, f: F) -> R
where F: FnOnce(*mut ffi::PyObject) -> R
{
f(unsafe { if *self { ffi::Py_True() } else { ffi::Py_False() } })
}
}
impl IntoPyObject for bool {
#[inline]
fn into_object(self, py: Python) -> PyObject {
PyBool::new(py, self).into()
}
}
pyobject_extract!(obj to bool => {
Ok(<PyBool as PyTryFrom>::try_from(obj)?.is_true())
});
#[cfg(test)]
mod test {
use python::Python;
use objects::{PyBool, PyObjectRef};
use conversion::ToPyObject;
use objectprotocol::ObjectProtocol;
#[test]
fn test_true() {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(PyBool::new(py, true).is_true());
let t: &PyObjectRef = PyBool::new(py, true).into();
assert_eq!(true, t.extract().unwrap());
assert!(true.to_object(py) == PyBool::new(py, true).into());
}
#[test]
fn test_false() {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(!PyBool::new(py, false).is_true());
let t: &PyObjectRef = PyBool::new(py, false).into();
assert_eq!(false, t.extract().unwrap());
assert!(false.to_object(py) == PyBool::new(py, false).into());
}
}