Make validate_downcastable_from unsafe (#6851)

This commit is contained in:
Noa authored and GitHub committed 2026-01-26 10:39:08 +09:00
1 parent 0a9d41d3dd
commit 617cdc9724
5 files changed
+8 -12

No files matched your search

+1 -1
View File
@@ -667,7 +667,7 @@ pub(crate) fn impl_pyclass(attr: PunctuatedNestedMeta, item: Item) -> Result<Tok
const PAYLOAD_TYPE_ID: ::core::any::TypeId = <#base_type as ::rustpython_vm::PyPayload>::PAYLOAD_TYPE_ID;
#[inline]
fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
unsafe fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
<Self as ::rustpython_vm::class::PyClassDef>::BASICSIZE <= obj.class().slots.basicsize && obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
}
+1 -1
View File
@@ -595,7 +595,7 @@ pub(crate) fn impl_pystruct_sequence(
const PAYLOAD_TYPE_ID: ::core::any::TypeId = <::rustpython_vm::builtins::PyTuple as ::rustpython_vm::PyPayload>::PAYLOAD_TYPE_ID;
#[inline]
fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
unsafe fn validate_downcastable_from(obj: &::rustpython_vm::PyObject) -> bool {
obj.class().fast_issubclass(<Self as ::rustpython_vm::class::StaticType>::static_type())
}
+1 -1
View File
@@ -1944,7 +1944,7 @@ impl PyPayload for PyUtf8Str {
const PAYLOAD_TYPE_ID: core::any::TypeId = core::any::TypeId::of::<PyStr>();
fn validate_downcastable_from(obj: &PyObject) -> bool {
unsafe fn validate_downcastable_from(obj: &PyObject) -> bool {
// SAFETY: we know the object is a PyStr in this context
let wtf8 = unsafe { obj.downcast_unchecked_ref::<PyStr>() };
wtf8.is_utf8()
+1 -1
View File
@@ -753,7 +753,7 @@ impl PyObject {
/// Check if this object can be downcast to T.
#[inline(always)]
pub fn downcastable<T: PyPayload>(&self) -> bool {
T::downcastable_from(self)
self.typeid() == T::PAYLOAD_TYPE_ID && unsafe { T::validate_downcastable_from(self) }
}
/// Attempt to downcast this reference to a subclass.
+4 -8
View File
@@ -28,19 +28,15 @@ pub(crate) fn cold_downcast_type_error(
pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static {
const PAYLOAD_TYPE_ID: core::any::TypeId = core::any::TypeId::of::<Self>();
/// # Safety: this function should only be called if `payload_type_id` matches the type of `obj`.
/// # Safety
/// This function should only be called if `payload_type_id` matches the type of `obj`.
#[inline]
fn downcastable_from(obj: &PyObject) -> bool {
obj.typeid() == Self::PAYLOAD_TYPE_ID && Self::validate_downcastable_from(obj)
}
#[inline]
fn validate_downcastable_from(_obj: &PyObject) -> bool {
unsafe fn validate_downcastable_from(_obj: &PyObject) -> bool {
true
}
fn try_downcast_from(obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
if Self::downcastable_from(obj) {
if obj.downcastable::<Self>() {
return Ok(());
}