From 0bd25e7224f35c4a75585c5689fe3a4959a8771d Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Tue, 6 Aug 2024 12:54:20 +0800 Subject: [PATCH] ... --- src/public/py_str.c | 20 ++++++++++++++++++++ tests/46_bytes.py | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/public/py_str.c b/src/public/py_str.c index 11e2596b..0c83f20a 100644 --- a/src/public/py_str.c +++ b/src/public/py_str.c @@ -522,6 +522,25 @@ py_Type pk_str_iterator__register() { return type; } +static bool bytes__new__(int argc, py_Ref argv){ + if(argc == 1){ + py_newbytes(py_retval(), 0); + return true; + } + if(argc > 2) return TypeError("bytes() takes at most 1 argument"); + int length; + py_TValue* p = pk_arrayview(&argv[1], &length); + if(!p) return TypeError("bytes() argument must be a list or tuple"); + unsigned char* data = py_newbytes(py_retval(), length); + for(int i = 0; i < length; i++){ + if(!py_checktype(&p[i], tp_int)) return false; + py_i64 v = py_toint(&p[i]); + if(v < 0 || v > 255) return ValueError("bytes must be in range(0, 256)"); + data[i] = v; + } + return true; +} + static bool bytes__repr__(int argc, py_Ref argv) { PY_CHECK_ARGC(1); c11_bytes* self = py_touserdata(&argv[0]); @@ -611,6 +630,7 @@ py_Type pk_bytes__register() { py_Type type = pk_newtype("bytes", tp_object, NULL, NULL, false, true); // no need to dtor because the memory is controlled by the object + py_bindmagic(tp_bytes, __new__, bytes__new__); py_bindmagic(tp_bytes, __repr__, bytes__repr__); py_bindmagic(tp_bytes, __getitem__, bytes__getitem__); py_bindmagic(tp_bytes, __eq__, bytes__eq__); diff --git a/tests/46_bytes.py b/tests/46_bytes.py index 985a415d..091570b5 100644 --- a/tests/46_bytes.py +++ b/tests/46_bytes.py @@ -34,4 +34,8 @@ assert a[::-1] == b"!dlroW ,olleH" assert a[::2] == b"Hlo ol!" assert a[2:5:2] == b"lo" assert a[5:2:-1] == b",ol" -assert a[5:2:-2] == b",l" \ No newline at end of file +assert a[5:2:-2] == b",l" + +assert bytes() == b'' +assert bytes((65,)) == b'A' +assert bytes([0, 1, 2, 3]) == b'\x00\x01\x02\x03' \ No newline at end of file