diff --git a/vm/src/lib.rs b/vm/src/lib.rs index 1f8fe9be4..c9b8a7686 100644 --- a/vm/src/lib.rs +++ b/vm/src/lib.rs @@ -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; diff --git a/vm/src/obj/objtuple.rs b/vm/src/obj/objtuple.rs index 00a011504..7d6957491 100644 --- a/vm/src/obj/objtuple.rs +++ b/vm/src/obj/objtuple.rs @@ -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 + ::as_slice(self) } } diff --git a/vm/src/sequence.rs b/vm/src/sequence.rs new file mode 100644 index 000000000..f6e494c7d --- /dev/null +++ b/vm/src/sequence.rs @@ -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(&self, other: PyObjectRef, op: F, vm: &VirtualMachine) -> PyResult + where + F: Fn(&[PyObjectRef], &[PyObjectRef]) -> PyResult, + { + let r = if let Some(other) = other.payload_if_subclass::(vm) { + vm.new_bool(op(self.as_slice(), other.as_slice())?) + } else { + vm.ctx.not_implemented() + }; + Ok(r) + } +}