1+ use super :: objstr;
2+ use super :: objtype;
13use super :: pyobject:: {
24 AttributeProtocol , PyContext , PyFuncArgs , PyObject , PyObjectKind , PyObjectRef , PyResult ,
5+ TypeProtocol ,
36} ;
47use super :: vm:: VirtualMachine ;
58use std:: collections:: HashMap ;
@@ -23,10 +26,43 @@ pub fn new(dict_type: PyObjectRef) -> PyObjectRef {
2326 )
2427}
2528
29+ fn get_elements ( obj : & PyObjectRef ) -> HashMap < String , PyObjectRef > {
30+ if let PyObjectKind :: Dict { elements } = & obj. borrow ( ) . kind {
31+ elements. clone ( )
32+ } else {
33+ panic ! ( "Cannot extract dict elements" ) ;
34+ }
35+ }
36+
2637fn dict_new ( _vm : & mut VirtualMachine , args : PyFuncArgs ) -> PyResult {
2738 Ok ( new ( args. args [ 0 ] . clone ( ) ) )
2839}
2940
41+ fn dict_len ( vm : & mut VirtualMachine , args : PyFuncArgs ) -> PyResult {
42+ arg_check ! ( vm, args, required = [ ( o, Some ( vm. ctx. dict_type( ) ) ) ] ) ;
43+ let elements = get_elements ( o) ;
44+ Ok ( vm. ctx . new_int ( elements. len ( ) as i32 ) )
45+ }
46+
47+ fn dict_str ( vm : & mut VirtualMachine , args : PyFuncArgs ) -> PyResult {
48+ arg_check ! ( vm, args, required = [ ( o, Some ( vm. ctx. dict_type( ) ) ) ] ) ;
49+
50+ let elements = get_elements ( o) ;
51+ let mut str_parts = vec ! [ ] ;
52+ for elem in elements {
53+ match vm. to_str ( elem. 1 ) {
54+ Ok ( s) => {
55+ let value_str = objstr:: get_value ( & s) ;
56+ str_parts. push ( format ! ( "{}: {}" , elem. 0 , value_str) ) ;
57+ }
58+ Err ( err) => return Err ( err) ,
59+ }
60+ }
61+
62+ let s = format ! ( "{{ {} }}" , str_parts. join( ", " ) ) ;
63+ Ok ( vm. new_str ( s) )
64+ }
65+
3066pub fn create_type ( type_type : PyObjectRef , object_type : PyObjectRef , dict_type : PyObjectRef ) {
3167 ( * dict_type. borrow_mut ( ) ) . kind = PyObjectKind :: Class {
3268 name : String :: from ( "dict" ) ,
@@ -38,5 +74,7 @@ pub fn create_type(type_type: PyObjectRef, object_type: PyObjectRef, dict_type:
3874
3975pub fn init ( context : & PyContext ) {
4076 let ref dict_type = context. dict_type ;
77+ dict_type. set_attr ( "__len__" , context. new_rustfunc ( dict_len) ) ;
4178 dict_type. set_attr ( "__new__" , context. new_rustfunc ( dict_new) ) ;
79+ dict_type. set_attr ( "__str__" , context. new_rustfunc ( dict_str) ) ;
4280}
0 commit comments