Skip to content

Commit 2766082

Browse files
committed
Implement AsMapping for PyStr
1 parent 40fd9c2 commit 2766082

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed

vm/src/builtins/pystr.rs

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@ use crate::{
77
anystr::{self, adjust_indices, AnyStr, AnyStrContainer, AnyStrWrapper},
88
format::{FormatSpec, FormatString, FromTemplate},
99
function::{ArgIterable, FuncArgs, IntoPyException, IntoPyObject, OptionalArg, OptionalOption},
10-
protocol::PyIterReturn,
10+
protocol::{PyIterReturn, PyMappingMethods},
1111
sliceable::PySliceableSequence,
1212
types::{
13-
Comparable, Constructor, Hashable, IterNext, IterNextIterable, Iterable, PyComparisonOp,
14-
Unconstructible,
13+
AsMapping, Comparable, Constructor, Hashable, IterNext, IterNextIterable, Iterable,
14+
PyComparisonOp, Unconstructible,
1515
},
1616
utils::Either,
1717
IdProtocol, ItemProtocol, PyClassDef, PyClassImpl, PyComparisonValue, PyContext, PyObject,
18-
PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol, VirtualMachine,
18+
PyObjectRef, PyObjectView, PyRef, PyResult, PyValue, TypeProtocol, VirtualMachine,
1919
};
2020
use ascii::{AsciiStr, AsciiString};
2121
use bstr::ByteSlice;
@@ -363,7 +363,10 @@ impl PyStr {
363363
}
364364
}
365365

366-
#[pyimpl(flags(BASETYPE), with(Hashable, Comparable, Iterable, Constructor))]
366+
#[pyimpl(
367+
flags(BASETYPE),
368+
with(AsMapping, Hashable, Comparable, Iterable, Constructor)
369+
)]
367370
impl PyStr {
368371
#[pymethod(magic)]
369372
fn add(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
@@ -1245,6 +1248,38 @@ impl Iterable for PyStr {
12451248
}
12461249
}
12471250

1251+
impl AsMapping for PyStr {
1252+
fn as_mapping(_zelf: &PyObjectView<Self>, _vm: &VirtualMachine) -> PyMappingMethods {
1253+
PyMappingMethods {
1254+
length: Some(Self::length),
1255+
subscript: Some(Self::subscript),
1256+
ass_subscript: None,
1257+
}
1258+
}
1259+
1260+
#[inline]
1261+
fn length(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
1262+
Self::downcast_ref(&zelf, vm).map(|zelf| Ok(zelf.len()))?
1263+
}
1264+
1265+
#[inline]
1266+
fn subscript(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
1267+
Self::downcast_ref(&zelf, vm)
1268+
.map(|zelf| zelf.getitem(needle, vm))?
1269+
.map(|item| item.into_object(vm))
1270+
}
1271+
1272+
#[cold]
1273+
fn ass_subscript(
1274+
zelf: PyObjectRef,
1275+
_needle: PyObjectRef,
1276+
_value: Option<PyObjectRef>,
1277+
_vm: &VirtualMachine,
1278+
) -> PyResult<()> {
1279+
unreachable!("ass_subscript not implemented for {}", zelf.class())
1280+
}
1281+
}
1282+
12481283
#[derive(FromArgs)]
12491284
struct EncodeArgs {
12501285
#[pyarg(any, default)]

0 commit comments

Comments
 (0)