-
Notifications
You must be signed in to change notification settings - Fork 758
/
slice.rs
199 lines (171 loc) · 6.45 KB
/
slice.rs
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use std::borrow::Cow;
#[cfg(feature = "experimental-inspect")]
use crate::inspect::types::TypeInfo;
use crate::{
conversion::IntoPyObject,
types::{PyByteArray, PyByteArrayMethods, PyBytes},
Bound, Py, PyAny, PyErr, PyObject, PyResult, Python,
};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
#[allow(deprecated)]
impl IntoPy<PyObject> for &[u8] {
fn into_py(self, py: Python<'_>) -> PyObject {
PyBytes::new(py, self).unbind().into()
}
}
impl<'a, 'py, T> IntoPyObject<'py> for &'a [T]
where
&'a T: IntoPyObject<'py>,
T: 'a, // MSRV
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns [`&[u8]`](std::slice) into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
<&T>::borrowed_sequence_into_pyobject(self, py, crate::conversion::private::Token)
}
#[cfg(feature = "experimental-inspect")]
fn type_output() -> TypeInfo {
TypeInfo::union_of(&[
TypeInfo::builtin("bytes"),
TypeInfo::list_of(<&T>::type_output()),
])
}
}
impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for &'a [u8] {
fn from_py_object_bound(obj: crate::Borrowed<'a, '_, PyAny>) -> PyResult<Self> {
Ok(obj.downcast::<PyBytes>()?.as_bytes())
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
TypeInfo::builtin("bytes")
}
}
/// Special-purpose trait impl to efficiently handle both `bytes` and `bytearray`
///
/// If the source object is a `bytes` object, the `Cow` will be borrowed and
/// pointing into the source object, and no copying or heap allocations will happen.
/// If it is a `bytearray`, its contents will be copied to an owned `Cow`.
impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for Cow<'a, [u8]> {
fn from_py_object_bound(ob: crate::Borrowed<'a, '_, PyAny>) -> PyResult<Self> {
if let Ok(bytes) = ob.downcast::<PyBytes>() {
return Ok(Cow::Borrowed(bytes.as_bytes()));
}
let byte_array = ob.downcast::<PyByteArray>()?;
Ok(Cow::Owned(byte_array.to_vec()))
}
#[cfg(feature = "experimental-inspect")]
fn type_input() -> TypeInfo {
Self::type_output()
}
}
#[allow(deprecated)]
impl ToPyObject for Cow<'_, [u8]> {
fn to_object(&self, py: Python<'_>) -> Py<PyAny> {
PyBytes::new(py, self.as_ref()).into()
}
}
#[allow(deprecated)]
impl IntoPy<Py<PyAny>> for Cow<'_, [u8]> {
fn into_py(self, py: Python<'_>) -> Py<PyAny> {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py, T> IntoPyObject<'py> for Cow<'_, [T]>
where
T: Clone,
for<'a> &'a T: IntoPyObject<'py>,
{
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
/// Turns `Cow<[u8]>` into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
///
/// [`PyBytes`]: crate::types::PyBytes
/// [`PyList`]: crate::types::PyList
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
<&T>::borrowed_sequence_into_pyobject(self.as_ref(), py, crate::conversion::private::Token)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use crate::{
conversion::IntoPyObject,
ffi,
types::{any::PyAnyMethods, PyBytes, PyBytesMethods, PyList},
Python,
};
#[test]
fn test_extract_bytes() {
Python::with_gil(|py| {
let py_bytes = py.eval(ffi::c_str!("b'Hello Python'"), None, None).unwrap();
let bytes: &[u8] = py_bytes.extract().unwrap();
assert_eq!(bytes, b"Hello Python");
});
}
#[test]
fn test_cow_impl() {
Python::with_gil(|py| {
let bytes = py.eval(ffi::c_str!(r#"b"foobar""#), None, None).unwrap();
let cow = bytes.extract::<Cow<'_, [u8]>>().unwrap();
assert_eq!(cow, Cow::<[u8]>::Borrowed(b"foobar"));
let byte_array = py
.eval(ffi::c_str!(r#"bytearray(b"foobar")"#), None, None)
.unwrap();
let cow = byte_array.extract::<Cow<'_, [u8]>>().unwrap();
assert_eq!(cow, Cow::<[u8]>::Owned(b"foobar".to_vec()));
let something_else_entirely = py.eval(ffi::c_str!("42"), None, None).unwrap();
something_else_entirely
.extract::<Cow<'_, [u8]>>()
.unwrap_err();
let cow = Cow::<[u8]>::Borrowed(b"foobar").into_pyobject(py).unwrap();
assert!(cow.is_instance_of::<PyBytes>());
let cow = Cow::<[u8]>::Owned(b"foobar".to_vec())
.into_pyobject(py)
.unwrap();
assert!(cow.is_instance_of::<PyBytes>());
});
}
#[test]
fn test_slice_intopyobject_impl() {
Python::with_gil(|py| {
let bytes: &[u8] = b"foobar";
let obj = bytes.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), bytes);
let nums: &[u16] = &[0, 1, 2, 3];
let obj = nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
#[test]
fn test_cow_intopyobject_impl() {
Python::with_gil(|py| {
let borrowed_bytes = Cow::<[u8]>::Borrowed(b"foobar");
let obj = borrowed_bytes.clone().into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &*borrowed_bytes);
let owned_bytes = Cow::<[u8]>::Owned(b"foobar".to_vec());
let obj = owned_bytes.clone().into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyBytes>());
let obj = obj.downcast_into::<PyBytes>().unwrap();
assert_eq!(obj.as_bytes(), &*owned_bytes);
let borrowed_nums = Cow::<[u16]>::Borrowed(&[0, 1, 2, 3]);
let obj = borrowed_nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
let owned_nums = Cow::<[u16]>::Owned(vec![0, 1, 2, 3]);
let obj = owned_nums.into_pyobject(py).unwrap();
assert!(obj.is_instance_of::<PyList>());
});
}
}