Skip to content

Commit ba67f3c

Browse files
committed
refactore fromhex
1 parent 4a4d163 commit ba67f3c

File tree

3 files changed

+6
-12
lines changed

3 files changed

+6
-12
lines changed

tests/snippets/bytes.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@
142142
bytes.fromhex("6Z2")
143143
except ValueError as e:
144144
str(e) == "non-hexadecimal number found in fromhex() arg at position 1"
145-
145+
with assertRaises(TypeError):
146+
bytes.fromhex(b'hhjjk')
146147
# center
147148
assert [b"koki".center(i, b"|") for i in range(3, 10)] == [
148149
b"koki",

vm/src/obj/objbyteinner.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ impl PyByteInner {
342342
Ok(vm.ctx.new_str(bla))
343343
}
344344

345-
pub fn fromhex(string: String, vm: &VirtualMachine) -> Result<Vec<u8>, PyObjectRef> {
345+
pub fn fromhex(string: &str, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
346346
// first check for invalid character
347347
for (i, c) in string.char_indices() {
348348
if !c.is_digit(16) && !c.is_whitespace() {

vm/src/obj/objbytes.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::obj::objstr::PyString;
1+
use crate::obj::objstr::PyStringRef;
22
use crate::vm::VirtualMachine;
33
use core::cell::Cell;
44
use std::ops::Deref;
@@ -216,15 +216,8 @@ impl PyBytesRef {
216216
self.inner.hex(vm)
217217
}
218218

219-
// #[pymethod(name = "fromhex")]
220-
fn fromhex(string: PyObjectRef, vm: &VirtualMachine) -> PyResult {
221-
match_class!(string,
222-
s @ PyString => {
223-
match PyByteInner::fromhex(s.to_string(), vm) {
224-
Ok(x) => Ok(vm.ctx.new_bytes(x)),
225-
Err(y) => Err(y)}},
226-
obj => Err(vm.new_type_error(format!("fromhex() argument must be str, not {}", obj )))
227-
)
219+
fn fromhex(string: PyStringRef, vm: &VirtualMachine) -> PyResult {
220+
Ok(vm.ctx.new_bytes(PyByteInner::fromhex(string.as_str(), vm)?))
228221
}
229222

230223
#[pymethod(name = "center")]

0 commit comments

Comments
 (0)