Skip to content
Merged
Changes from all commits
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
Implement AsMapping for PyStr
  • Loading branch information
moreal committed Nov 6, 2021
commit 276608233e74e1eb478f2af654095bdbd57cd3a6
45 changes: 40 additions & 5 deletions vm/src/builtins/pystr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ use crate::{
anystr::{self, adjust_indices, AnyStr, AnyStrContainer, AnyStrWrapper},
format::{FormatSpec, FormatString, FromTemplate},
function::{ArgIterable, FuncArgs, IntoPyException, IntoPyObject, OptionalArg, OptionalOption},
protocol::PyIterReturn,
protocol::{PyIterReturn, PyMappingMethods},
sliceable::PySliceableSequence,
types::{
Comparable, Constructor, Hashable, IterNext, IterNextIterable, Iterable, PyComparisonOp,
Unconstructible,
AsMapping, Comparable, Constructor, Hashable, IterNext, IterNextIterable, Iterable,
PyComparisonOp, Unconstructible,
},
utils::Either,
IdProtocol, ItemProtocol, PyClassDef, PyClassImpl, PyComparisonValue, PyContext, PyObject,
PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol, VirtualMachine,
PyObjectRef, PyObjectView, PyRef, PyResult, PyValue, TypeProtocol, VirtualMachine,
};
use ascii::{AsciiStr, AsciiString};
use bstr::ByteSlice;
Expand Down Expand Up @@ -363,7 +363,10 @@ impl PyStr {
}
}

#[pyimpl(flags(BASETYPE), with(Hashable, Comparable, Iterable, Constructor))]
#[pyimpl(
flags(BASETYPE),
with(AsMapping, Hashable, Comparable, Iterable, Constructor)
)]
impl PyStr {
#[pymethod(magic)]
fn add(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Expand Down Expand Up @@ -1245,6 +1248,38 @@ impl Iterable for PyStr {
}
}

impl AsMapping for PyStr {
fn as_mapping(_zelf: &PyObjectView<Self>, _vm: &VirtualMachine) -> PyMappingMethods {
PyMappingMethods {
length: Some(Self::length),
subscript: Some(Self::subscript),
ass_subscript: None,
}
}

#[inline]
fn length(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
Self::downcast_ref(&zelf, vm).map(|zelf| Ok(zelf.len()))?
}

#[inline]
fn subscript(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Self::downcast_ref(&zelf, vm)
.map(|zelf| zelf.getitem(needle, vm))?
.map(|item| item.into_object(vm))
}

#[cold]
fn ass_subscript(
zelf: PyObjectRef,
_needle: PyObjectRef,
_value: Option<PyObjectRef>,
_vm: &VirtualMachine,
) -> PyResult<()> {
unreachable!("ass_subscript not implemented for {}", zelf.class())
}
}

#[derive(FromArgs)]
struct EncodeArgs {
#[pyarg(any, default)]
Expand Down