@@ -7,15 +7,15 @@ use crate::{
7
7
anystr:: { self , adjust_indices, AnyStr , AnyStrContainer , AnyStrWrapper } ,
8
8
format:: { FormatSpec , FormatString , FromTemplate } ,
9
9
function:: { ArgIterable , FuncArgs , IntoPyException , IntoPyObject , OptionalArg , OptionalOption } ,
10
- protocol:: PyIterReturn ,
10
+ protocol:: { PyIterReturn , PyMappingMethods } ,
11
11
sliceable:: PySliceableSequence ,
12
12
types:: {
13
- Comparable , Constructor , Hashable , IterNext , IterNextIterable , Iterable , PyComparisonOp ,
14
- Unconstructible ,
13
+ AsMapping , Comparable , Constructor , Hashable , IterNext , IterNextIterable , Iterable ,
14
+ PyComparisonOp , Unconstructible ,
15
15
} ,
16
16
utils:: Either ,
17
17
IdProtocol , ItemProtocol , PyClassDef , PyClassImpl , PyComparisonValue , PyContext , PyObject ,
18
- PyObjectRef , PyRef , PyResult , PyValue , TypeProtocol , VirtualMachine ,
18
+ PyObjectRef , PyObjectView , PyRef , PyResult , PyValue , TypeProtocol , VirtualMachine ,
19
19
} ;
20
20
use ascii:: { AsciiStr , AsciiString } ;
21
21
use bstr:: ByteSlice ;
@@ -363,7 +363,10 @@ impl PyStr {
363
363
}
364
364
}
365
365
366
- #[ pyimpl( flags( BASETYPE ) , with( Hashable , Comparable , Iterable , Constructor ) ) ]
366
+ #[ pyimpl(
367
+ flags( BASETYPE ) ,
368
+ with( AsMapping , Hashable , Comparable , Iterable , Constructor )
369
+ ) ]
367
370
impl PyStr {
368
371
#[ pymethod( magic) ]
369
372
fn add ( zelf : PyRef < Self > , other : PyObjectRef , vm : & VirtualMachine ) -> PyResult {
@@ -1245,6 +1248,38 @@ impl Iterable for PyStr {
1245
1248
}
1246
1249
}
1247
1250
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
+
1248
1283
#[ derive( FromArgs ) ]
1249
1284
struct EncodeArgs {
1250
1285
#[ pyarg( any, default ) ]
0 commit comments