Merge pull request #3728 from rng-dynamics/object-sizeof

Add `object.__sizeof__`
This commit is contained in:
Jeong YunWon
2022-05-21 13:15:46 +09:00
committed by GitHub
4 changed files with 13 additions and 1 deletions

View File

@@ -210,6 +210,7 @@ fn generate_class_def(
Some(v) => quote!(Some(#v) ),
None => quote!(None),
};
let basicsize = quote!(std::mem::size_of::<#ident>());
let is_pystruct = attrs.iter().any(|attr| {
path_eq(&attr.path, "derive")
&& if let Ok(Meta::List(l)) = attr.parse_meta() {
@@ -259,6 +260,7 @@ fn generate_class_def(
const MODULE_NAME: Option<&'static str> = #module_name;
const TP_NAME: &'static str = #module_class_name;
const DOC: Option<&'static str> = #doc;
const BASICSIZE: usize = #basicsize;
}
impl ::rustpython_vm::class::StaticType for #ident {

View File

@@ -326,6 +326,11 @@ impl PyBaseObject {
fn hash(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
Self::slot_hash(&zelf, vm)
}
#[pymethod(magic)]
fn sizeof(zelf: PyObjectRef) -> usize {
zelf.class().slots.basicsize
}
}
pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDictRef> {

View File

@@ -58,6 +58,7 @@ pub trait PyClassDef {
const MODULE_NAME: Option<&'static str>;
const TP_NAME: &'static str;
const DOC: Option<&'static str> = None;
const BASICSIZE: usize;
}
impl<T> PyClassDef for PyRef<T>
@@ -68,6 +69,7 @@ where
const MODULE_NAME: Option<&'static str> = T::MODULE_NAME;
const TP_NAME: &'static str = T::TP_NAME;
const DOC: Option<&'static str> = T::DOC;
const BASICSIZE: usize = T::BASICSIZE;
}
pub trait PyClassImpl: PyClassDef {
@@ -125,6 +127,7 @@ pub trait PyClassImpl: PyClassDef {
let mut slots = PyTypeSlots {
flags: Self::TP_FLAGS,
name: PyRwLock::new(Some(Self::TP_NAME.to_owned())),
basicsize: Self::BASICSIZE,
doc: Self::DOC,
..Default::default()
};

View File

@@ -23,7 +23,9 @@ use std::{
#[non_exhaustive]
pub struct PyTypeSlots {
pub name: PyRwLock<Option<String>>, // tp_name, not class name
// tp_basicsize, tp_itemsize
pub basicsize: usize,
// tp_itemsize
// Methods to implement standard operations