BLUELOVETH %!s(int64=2) %!d(string=hai) anos
pai
achega
c0e06c3144
Modificáronse 4 ficheiros con 8 adicións e 3 borrados
  1. 3 2
      include/pocketpy/obj.h
  2. BIN=BIN
      libpocketpy.dylib
  3. 2 1
      src/pocketpy.cpp
  4. 3 0
      tests/10_bytes.py

+ 3 - 2
include/pocketpy/obj.h

@@ -61,11 +61,12 @@ struct Bytes{
         return _data != rhs._data;
     }
 
-    std::string str() const noexcept { return std::string(_data.begin(), _data.end()); }
+    Str str() const noexcept { return Str(_data.data(), _data.size()); }
 
     Bytes() : _data(), _ok(false) {}
     Bytes(std::vector<char>&& data) : _data(std::move(data)), _ok(true) {}
-    Bytes(const std::string& data) : _data(data.begin(), data.end()), _ok(true) {}
+    Bytes(const Str& data) : _data(data.begin(), data.end()), _ok(true) {}
+    Bytes(std::string_view sv): _data(sv.begin(), sv.end()), _ok(true) {}
     operator bool() const noexcept { return _ok; }
 };
 

BIN=BIN
libpocketpy.dylib


+ 2 - 1
src/pocketpy.cpp

@@ -916,7 +916,8 @@ void init_builtins(VM* _vm) {
 
     _vm->bind__hash__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {
         const Bytes& self = _CAST(Bytes&, obj);
-        return (i64)std::hash<std::string>()(self.str());
+        std::string_view view(self.data(), self.size());
+        return (i64)std::hash<std::string_view>()(view);
     });
 
     _vm->bind__repr__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {

+ 3 - 0
tests/10_bytes.py

@@ -3,3 +3,6 @@ assert a.encode() == b'12345'
 
 assert b'\xff\xee' != b'1234'
 assert b'\xff\xee' == b'\xff\xee'
+
+a = '测试123'
+assert a == a.encode().decode()