This commit is contained in:
blueloveTH 2023-07-29 16:01:19 +08:00
parent 73a5e8f19c
commit 8f7f8616e9

View File

@ -47,66 +47,45 @@ struct StarWrapper{
}; };
struct Bytes{ struct Bytes{
const char* _data; std::vector<char> _v;
int _size; bool valid;
int size() const noexcept { return _size; } int size() const noexcept { return (int)_v.size(); }
int operator[](int i) const noexcept { return (int)(uint8_t)_data[i]; } int operator[](int i) const noexcept { return (int)(uint8_t)_v[i]; }
const char* data() const noexcept { return _data; } const char* data() const noexcept { return _v.data(); }
bool operator==(const Bytes& rhs) const noexcept { bool operator==(const Bytes& rhs) const{ return _v == rhs._v && valid == rhs.valid; }
return _size == rhs._size && memcmp(_data, rhs._data, _size) == 0; bool operator!=(const Bytes& rhs) const{ return _v != rhs._v || valid != rhs.valid; }
}
bool operator!=(const Bytes& rhs) const noexcept { Str str() const noexcept { return Str(_v.data(), _v.size()); }
return _size != rhs._size || memcmp(_data, rhs._data, _size) != 0; std::string_view sv() const noexcept { return std::string_view(_v.data(), _v.size()); }
}
Str str() const noexcept { return Str(_data, _size); } Bytes() : valid(false) {}
std::string_view sv() const noexcept { return std::string_view(_data, _size); } Bytes(std::vector<char>&& v): _v(std::move(v)), valid(true) {}
Bytes(std::string_view sv): valid(true) {
Bytes() : _data(nullptr), _size(0) {} _v.resize(sv.size());
Bytes(std::vector<char>&& v){ for(int i=0; i<sv.size(); i++) _v[i] = sv[i];
char a[sizeof(std::vector<char>)];
new (a) std::vector<char>(std::move(v));
std::vector<char>* p = reinterpret_cast<std::vector<char>*>(a);
_data = p->data();
_size = p->size();
}
Bytes(std::string_view sv){
_data = new char[sv.size()];
memcpy((void*)_data, sv.data(), sv.size());
_size = sv.size();
} }
Bytes(const Str& str): Bytes(str.sv()) {} Bytes(const Str& str): Bytes(str.sv()) {}
operator bool() const noexcept { return _data != nullptr;} operator bool() const noexcept { return valid; }
// copy constructor // copy constructor
Bytes(const Bytes& rhs): Bytes(rhs.sv()) {} Bytes(const Bytes& rhs) : _v(rhs._v), valid(rhs.valid) {}
// move constructor // move constructor
Bytes(Bytes&& rhs){ Bytes(Bytes&& rhs) noexcept : _v(std::move(rhs._v)), valid(rhs.valid) {
_data = rhs._data; rhs.valid = false;
_size = rhs._size;
rhs._data = nullptr;
rhs._size = 0;
} }
Bytes& operator=(Bytes&& rhs) noexcept { Bytes& operator=(Bytes&& rhs) noexcept {
delete[] _data; _v = std::move(rhs._v);
_data = rhs._data; valid = rhs.valid;
_size = rhs._size; rhs.valid = false;
rhs._data = nullptr;
rhs._size = 0;
return *this; return *this;
} }
// delete copy assignment // delete copy assignment
Bytes& operator=(const Bytes& rhs) = delete; Bytes& operator=(const Bytes& rhs) = delete;
~Bytes(){
delete[] _data;
}
}; };
using Super = std::pair<PyObject*, Type>; using Super = std::pair<PyObject*, Type>;