Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 42 additions & 57 deletions crates/stdlib/src/elementtree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub(crate) mod _elementtree {
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine, atomic_func,
builtins::{PyAnyDict, PyDict, PyDictRef, PyList, PyModule, PyStr, PyType, PyTypeRef},
function::{FuncArgs, PySetterValue},
function::{ArgBytesOrStr, FuncArgs, PySetterValue},
protocol::{PyMappingMethods, PyNumberMethods, PySequenceMethods},
sliceable::{NameElement, SequenceIndex, SliceableSequenceOp},
types::{
Expand Down Expand Up @@ -807,10 +807,9 @@ pub(crate) mod _elementtree {
#[pymethod]
fn iter(zelf: PyRef<Self>, args: IterArgs, vm: &VirtualMachine) -> PyElementIter {
let tag = args.tag.unwrap_or_else(|| vm.ctx.none());
let tag = match tag.downcast_ref::<PyStr>() {
Some(s) if s.as_wtf8() == "*" => vm.ctx.none(),
_ => tag,
};
let wildcard =
ArgBytesOrStr::with_object_ref(&tag, |bytes| bytes == b"*").unwrap_or(false);
let tag = if wildcard { vm.ctx.none() } else { tag };
PyElementIter::new(zelf, tag, false)
}

Expand Down Expand Up @@ -1172,30 +1171,26 @@ pub(crate) mod _elementtree {
/// plain tag, in which case `find`/`findall` must go through
/// `ElementPath`?
fn check_path(tag: &PyObject) -> bool {
let bytes = if let Some(s) = tag.downcast_ref::<PyStr>() {
s.as_bytes()
} else if let Some(b) = tag.downcast_ref::<crate::vm::builtins::PyBytes>() {
b.as_bytes()
} else {
// Unknown type; might be a path expression.
return true;
};
if bytes.len() >= 3
&& bytes[0] == b'{'
&& (bytes[1] == b'}' || (bytes[1] == b'*' && bytes[2] == b'}'))
{
return true;
}
let mut check = true;
for &ch in bytes {
match ch {
b'{' => check = false,
b'}' => check = true,
b'/' | b'*' | b'[' | b'@' | b'.' if check => return true,
_ => {}
ArgBytesOrStr::with_object_ref(tag, |bytes| {
if bytes.len() >= 3
&& bytes[0] == b'{'
&& (bytes[1] == b'}' || (bytes[1] == b'*' && bytes[2] == b'}'))
{
return true;
}
}
false
let mut check = true;
for &ch in bytes {
match ch {
b'{' => check = false,
b'}' => check = true,
b'/' | b'*' | b'[' | b'@' | b'.' if check => return true,
_ => {}
}
}
false
})
// Unknown type; might be a path expression.
.unwrap_or(true)
}

impl AsMapping for PyElement {
Expand Down Expand Up @@ -1772,28 +1767,25 @@ pub(crate) mod _elementtree {
.try_to_value(vm)
.map_err(|_| vm.new_type_error("events must be a sequence"))?;
for event in events {
let name = if let Some(s) = event.downcast_ref::<PyStr>() {
s.as_bytes().to_vec()
} else if let Some(b) = event.downcast_ref::<crate::vm::builtins::PyBytes>() {
b.as_bytes().to_vec()
} else {
let mut st = self.state.write();
let slot = ArgBytesOrStr::with_object_ref(&event, |name| match name {
b"start" => Some(&mut st.start_event),
b"end" => Some(&mut st.end_event),
b"start-ns" => Some(&mut st.start_ns_event),
b"end-ns" => Some(&mut st.end_ns_event),
b"comment" => Some(&mut st.comment_event),
b"pi" => Some(&mut st.pi_event),
_ => None,
});
let Some(slot) = slot else {
drop(st);
return Err(vm.new_value_error("invalid events sequence"));
};
let mut st = self.state.write();
match name.as_slice() {
b"start" => st.start_event = Some(event),
b"end" => st.end_event = Some(event),
b"start-ns" => st.start_ns_event = Some(event),
b"end-ns" => st.end_ns_event = Some(event),
b"comment" => st.comment_event = Some(event),
b"pi" => st.pi_event = Some(event),
_ => {
drop(st);
return Err(
vm.new_value_error(format!("unknown event {}", event.repr(vm)?))
);
}
}
let Some(slot) = slot else {
drop(st);
return Err(vm.new_value_error(format!("unknown event {}", event.repr(vm)?)));
};
*slot = Some(event);
}
Ok(())
}
Expand Down Expand Up @@ -2231,15 +2223,8 @@ pub(crate) mod _elementtree {
let read = file.get_attr("read", vm)?;
loop {
let buffer = read.call((64 * 1024,), vm)?;
if let Some(s) = buffer.downcast_ref::<PyStr>() {
if s.is_empty() {
break;
}
} else if let Some(b) = buffer.downcast_ref::<crate::vm::builtins::PyBytes>() {
if b.as_bytes().is_empty() {
break;
}
} else {
if ArgBytesOrStr::with_object_ref(&buffer, |bytes| bytes.is_empty()).unwrap_or(true)
{
break;
}
zelf.expat_parse(buffer, false, vm)?;
Expand Down
10 changes: 3 additions & 7 deletions crates/stdlib/src/pystruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub(crate) mod _struct {
buffer::{FormatSpec, new_struct_error, struct_error_type},
builtins::{PyBytes, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef},
common::{lock::PyRwLock, rc::PyRc},
function::{ArgBytesLike, ArgMemoryBuffer, FuncArgs, NameValues, PosArgs},
function::{ArgBytesLike, ArgBytesOrStr, ArgMemoryBuffer, FuncArgs, NameValues, PosArgs},
match_class,
protocol::PyIterReturn,
stdlib::_warnings,
Expand Down Expand Up @@ -309,12 +309,8 @@ pub(crate) mod _struct {
}

fn same_format(format: &PyStr, candidate: &PyObject) -> bool {
candidate
.downcast_ref::<PyStr>()
.is_some_and(|candidate| candidate.as_bytes() == format.as_bytes())
|| candidate
.downcast_ref::<PyBytes>()
.is_some_and(|candidate| candidate.as_bytes() == format.as_bytes())
ArgBytesOrStr::with_object_ref(candidate, |bytes| bytes == format.as_bytes())
.unwrap_or(false)
}
}

Expand Down
20 changes: 4 additions & 16 deletions crates/vm/src/bytes_inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
cformat::cformat_bytes,
common::wtf8::is_py_ascii_whitespace,
common::{borrow::BorrowedValue, hash},
function::{ArgIndex, ArgIterable, Either, OptionalArg, PyComparisonValue},
function::{ArgBytesOrStr, ArgIndex, ArgIterable, Either, OptionalArg, PyComparisonValue},
literal::escape::Escape,
protocol::{BufferFlags, PyBuffer},
sequence::{SequenceExt, SequenceMutExt},
Expand Down Expand Up @@ -1401,7 +1401,7 @@ pub(crate) fn bytes_decode(
#[derive(FromArgs)]
pub(crate) struct ByteInnerHexOptions {
#[pyarg(any, optional)]
pub sep: OptionalArg<Either<PyStrRef, PyBytesRef>>,
pub sep: OptionalArg<ArgBytesOrStr>,
#[pyarg(any, default = 1)]
pub bytes_per_sep: isize,
}
Expand All @@ -1417,24 +1417,12 @@ impl ByteInnerHexOptions {
return Ok((None, bytes_per_sep));
};

let s_guard;
let b_guard;
let (obj, bytes) = match &sep {
Either::A(s) => {
s_guard = s.as_wtf8();
(s.as_object(), s_guard.as_bytes())
}
Either::B(b) => {
b_guard = b.as_bytes();
(b.as_object(), b_guard)
}
};
if obj.length(vm)? != 1 {
if sep.as_object().length(vm)? != 1 {
return Err(vm.new_value_error("sep must be length 1."));
}
// An object that claims a length it does not have separates with NUL,
// which is what reading past the end of its data gives.
let sep = bytes.first().copied().unwrap_or(0);
let sep = sep.with_ref(|bytes| bytes.first().copied().unwrap_or(0));
if sep > 127 {
return Err(vm.new_value_error("sep must be ASCII."));
}
Expand Down
113 changes: 112 additions & 1 deletion crates/vm/src/function/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject,
VirtualMachine,
builtins::{PyBytes, PyStr, PyStrRef},
builtins::{PyBytes, PyBytesRef, PyStr, PyStrRef},
common::borrow::{BorrowedValue, BorrowedValueMut},
protocol::{BufferFlags, PyBuffer},
};
Expand Down Expand Up @@ -235,6 +235,56 @@ impl<'a> TryFromBorrowedObject<'a> for ArgMemoryBuffer {
}
}

/// A bytes object or text string, including subclasses, without buffer conversion.
#[derive(Debug)]
pub enum ArgBytesOrStr {
Bytes(PyBytesRef),
Str(PyStrRef),
}

impl ArgBytesOrStr {
#[must_use]
pub fn as_object(&self) -> &PyObject {
match self {
Self::Bytes(b) => b.as_object(),
Self::Str(s) => s.as_object(),
}
}

/// Borrow the payload directly, using WTF-8 for strings.
pub fn with_ref<F, R>(&self, f: F) -> R
where
F: FnOnce(&[u8]) -> R,
{
match self {
Self::Bytes(b) => f(b.as_bytes()),
Self::Str(s) => f(s.as_bytes()),
}
}

/// Borrow an object's payload without allocating or invoking Python conversion.
/// Other objects return `None`, rather than raising a conversion error.
pub fn with_object_ref<F, R>(obj: &PyObject, f: F) -> Option<R>
where
F: FnOnce(&[u8]) -> R,
{
if let Some(b) = obj.downcast_ref::<PyBytes>() {
Some(f(b.as_bytes()))
} else {
obj.downcast_ref::<PyStr>().map(|s| f(s.as_bytes()))
}
}
}

impl TryFromObject for ArgBytesOrStr {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
obj.downcast()
.map(Self::Bytes)
.or_else(|obj| obj.downcast().map(Self::Str))
.map_err(|obj| vm.new_type_error(format!("unexpected type {}", obj.class())))
}
}

/// A text string or bytes-like object. Like the `s*` format code for `PyArg_Parse` in CPython.
pub enum ArgStrOrBytesLike {
Buf(ArgBytesLike),
Expand Down Expand Up @@ -315,3 +365,64 @@ impl ArgAsciiBuffer {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{Interpreter, common::wtf8::Wtf8Buf};

#[test]
fn bytes_or_str_borrows_original_payloads() {
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let expected = [0xed, 0xa0, 0x80];
let objects: [PyObjectRef; 2] = [
vm.ctx.new_bytes(expected.to_vec()).into(),
vm.ctx.new_str(Wtf8Buf::from_wide(&[0xd800])).into(),
];
for obj in objects {
let original = if let Some(b) = obj.downcast_ref::<PyBytes>() {
b.as_bytes()
} else {
obj.downcast_ref::<PyStr>().unwrap().as_bytes()
};
let ptr = original.as_ptr();
let arg = ArgBytesOrStr::try_from_object(vm, obj.clone()).unwrap();
assert!(arg.as_object().is(&obj));
let count = obj.strong_count();
let mut calls = 0;
assert_eq!(
ArgBytesOrStr::with_object_ref(&obj, |bytes| {
calls += 1;
assert_eq!(obj.strong_count(), count);
assert_eq!(bytes.as_ptr(), ptr);
assert_eq!(bytes, expected);
}),
Some(())
);
assert_eq!(calls, 1);
drop(obj);
arg.with_ref(|bytes| {
assert_eq!(bytes.as_ptr(), ptr);
assert_eq!(bytes, expected);
});
}
});
}

#[test]
fn bytes_or_str_rejects_other_objects_without_borrowing() {
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let objects: [PyObjectRef; 2] = [
vm.ctx.new_bytearray(vec![b'*']).into(),
vm.ctx.new_int(42).into(),
];
for obj in objects {
assert_eq!(
ArgBytesOrStr::with_object_ref(&obj, |_| panic!("unexpected borrow")),
None::<()>
);
assert!(ArgBytesOrStr::try_from_object(vm, obj).is_err());
}
});
}
}
3 changes: 2 additions & 1 deletion crates/vm/src/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ pub(crate) use argument::{
};
pub use arithmetic::{PyArithmeticValue, PyComparisonValue};
pub use buffer::{
ArgAsciiBuffer, ArgBytesLike, ArgContiguousBytesLike, ArgMemoryBuffer, ArgStrOrBytesLike,
ArgAsciiBuffer, ArgBytesLike, ArgBytesOrStr, ArgContiguousBytesLike, ArgMemoryBuffer,
ArgStrOrBytesLike,
};
pub use builtin::{IntoPyNativeFn, PyNativeFn, static_func, static_raw_func};
pub use doctext::{ItemDoc, db_doc, plain_doc};
Expand Down
Loading