Skip to content
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
ctypes.Structure implementation
Signed-off-by: Ashwin Naren <arihant2math@gmail.com>
  • Loading branch information
arihant2math committed Feb 28, 2025
commit 66c40c6616e7157b0f6c972d24f3cd18e3a25ce4
54 changes: 53 additions & 1 deletion vm/src/stdlib/ctypes/structure.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,57 @@
use std::collections::HashMap;
use crate::builtins::{PyList, PyStr, PyTuple, PyTypeRef};
use crate::function::FuncArgs;
use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use rustpython_vm::types::Constructor;
use std::fmt::Debug;
use rustpython_common::lock::PyRwLock;
use crate::types::GetAttr;

#[pyclass(name = "Structure", module = "_ctypes")]
pub struct PyCStructure {}
#[derive(PyPayload, Debug)]
pub struct PyCStructure {
field_data: PyRwLock<HashMap<String, PyObjectRef>>,
data: PyRwLock<HashMap<String, PyObjectRef>>
}

impl Constructor for PyCStructure {
type Args = FuncArgs;

fn py_new(cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
let fields_attr = cls.get_class_attr(vm.ctx.interned_str("_fields_").unwrap()).ok_or_else(|| {
vm.new_attribute_error("Structure must have a _fields_ attribute".to_string())
})?;
// downcast into list
let fields = fields_attr.downcast_ref::<PyList>().ok_or_else(|| {
vm.new_type_error("Structure _fields_ attribute must be a list".to_string())
})?;
let fields = fields.borrow_vec();
let mut field_data = HashMap::new();
for field in fields.iter() {
let field = field.downcast_ref::<PyTuple>().ok_or_else(|| {
vm.new_type_error("Field must be a tuple".to_string())
})?;
let name = field.get(0).unwrap().downcast_ref::<PyStr>().ok_or_else(|| {
vm.new_type_error("Field name must be a string".to_string())
})?;
let typ = field.get(1).unwrap().clone();
field_data.insert(name.as_str().to_string(), typ);
}
todo!("Implement PyCStructure::py_new")
}
}

impl GetAttr for PyCStructure {
fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
let name = name.to_string();
let data = zelf.data.read();
match data.get(&name) {
Some(value) => Ok(value.clone()),
None => Err(vm.new_attribute_error(format!("No attribute named {}", name)))
}
}
}

#[pyclass(flags(BASETYPE, IMMUTABLETYPE))]
impl PyCStructure {}