Browse Source

add `bytes.__add__`

blueloveTH 1 year ago
parent
commit
d81a1c5415
2 changed files with 15 additions and 0 deletions
  1. 9 0
      src/pocketpy.cpp
  2. 6 0
      tests/11_bytes.py

+ 9 - 0
src/pocketpy.cpp

@@ -1073,6 +1073,15 @@ void init_builtins(VM* _vm) {
         return VAR(self[i]);
     });
 
+    _vm->bind__add__(VM::tp_bytes, [](VM* vm, PyObject* _0, PyObject* _1) {
+        const Bytes& a = _CAST(Bytes&, _0);
+        const Bytes& b = CAST(Bytes&, _1);
+        unsigned char *buffer = new unsigned char[a.size() + b.size()];
+        memcpy(buffer, a.data(), a.size());
+        memcpy(buffer + a.size(), b.data(), b.size());
+        return VAR(Bytes(buffer, a.size() + b.size()));
+    });
+
     _vm->bind__hash__(VM::tp_bytes, [](VM* vm, PyObject* _0) {
         const Bytes& self = _CAST(Bytes&, _0);
         std::string_view view((char*)self.data(), self.size());

+ 6 - 0
tests/11_bytes.py

@@ -1,6 +1,12 @@
 a = '12345'
 assert a.encode() == b'12345'
 
+# test add
+assert b'123' + b'456' == b'123456'
+assert b'' + b'123' == b'123'
+assert b'123' + b'' == b'123'
+assert b'' + b'' == b''
+
 assert b'\xff\xee' != b'1234'
 assert b'\xff\xee' == b'\xff\xee'