forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjset.rs
More file actions
165 lines (145 loc) · 5.03 KB
/
objset.rs
File metadata and controls
165 lines (145 loc) · 5.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
* Builtin set type with a sequence of unique items.
*/
use super::super::pyobject::{
AttributeProtocol, IdProtocol, PyContext, PyFuncArgs, PyObject, PyObjectKind, PyObjectRef,
PyResult, TypeProtocol,
};
use super::super::vm::VirtualMachine;
use super::objbool;
use super::objiter;
use super::objstr;
use super::objtype;
use num_bigint::ToBigInt;
use std::collections::HashMap;
pub fn get_elements(obj: &PyObjectRef) -> HashMap<usize, PyObjectRef> {
if let PyObjectKind::Set { elements } = &obj.borrow().kind {
elements.clone()
} else {
panic!("Cannot extract set elements from non-set");
}
}
pub fn sequence_to_hashmap(iterable: &Vec<PyObjectRef>) -> HashMap<usize, PyObjectRef> {
let mut elements = HashMap::new();
for item in iterable {
let key = item.get_id();
elements.insert(key, item.clone());
}
elements
}
fn set_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("set.add called with: {:?}", args);
arg_check!(
vm,
args,
required = [(s, Some(vm.ctx.set_type())), (item, None)]
);
let mut mut_obj = s.borrow_mut();
if let PyObjectKind::Set { ref mut elements } = mut_obj.kind {
let key = item.get_id();
elements.insert(key, item.clone());
Ok(vm.get_none())
} else {
Err(vm.new_type_error("set.add is called with no list".to_string()))
}
}
/* Create a new object of sub-type of set */
fn set_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(cls, None)],
optional = [(iterable, None)]
);
if !objtype::issubclass(cls, &vm.ctx.set_type()) {
return Err(vm.new_type_error(format!("{:?} is not a subtype of set", cls)));
}
let elements = match iterable {
None => HashMap::new(),
Some(iterable) => {
let mut elements = HashMap::new();
let iterator = objiter::get_iter(vm, iterable)?;
loop {
match vm.call_method(&iterator, "__next__", vec![]) {
Ok(v) => {
// TODO: should we use the hash function here?
let key = v.get_id();
elements.insert(key, v);
}
_ => break,
}
}
elements
}
};
Ok(PyObject::new(
PyObjectKind::Set { elements: elements },
cls.clone(),
))
}
fn set_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("set.len called with: {:?}", args);
arg_check!(vm, args, required = [(s, Some(vm.ctx.set_type()))]);
let elements = get_elements(s);
Ok(vm.context().new_int(elements.len().to_bigint().unwrap()))
}
fn set_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(o, Some(vm.ctx.set_type()))]);
let elements = get_elements(o);
let s = if elements.len() == 0 {
"set()".to_string()
} else {
let mut str_parts = vec![];
for elem in elements.values() {
let part = vm.to_repr(elem)?;
str_parts.push(objstr::get_value(&part));
}
format!("{{{}}}", str_parts.join(", "))
};
Ok(vm.new_str(s))
}
pub fn set_contains(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(set, Some(vm.ctx.set_type())), (needle, None)]
);
for element in get_elements(set).iter() {
match vm.call_method(needle, "__eq__", vec![element.1.clone()]) {
Ok(value) => {
if objbool::get_value(&value) {
return Ok(vm.new_bool(true));
}
}
Err(_) => return Err(vm.new_type_error("".to_string())),
}
}
Ok(vm.new_bool(false))
}
fn frozenset_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(o, Some(vm.ctx.frozenset_type()))]);
let elements = get_elements(o);
let s = if elements.len() == 0 {
"frozenset()".to_string()
} else {
let mut str_parts = vec![];
for elem in elements.values() {
let part = vm.to_repr(elem)?;
str_parts.push(objstr::get_value(&part));
}
format!("frozenset({{{}}})", str_parts.join(", "))
};
Ok(vm.new_str(s))
}
pub fn init(context: &PyContext) {
let ref set_type = context.set_type;
set_type.set_attr("__contains__", context.new_rustfunc(set_contains));
set_type.set_attr("__len__", context.new_rustfunc(set_len));
set_type.set_attr("__new__", context.new_rustfunc(set_new));
set_type.set_attr("__repr__", context.new_rustfunc(set_repr));
set_type.set_attr("add", context.new_rustfunc(set_add));
let ref frozenset_type = context.set_type;
frozenset_type.set_attr("__contains__", context.new_rustfunc(set_contains));
frozenset_type.set_attr("__len__", context.new_rustfunc(set_len));
frozenset_type.set_attr("__repr__", context.new_rustfunc(frozenset_repr));
}