Skip to content

Commit de94a5a

Browse files
Make PyBytesWriter -> PyBytes conversion infallible
1 parent 993eda8 commit de94a5a

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

src/byteswriter.rs

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use crate::{
1313
py_result_ext::PyResultExt,
1414
};
1515
use crate::{Bound, IntoPyObject, PyErr, PyResult, Python};
16+
use std::convert::Infallible;
1617
use std::io::IoSlice;
1718
#[cfg(not(Py_LIMITED_API))]
1819
use std::{
@@ -85,24 +86,20 @@ impl<'py> PyBytesWriter<'py> {
8586
}
8687
}
8788

88-
#[cfg(not(Py_LIMITED_API))]
89-
impl<'py> TryFrom<PyBytesWriter<'py>> for Bound<'py, PyBytes> {
90-
type Error = PyErr;
91-
89+
impl<'py> From<PyBytesWriter<'py>> for Bound<'py, PyBytes> {
9290
#[inline]
93-
fn try_from(value: PyBytesWriter<'py>) -> Result<Self, Self::Error> {
91+
#[cfg(not(Py_LIMITED_API))]
92+
fn from(value: PyBytesWriter<'py>) -> Self {
9493
let py = value.python;
9594
unsafe {
9695
PyBytesWriter_Finish(ManuallyDrop::new(value).writer.as_ptr())
97-
.assume_owned_or_err(py)
96+
.assume_owned(py)
9897
.cast_into_unchecked()
9998
}
10099
}
101-
}
102100

103-
#[cfg(Py_LIMITED_API)]
104-
impl<'py> From<PyBytesWriter<'py>> for Bound<'py, PyBytes> {
105101
#[inline]
102+
#[cfg(Py_LIMITED_API)]
106103
fn from(writer: PyBytesWriter<'py>) -> Self {
107104
PyBytes::new(writer.python, &writer.buffer)
108105
}
@@ -111,11 +108,11 @@ impl<'py> From<PyBytesWriter<'py>> for Bound<'py, PyBytes> {
111108
impl<'py> IntoPyObject<'py> for PyBytesWriter<'py> {
112109
type Target = PyBytes;
113110
type Output = Bound<'py, PyBytes>;
114-
type Error = PyErr;
111+
type Error = Infallible;
115112

116113
#[inline]
117114
fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> {
118-
self.try_into().map_err(Into::into)
115+
Ok(self.into())
119116
}
120117
}
121118

@@ -211,8 +208,8 @@ mod tests {
211208
Python::attach(|py| {
212209
let buf = [1, 2, 3, 4];
213210
let mut writer = PyBytesWriter::new(py).unwrap();
214-
writer.write(&buf).unwrap();
215-
let bytes: Bound<'_, PyBytes> = writer.try_into().unwrap();
211+
assert_eq!(writer.write(&buf).unwrap(), 4);
212+
let bytes: Bound<'_, PyBytes> = writer.into();
216213
assert_eq!(bytes, buf);
217214
})
218215
}
@@ -222,8 +219,8 @@ mod tests {
222219
Python::attach(|py| {
223220
let bufs = [IoSlice::new(&[1, 2]), IoSlice::new(&[3, 4])];
224221
let mut writer = PyBytesWriter::new(py).unwrap();
225-
writer.write_vectored(&bufs).unwrap();
226-
let bytes: Bound<'_, PyBytes> = writer.try_into().unwrap();
222+
assert_eq!(writer.write_vectored(&bufs).unwrap(), 4);
223+
let bytes: Bound<'_, PyBytes> = writer.into();
227224
assert_eq!(bytes, [1, 2, 3, 4]);
228225
})
229226
}

0 commit comments

Comments
 (0)