Skip to content

Commit d7afc47

Browse files
committed
BorrowedBuffer::as_slice()
1 parent 0109a11 commit d7afc47

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

Modules/_base64/src/lib.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,15 @@ impl BorrowedBuffer {
158158
fn as_ptr(&self) -> *const u8 {
159159
self.view.buf.cast::<u8>() as *const u8
160160
}
161+
162+
fn as_slice(&self, msg: &CStr) -> PyResult<&[u8]> {
163+
let len = self.len();
164+
if len < 0 {
165+
return Err(MakeErr::type_error(msg).into());
166+
}
167+
let slice = unsafe { slice::from_raw_parts(self.as_ptr(), len as usize) };
168+
Ok(slice)
169+
}
161170
}
162171

163172
impl Drop for BorrowedBuffer {
@@ -194,17 +203,9 @@ pub unsafe extern "C" fn standard_b64encode(
194203
fn standard_b64encode_impl(source: &PyObject) -> PyResult<*mut PyObject> {
195204
let buffer = BorrowedBuffer::from_object(source)?;
196205

197-
let view_len = buffer.len();
198-
if view_len < 0 {
199-
return Err(
200-
MakeErr::type_error(c"standard_b64encode() argument has negative length").into(),
201-
);
202-
}
203-
204-
let input_len = view_len as usize;
205-
let input = unsafe { slice::from_raw_parts(buffer.as_ptr(), input_len) };
206+
let input = buffer.as_slice(c"standard_b64encode() argument has negative length")?;
206207

207-
let Some(output_len) = encoded_output_len(input_len) else {
208+
let Some(output_len) = encoded_output_len(input.len()) else {
208209
return Err(MakeErr::NoMemory.into());
209210
};
210211

0 commit comments

Comments
 (0)