forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjbytes.rs
More file actions
60 lines (55 loc) · 1.9 KB
/
objbytes.rs
File metadata and controls
60 lines (55 loc) · 1.9 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
use super::super::pyobject::{
AttributeProtocol, FromPyObjectRef, PyContext, PyFuncArgs, PyObjectKind, PyObjectRef, PyResult,
TypeProtocol,
};
use super::super::vm::VirtualMachine;
use super::objint;
use super::objlist;
use super::objtype;
// Binary data support
// Fill bytes class methods:
pub fn init(context: &PyContext) {
let ref bytes_type = context.bytes_type;
bytes_type.set_attr("__init__", context.new_rustfunc(bytes_init));
bytes_type.set_attr("__str__", context.new_rustfunc(bytes_str));
}
// __init__ (store value into objectkind)
fn bytes_init(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(zelf, Some(vm.ctx.bytes_type())), (arg, None)]
);
let val = if objtype::isinstance(arg.clone(), vm.ctx.list_type()) {
let mut data_bytes = vec![];
for elem in objlist::get_elements(arg.clone()) {
let v = match objint::to_int(vm, &elem) {
Ok(int_ref) => int_ref,
Err(err) => return Err(err),
};
data_bytes.push(v as u8);
}
data_bytes
} else {
return Err(vm.new_type_error("Cannot construct bytes".to_string()));
};
set_value(zelf, val);
Ok(vm.get_none())
}
pub fn get_value(obj: &PyObjectRef) -> Vec<u8> {
if let PyObjectKind::Bytes { value } = &obj.borrow().kind {
value.clone()
} else {
panic!("Inner error getting int {:?}", obj);
}
}
fn set_value(obj: &PyObjectRef, value: Vec<u8>) {
obj.borrow_mut().kind = PyObjectKind::Bytes { value };
}
fn bytes_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytes_type()))]);
let data = get_value(obj);
let data: Vec<String> = data.into_iter().map(|b| format!("\\x{:02x}", b)).collect();
let data = data.join("");
Ok(vm.new_str(format!("b'{}'", data)))
}