Skip to content

Commit 0f4c2c1

Browse files
author
Antonio Yang
committed
byte.decode
- support ascii, utf-8 encoding - raise LookupError for unhandled encoding
1 parent 13d0c07 commit 0f4c2c1

File tree

4 files changed

+124
-1
lines changed

4 files changed

+124
-1
lines changed

tests/snippets/bytes.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@
322322

323323
# make trans
324324
# fmt: off
325-
assert (
325+
assert (
326326
bytes.maketrans(memoryview(b"abc"), bytearray(b"zzz"))
327327
== bytes([0, 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, 122, 122, 122, 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, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255])
328328
)
@@ -597,3 +597,11 @@
597597
assert a * 1 == b'abcd'
598598
assert a * 3 == b'abcdabcdabcd'
599599
assert 3 * a == b'abcdabcdabcd'
600+
601+
# decode
602+
assert b'\x72\x75\x73\x74'.decode('ascii') == 'rust'
603+
assert b'\xc2\xae\x75\x73\x74'.decode('ascii', 'replace') == '��ust'
604+
assert b'\xc2\xae\x75\x73\x74'.decode('ascii', 'ignore') == 'ust'
605+
assert b'\xc2\xae\x75\x73\x74'.decode('utf-8') == '®ust'
606+
assert b'\xc2\xae\x75\x73\x74'.decode() == '®ust'
607+
assert b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97'.decode('utf-8') == '中文字'

vm/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ proc-macro-hack = { version = "0.5", optional = true }
6262
bitflags = "1.1"
6363
libc = "0.2"
6464
nix = "0.14.1"
65+
wtf8 = "0.0.3"
6566

6667
flame = { version = "0.2", optional = true }
6768
flamer = { version = "0.3", optional = true }

vm/src/obj/objbytes.rs

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ use super::objiter;
2323

2424
use super::objtype::PyClassRef;
2525

26+
use wtf8;
27+
2628
/// "bytes(iterable_of_ints) -> bytes\n\
2729
/// bytes(string, encoding[, errors]) -> bytes\n\
2830
/// bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\
@@ -420,6 +422,113 @@ impl PyBytesRef {
420422
fn rmul(self, n: PyIntRef, vm: &VirtualMachine) -> PyResult {
421423
self.repeat(n, vm)
422424
}
425+
426+
/// Return a string decoded from the given bytes.
427+
/// Default encoding is 'utf-8'.
428+
/// Default errors is 'strict', meaning that encoding errors raise a UnicodeError.
429+
/// Other possible values are 'ignore', 'replace'
430+
/// For a list of possible encodings,
431+
/// see https://docs.python.org/3/library/codecs.html#standard-encodings
432+
/// currently, only 'utf-8' and 'ascii' emplemented
433+
#[pymethod(name = "decode")]
434+
fn decode(
435+
self,
436+
encoding: OptionalArg<PyStringRef>,
437+
errors: OptionalArg<PyStringRef>,
438+
vm: &VirtualMachine,
439+
) -> PyResult<String> {
440+
let mut strict_mod = true;
441+
let replacing_char = match errors {
442+
OptionalArg::Present(ref input) => match input.as_str() {
443+
"replace" => {
444+
strict_mod = false;
445+
Some('\u{FFFD}')
446+
}
447+
"ignore" => {
448+
strict_mod = false;
449+
None
450+
}
451+
_ => None,
452+
},
453+
OptionalArg::Missing => None,
454+
};
455+
let encoding_type = match encoding {
456+
OptionalArg::Present(ref input) => input.as_str(),
457+
OptionalArg::Missing => "utf-8",
458+
};
459+
460+
let decode_error = Err(vm.new_value_error("DecodeError".to_string()));
461+
462+
let mut decode_content = String::new();
463+
match encoding_type {
464+
"ascii" => {
465+
for &b in self.get_value() {
466+
if b.is_ascii() {
467+
decode_content.push(b as char)
468+
} else if !strict_mod && replacing_char.is_some() {
469+
decode_content.push(replacing_char.unwrap())
470+
}
471+
}
472+
}
473+
"utf-8" | "utf8" | "" => {
474+
let mut p: u32 = 0u32;
475+
let mut remaining_bytes = 0;
476+
for &b in self.get_value() {
477+
if (b as u8) & 128 == 0 {
478+
if b.is_ascii() {
479+
decode_content.push(b as char)
480+
} else if !strict_mod && replacing_char.is_some() {
481+
decode_content.push(replacing_char.unwrap())
482+
}
483+
} else if (b as u8) & 192 == 128 {
484+
remaining_bytes -= 1;
485+
486+
p += u32::from(b as u8 & 63) << (6 * remaining_bytes);
487+
488+
if remaining_bytes == 0 {
489+
match wtf8::CodePoint::from_u32(p) {
490+
Some(cp) => {
491+
if !strict_mod && replacing_char.is_some() {
492+
decode_content.push(cp.to_char_lossy());
493+
} else {
494+
match cp.to_char() {
495+
Some(c) => decode_content.push(c),
496+
None => {
497+
if strict_mod {
498+
return decode_error;
499+
}
500+
}
501+
}
502+
}
503+
}
504+
None => {
505+
if replacing_char.is_none() {
506+
decode_content.push(replacing_char.unwrap())
507+
}
508+
}
509+
}
510+
p = 0u32;
511+
}
512+
} else if (b as u8) & 224 == 192 {
513+
remaining_bytes = 1;
514+
p = u32::from(b as u8 & 31) << 6;
515+
} else if (b as u8) & 240 == 224 {
516+
remaining_bytes = 2;
517+
p = u32::from(b as u8 & 15) << 12;
518+
} else if (b as u8) & 248 == 240 {
519+
remaining_bytes = 3;
520+
p = u32::from(b as u8 & 7) << 18;
521+
} else if !strict_mod && replacing_char.is_some() {
522+
decode_content.push(replacing_char.unwrap())
523+
}
524+
}
525+
}
526+
_ => {
527+
return Err(vm.new_lookup_error(format!("unknown encoding: {}", encoding_type)));
528+
}
529+
}
530+
Ok(decode_content)
531+
}
423532
}
424533

425534
#[pyclass]

vm/src/vm.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,11 @@ impl VirtualMachine {
265265
self.new_exception_obj(exc_type, vec![pystr_msg]).unwrap()
266266
}
267267

268+
pub fn new_lookup_error(&self, msg: String) -> PyObjectRef {
269+
let lookup_error = self.ctx.exceptions.lookup_error.clone();
270+
self.new_exception(lookup_error, msg)
271+
}
272+
268273
pub fn new_attribute_error(&self, msg: String) -> PyObjectRef {
269274
let attribute_error = self.ctx.exceptions.attribute_error.clone();
270275
self.new_exception(attribute_error, msg)

0 commit comments

Comments
 (0)