rustpython_vm::sequence & PySequenceContainer

This commit is contained in:
Jeong YunWon
2020-01-06 02:26:17 +09:00
parent 50ff5e89f9
commit 0aca07a8cb
3 changed files with 31 additions and 1 deletions

View File

@@ -64,6 +64,7 @@ pub mod py_serde;
mod pyhash;
pub mod pyobject;
pub mod scope;
mod sequence;
pub mod stdlib;
mod sysmodule;
pub mod types;

View File

@@ -9,6 +9,7 @@ use crate::pyhash;
use crate::pyobject::{
IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
};
use crate::sequence::PySequenceContainer;
use crate::vm::{ReprGuard, VirtualMachine};
/// tuple() -> empty tuple
@@ -57,13 +58,19 @@ impl_intopyobj_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
impl_intopyobj_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
impl_intopyobj_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
impl PySequenceContainer for PyTuple {
fn as_slice(&self) -> &[PyObjectRef] {
&self.elements
}
}
impl PyTuple {
pub fn fast_getitem(&self, idx: usize) -> PyObjectRef {
self.elements[idx].clone()
}
pub fn as_slice(&self) -> &[PyObjectRef] {
&self.elements
<PyTuple as PySequenceContainer>::as_slice(self)
}
}

22
vm/src/sequence.rs Normal file
View File

@@ -0,0 +1,22 @@
use crate::pyobject::{PyObjectRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
pub trait PySequenceContainer
where
Self: PyValue,
{
fn as_slice(&self) -> &[PyObjectRef];
#[inline]
fn cmp<F>(&self, other: PyObjectRef, op: F, vm: &VirtualMachine) -> PyResult
where
F: Fn(&[PyObjectRef], &[PyObjectRef]) -> PyResult<bool>,
{
let r = if let Some(other) = other.payload_if_subclass::<Self>(vm) {
vm.new_bool(op(self.as_slice(), other.as_slice())?)
} else {
vm.ctx.not_implemented()
};
Ok(r)
}
}