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
162 lines (138 loc) · 4.8 KB
/
objbytes.rs
File metadata and controls
162 lines (138 loc) · 4.8 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
use std::cell::Cell;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use num_traits::ToPrimitive;
use crate::function::OptionalArg;
use crate::pyobject::{PyContext, PyIteratorValue, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
use super::objint;
use super::objtype::PyClassRef;
#[derive(Debug)]
pub struct PyBytes {
value: Vec<u8>,
}
type PyBytesRef = PyRef<PyBytes>;
impl PyBytes {
pub fn new(data: Vec<u8>) -> Self {
PyBytes { value: data }
}
}
impl Deref for PyBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.value
}
}
impl PyValue for PyBytes {
fn class(vm: &VirtualMachine) -> PyClassRef {
vm.ctx.bytes_type()
}
}
// Binary data support
// Fill bytes class methods:
pub fn init(context: &PyContext) {
let bytes_type = context.bytes_type.as_object();
let bytes_doc =
"bytes(iterable_of_ints) -> bytes\n\
bytes(string, encoding[, errors]) -> bytes\n\
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\
bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\
bytes() -> empty bytes object\n\nConstruct an immutable array of bytes from:\n \
- an iterable yielding integers in range(256)\n \
- a text string encoded using the specified encoding\n \
- any object implementing the buffer API.\n \
- an integer";
extend_class!(context, bytes_type, {
"__new__" => context.new_rustfunc(bytes_new),
"__eq__" => context.new_rustfunc(PyBytesRef::eq),
"__lt__" => context.new_rustfunc(PyBytesRef::lt),
"__le__" => context.new_rustfunc(PyBytesRef::le),
"__gt__" => context.new_rustfunc(PyBytesRef::gt),
"__ge__" => context.new_rustfunc(PyBytesRef::ge),
"__hash__" => context.new_rustfunc(PyBytesRef::hash),
"__repr__" => context.new_rustfunc(PyBytesRef::repr),
"__len__" => context.new_rustfunc(PyBytesRef::len),
"__iter__" => context.new_rustfunc(PyBytesRef::iter),
"__doc__" => context.new_str(bytes_doc.to_string())
});
}
fn bytes_new(
cls: PyClassRef,
val_option: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<PyBytesRef> {
// Create bytes data:
let value = if let OptionalArg::Present(ival) = val_option {
let elements = vm.extract_elements(&ival)?;
let mut data_bytes = vec![];
for elem in elements.iter() {
let v = objint::to_int(vm, elem, 10)?;
data_bytes.push(v.to_u8().unwrap());
}
data_bytes
// return Err(vm.new_type_error("Cannot construct bytes".to_string()));
} else {
vec![]
};
PyBytes::new(value).into_ref_with_type(vm, cls)
}
impl PyBytesRef {
fn eq(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Ok(other) = other.downcast::<PyBytes>() {
vm.ctx.new_bool(self.value == other.value)
} else {
vm.ctx.not_implemented()
}
}
fn ge(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Ok(other) = other.downcast::<PyBytes>() {
vm.ctx.new_bool(self.value >= other.value)
} else {
vm.ctx.not_implemented()
}
}
fn gt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Ok(other) = other.downcast::<PyBytes>() {
vm.ctx.new_bool(self.value > other.value)
} else {
vm.ctx.not_implemented()
}
}
fn le(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Ok(other) = other.downcast::<PyBytes>() {
vm.ctx.new_bool(self.value <= other.value)
} else {
vm.ctx.not_implemented()
}
}
fn lt(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Ok(other) = other.downcast::<PyBytes>() {
vm.ctx.new_bool(self.value < other.value)
} else {
vm.ctx.not_implemented()
}
}
fn len(self, _vm: &VirtualMachine) -> usize {
self.value.len()
}
fn hash(self, _vm: &VirtualMachine) -> u64 {
let mut hasher = DefaultHasher::new();
self.value.hash(&mut hasher);
hasher.finish()
}
fn repr(self, _vm: &VirtualMachine) -> String {
// TODO: don't just unwrap
let data = String::from_utf8(self.value.clone()).unwrap();
format!("b'{}'", data)
}
fn iter(obj: PyBytesRef, _vm: &VirtualMachine) -> PyIteratorValue {
PyIteratorValue {
position: Cell::new(0),
iterated_obj: obj.into_object(),
}
}
}
pub fn get_value<'a>(obj: &'a PyObjectRef) -> impl Deref<Target = Vec<u8>> + 'a {
&obj.payload::<PyBytes>().unwrap().value
}