optim str

Update str.h

Update str.h
This commit is contained in:
blueloveTH 2022-11-20 19:27:01 +08:00
parent 3cc481c50e
commit 75ed4c350e
5 changed files with 21 additions and 22 deletions

View File

@ -16,6 +16,7 @@
#include <string_view>
#include <queue>
#include <iomanip>
#include <map>
#include <thread>
#include <atomic>

View File

@ -23,7 +23,7 @@ struct ByteCode{
};
_Str pad(const _Str& s, const int n){
return s + _Str(n - s.size(), ' ');
return s + std::string(n - s.size(), ' ');
}
struct CodeObject {

View File

@ -260,7 +260,7 @@ public:
int ret = parser->eatName();
if(ret!=0) syntaxError("identifier is illegal, err " + std::to_string(ret));
} else {
syntaxError("unknown character: " + _Str(1, c));
syntaxError("unknown character: " + std::string(1, c));
}
return;
}

View File

@ -83,7 +83,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
vm->__checkArgSize(args, 1);
_Int i = vm->PyInt_AS_C(args[0]);
if (i < 0 || i > 128) vm->valueError("chr() arg not in range(128)");
return vm->PyStr(_Str(1, (char)i));
return vm->PyStr(std::string(1, (char)i));
});
_vm->bindBuiltinFunc("ord", [](VM* vm, const pkpy::ArgList& args) {

View File

@ -55,13 +55,12 @@ public:
};
std::unordered_map<std::string, std::shared_ptr<_StrMemory>> _strIntern;
std::map<std::string, std::shared_ptr<_StrMemory>, std::less<>> _strIntern;
struct _StrLiteral {
const char* _str;
size_t _len;
constexpr _StrLiteral(const char* str, size_t len) : _str(str), _len(len) {}
class _StrLiteral : public std::string_view {
public:
constexpr _StrLiteral(const char* str, size_t len) : std::string_view(str, len) {}
};
inline constexpr _StrLiteral operator "" _c(const char* str, size_t len){
@ -74,36 +73,35 @@ private:
bool interned = false;
public:
_Str(const _StrLiteral& s){
construct(std::string(s._str, s._len));
construct(s);
intern();
}
_Str(const char* s){
construct(std::string(s));
construct(s);
}
_Str(const char* s, size_t len){
construct(std::string(s, len));
construct(std::string_view(s, len));
}
_Str(int n, char fill){
construct(std::string(n, fill));
_Str(){
construct("");
}
_Str(const std::string& s){
construct(s);
}
_Str(std::string&& s){
construct(std::move(s));
}
_Str(){
construct(std::string());
}
_Str(const _Str& s) : _s(s._s), interned(s.interned) {}
void construct(std::string s){
auto it = _strIntern.find(s);
// for move constructor, we do not check if the string is interned!!
_Str(std::string&& s){
this->_s = std::make_shared<_StrMemory>(std::move(s));
}
void construct(const std::string_view& sv){
auto it = _strIntern.find(sv);
if(it != _strIntern.end()){
this->_s = it->second;
interned = true;
}else{
this->_s = std::make_shared<_StrMemory>(std::move(s));
this->_s = std::make_shared<_StrMemory>(std::string(sv));
}
}