str.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #include "pocketpy/str.h"
  2. namespace pkpy {
  3. int utf8len(unsigned char c, bool suppress){
  4. if((c & 0b10000000) == 0) return 1;
  5. if((c & 0b11100000) == 0b11000000) return 2;
  6. if((c & 0b11110000) == 0b11100000) return 3;
  7. if((c & 0b11111000) == 0b11110000) return 4;
  8. if((c & 0b11111100) == 0b11111000) return 5;
  9. if((c & 0b11111110) == 0b11111100) return 6;
  10. if(!suppress) throw std::runtime_error("invalid utf8 char: " + std::to_string(c));
  11. return 0;
  12. }
  13. #define PK_STR_ALLOCATE() \
  14. if(this->size < (int)sizeof(this->_inlined)){ \
  15. this->data = this->_inlined; \
  16. }else{ \
  17. this->data = (char*)pool64_alloc(this->size+1); \
  18. }
  19. #define PK_STR_COPY_INIT(__s) \
  20. for(int i=0; i<this->size; i++){ \
  21. this->data[i] = __s[i]; \
  22. if(!isascii(__s[i])) is_ascii = false; \
  23. } \
  24. this->data[this->size] = '\0';
  25. Str::Str(): size(0), is_ascii(true), data(_inlined) {
  26. _inlined[0] = '\0';
  27. }
  28. Str::Str(int size, bool is_ascii): size(size), is_ascii(is_ascii) {
  29. PK_STR_ALLOCATE()
  30. }
  31. Str::Str(const std::string& s): size(s.size()), is_ascii(true) {
  32. PK_STR_ALLOCATE()
  33. PK_STR_COPY_INIT(s)
  34. }
  35. Str::Str(std::string_view s): size(s.size()), is_ascii(true) {
  36. PK_STR_ALLOCATE()
  37. PK_STR_COPY_INIT(s)
  38. }
  39. Str::Str(const char* s): size(strlen(s)), is_ascii(true) {
  40. PK_STR_ALLOCATE()
  41. PK_STR_COPY_INIT(s)
  42. }
  43. Str::Str(const char* s, int len): size(len), is_ascii(true) {
  44. PK_STR_ALLOCATE()
  45. PK_STR_COPY_INIT(s)
  46. }
  47. Str::Str(std::pair<char *, int> detached): size(detached.second), is_ascii(true) {
  48. this->data = detached.first;
  49. for(int i=0; i<size; i++){
  50. if(!isascii(data[i])){ is_ascii = false; break; }
  51. }
  52. PK_ASSERT(data[size] == '\0');
  53. }
  54. Str::Str(const Str& other): size(other.size), is_ascii(other.is_ascii) {
  55. PK_STR_ALLOCATE()
  56. memcpy(data, other.data, size);
  57. data[size] = '\0';
  58. }
  59. Str::Str(Str&& other): size(other.size), is_ascii(other.is_ascii) {
  60. if(other.is_inlined()){
  61. data = _inlined;
  62. for(int i=0; i<size; i++) _inlined[i] = other._inlined[i];
  63. data[size] = '\0';
  64. }else{
  65. data = other.data;
  66. // zero out `other`
  67. other.data = other._inlined;
  68. other.data[0] = '\0';
  69. other.size = 0;
  70. }
  71. }
  72. Str operator+(const char* p, const Str& str){
  73. Str other(p);
  74. return other + str;
  75. }
  76. std::ostream& operator<<(std::ostream& os, const Str& str){
  77. return os << str.sv();
  78. }
  79. bool operator<(const std::string_view other, const Str& str){
  80. return other < str.sv();
  81. }
  82. Str& Str::operator=(const Str& other){
  83. if(!is_inlined()) pool64_dealloc(data);
  84. size = other.size;
  85. is_ascii = other.is_ascii;
  86. PK_STR_ALLOCATE()
  87. memcpy(data, other.data, size);
  88. data[size] = '\0';
  89. return *this;
  90. }
  91. Str Str::operator+(const Str& other) const {
  92. Str ret(size + other.size, is_ascii && other.is_ascii);
  93. memcpy(ret.data, data, size);
  94. memcpy(ret.data + size, other.data, other.size);
  95. ret.data[ret.size] = '\0';
  96. return ret;
  97. }
  98. Str Str::operator+(const char* p) const {
  99. Str other(p);
  100. return *this + other;
  101. }
  102. bool Str::operator==(const Str& other) const {
  103. if(size != other.size) return false;
  104. return memcmp(data, other.data, size) == 0;
  105. }
  106. bool Str::operator!=(const Str& other) const {
  107. if(size != other.size) return true;
  108. return memcmp(data, other.data, size) != 0;
  109. }
  110. bool Str::operator==(const std::string_view other) const {
  111. if(size != (int)other.size()) return false;
  112. return memcmp(data, other.data(), size) == 0;
  113. }
  114. bool Str::operator!=(const std::string_view other) const {
  115. if(size != (int)other.size()) return true;
  116. return memcmp(data, other.data(), size) != 0;
  117. }
  118. bool Str::operator==(const char* p) const {
  119. return *this == std::string_view(p);
  120. }
  121. bool Str::operator!=(const char* p) const {
  122. return *this != std::string_view(p);
  123. }
  124. bool Str::operator<(const Str& other) const {
  125. return this->sv() < other.sv();
  126. }
  127. bool Str::operator<(const std::string_view other) const {
  128. return this->sv() < other;
  129. }
  130. bool Str::operator>(const Str& other) const {
  131. return this->sv() > other.sv();
  132. }
  133. bool Str::operator<=(const Str& other) const {
  134. return this->sv() <= other.sv();
  135. }
  136. bool Str::operator>=(const Str& other) const {
  137. return this->sv() >= other.sv();
  138. }
  139. Str::~Str(){
  140. if(!is_inlined()) pool64_dealloc(data);
  141. }
  142. Str Str::substr(int start, int len) const {
  143. Str ret(len, is_ascii);
  144. memcpy(ret.data, data + start, len);
  145. ret.data[len] = '\0';
  146. return ret;
  147. }
  148. Str Str::substr(int start) const {
  149. return substr(start, size - start);
  150. }
  151. Str Str::strip(bool left, bool right, const Str& chars) const {
  152. int L = 0;
  153. int R = u8_length();
  154. if(left){
  155. while(L < R && chars.index(u8_getitem(L)) != -1) L++;
  156. }
  157. if(right){
  158. while(L < R && chars.index(u8_getitem(R-1)) != -1) R--;
  159. }
  160. return u8_slice(L, R, 1);
  161. }
  162. Str Str::strip(bool left, bool right) const {
  163. if(is_ascii){
  164. int L = 0;
  165. int R = size;
  166. if(left){
  167. while(L < R && (data[L] == ' ' || data[L] == '\t' || data[L] == '\n' || data[L] == '\r')) L++;
  168. }
  169. if(right){
  170. while(L < R && (data[R-1] == ' ' || data[R-1] == '\t' || data[R-1] == '\n' || data[R-1] == '\r')) R--;
  171. }
  172. return substr(L, R - L);
  173. }else{
  174. return strip(left, right, " \t\n\r");
  175. }
  176. }
  177. Str Str::lower() const{
  178. std::string copy(data, size);
  179. std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c){
  180. if('A' <= c && c <= 'Z') return c + ('a' - 'A');
  181. return (int)c;
  182. });
  183. return Str(copy);
  184. }
  185. Str Str::upper() const{
  186. std::string copy(data, size);
  187. std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c){
  188. if('a' <= c && c <= 'z') return c - ('a' - 'A');
  189. return (int)c;
  190. });
  191. return Str(copy);
  192. }
  193. Str Str::escape(bool single_quote) const{
  194. SStream ss;
  195. escape_(ss, single_quote);
  196. return ss.str();
  197. }
  198. void Str::escape_(SStream& ss, bool single_quote) const {
  199. ss << (single_quote ? '\'' : '"');
  200. for (int i=0; i<length(); i++) {
  201. char c = this->operator[](i);
  202. switch (c) {
  203. case '"':
  204. if(!single_quote) ss << '\\';
  205. ss << '"';
  206. break;
  207. case '\'':
  208. if(single_quote) ss << '\\';
  209. ss << '\'';
  210. break;
  211. case '\\': ss << '\\' << '\\'; break;
  212. case '\n': ss << "\\n"; break;
  213. case '\r': ss << "\\r"; break;
  214. case '\t': ss << "\\t"; break;
  215. case '\b': ss << "\\b"; break;
  216. default:
  217. if ('\x00' <= c && c <= '\x1f') {
  218. ss << "\\x"; // << std::hex << std::setw(2) << std::setfill('0') << (int)c;
  219. ss << PK_HEX_TABLE[c >> 4];
  220. ss << PK_HEX_TABLE[c & 0xf];
  221. } else {
  222. ss << c;
  223. }
  224. }
  225. }
  226. ss << (single_quote ? '\'' : '"');
  227. }
  228. int Str::index(const Str& sub, int start) const {
  229. auto p = std::search(data + start, data + size, sub.data, sub.data + sub.size);
  230. if(p == data + size) return -1;
  231. return p - data;
  232. }
  233. Str Str::replace(char old, char new_) const{
  234. Str copied = *this;
  235. for(int i=0; i<copied.size; i++){
  236. if(copied.data[i] == old) copied.data[i] = new_;
  237. }
  238. return copied;
  239. }
  240. Str Str::replace(const Str& old, const Str& new_, int count) const {
  241. SStream ss;
  242. int start = 0;
  243. while(true){
  244. int i = index(old, start);
  245. if(i == -1) break;
  246. ss << substr(start, i - start);
  247. ss << new_;
  248. start = i + old.size;
  249. if(count != -1 && --count == 0) break;
  250. }
  251. ss << substr(start, size - start);
  252. return ss.str();
  253. }
  254. int Str::_unicode_index_to_byte(int i) const{
  255. if(is_ascii) return i;
  256. int j = 0;
  257. while(i > 0){
  258. j += utf8len(data[j]);
  259. i--;
  260. }
  261. return j;
  262. }
  263. int Str::_byte_index_to_unicode(int n) const{
  264. if(is_ascii) return n;
  265. int cnt = 0;
  266. for(int i=0; i<n; i++){
  267. if((data[i] & 0xC0) != 0x80) cnt++;
  268. }
  269. return cnt;
  270. }
  271. Str Str::u8_getitem(int i) const{
  272. i = _unicode_index_to_byte(i);
  273. return substr(i, utf8len(data[i]));
  274. }
  275. Str Str::u8_slice(int start, int stop, int step) const{
  276. SStream ss;
  277. if(is_ascii){
  278. PK_SLICE_LOOP(i, start, stop, step) ss << data[i];
  279. }else{
  280. PK_SLICE_LOOP(i, start, stop, step) ss << u8_getitem(i);
  281. }
  282. return ss.str();
  283. }
  284. int Str::u8_length() const {
  285. return _byte_index_to_unicode(size);
  286. }
  287. pod_vector<std::string_view> Str::split(const Str& sep) const{
  288. pod_vector<std::string_view> result;
  289. std::string_view tmp;
  290. int start = 0;
  291. while(true){
  292. int i = index(sep, start);
  293. if(i == -1) break;
  294. tmp = sv().substr(start, i - start);
  295. if(!tmp.empty()) result.push_back(tmp);
  296. start = i + sep.size;
  297. }
  298. tmp = sv().substr(start, size - start);
  299. if(!tmp.empty()) result.push_back(tmp);
  300. return result;
  301. }
  302. pod_vector<std::string_view> Str::split(char sep) const{
  303. pod_vector<std::string_view> result;
  304. int i = 0;
  305. for(int j = 0; j < size; j++){
  306. if(data[j] == sep){
  307. if(j > i) result.emplace_back(data+i, j-i);
  308. i = j + 1;
  309. continue;
  310. }
  311. }
  312. if(size > i) result.emplace_back(data+i, size-i);
  313. return result;
  314. }
  315. int Str::count(const Str& sub) const{
  316. if(sub.empty()) return size + 1;
  317. int cnt = 0;
  318. int start = 0;
  319. while(true){
  320. int i = index(sub, start);
  321. if(i == -1) break;
  322. cnt++;
  323. start = i + sub.size;
  324. }
  325. return cnt;
  326. }
  327. std::map<std::string, uint16_t, std::less<>>& StrName::_interned(){
  328. static std::map<std::string, uint16_t, std::less<>> interned;
  329. return interned;
  330. }
  331. std::map<uint16_t, std::string>& StrName::_r_interned(){
  332. static std::map<uint16_t, std::string> r_interned;
  333. return r_interned;
  334. }
  335. uint32_t StrName::_pesudo_random_index = 0;
  336. StrName StrName::get(std::string_view s){
  337. auto it = _interned().find(s);
  338. if(it != _interned().end()) return StrName(it->second);
  339. // generate new index
  340. // https://github.com/python/cpython/blob/3.12/Objects/dictobject.c#L175
  341. uint16_t index = ((_pesudo_random_index*5) + 1) & 65535;
  342. if(index == 0) throw std::runtime_error("StrName index overflow");
  343. _interned()[std::string(s)] = index;
  344. if(is_valid(index)) throw std::runtime_error("StrName index conflict");
  345. _r_interned()[index] = std::string(s);
  346. _pesudo_random_index = index;
  347. return StrName(index);
  348. }
  349. bool StrName::is_valid(int index) {
  350. return _r_interned().find(index) != _r_interned().end();
  351. }
  352. Str SStream::str(){
  353. // after this call, the buffer is no longer valid
  354. buffer.reserve(buffer.size() + 1); // allocate one more byte for '\0'
  355. buffer[buffer.size()] = '\0'; // set '\0'
  356. return Str(buffer.detach());
  357. }
  358. SStream& SStream::operator<<(const Str& s){
  359. buffer.extend(s.begin(), s.end());
  360. return *this;
  361. }
  362. SStream& SStream::operator<<(const char* s){
  363. buffer.extend(s, s + strlen(s));
  364. return *this;
  365. }
  366. SStream& SStream::operator<<(const std::string& s){
  367. buffer.extend(s.data(), s.data() + s.size());
  368. return *this;
  369. }
  370. SStream& SStream::operator<<(std::string_view s){
  371. buffer.extend(s.data(), s.data() + s.size());
  372. return *this;
  373. }
  374. SStream& SStream::operator<<(char c){
  375. buffer.push_back(c);
  376. return *this;
  377. }
  378. SStream& SStream::operator<<(StrName sn){
  379. return *this << sn.sv();
  380. }
  381. SStream& SStream::operator<<(size_t val){
  382. // size_t could be out of range of `i64`, use `std::to_string` instead
  383. return (*this) << std::to_string(val);
  384. }
  385. SStream& SStream::operator<<(int val){
  386. return (*this) << static_cast<i64>(val);
  387. }
  388. SStream& SStream::operator<<(i64 val){
  389. // str(-2**64).__len__() == 21
  390. buffer.reserve(buffer.size() + 24);
  391. if(val == 0){
  392. buffer.push_back('0');
  393. return *this;
  394. }
  395. if(val < 0){
  396. buffer.push_back('-');
  397. val = -val;
  398. }
  399. char* begin = buffer.end();
  400. while(val){
  401. buffer.push_back('0' + val % 10);
  402. val /= 10;
  403. }
  404. std::reverse(begin, buffer.end());
  405. return *this;
  406. }
  407. SStream& SStream::operator<<(f64 val){
  408. if(std::isinf(val)){
  409. return (*this) << (val > 0 ? "inf" : "-inf");
  410. }
  411. if(std::isnan(val)){
  412. return (*this) << "nan";
  413. }
  414. char b[32];
  415. if(_precision == -1){
  416. int prec = std::numeric_limits<f64>::max_digits10-1;
  417. snprintf(b, sizeof(b), "%.*g", prec, val);
  418. }else{
  419. int prec = _precision;
  420. snprintf(b, sizeof(b), "%.*f", prec, val);
  421. }
  422. (*this) << b;
  423. if(std::all_of(b+1, b+strlen(b), isdigit)) (*this) << ".0";
  424. return *this;
  425. }
  426. void SStream::write_hex(unsigned char c, bool non_zero){
  427. unsigned char high = c >> 4;
  428. unsigned char low = c & 0xf;
  429. if(non_zero){
  430. if(high) (*this) << PK_HEX_TABLE[high];
  431. if(high || low) (*this) << PK_HEX_TABLE[low];
  432. }else{
  433. (*this) << PK_HEX_TABLE[high];
  434. (*this) << PK_HEX_TABLE[low];
  435. }
  436. }
  437. void SStream::write_hex(void* p){
  438. if(p == nullptr){
  439. (*this) << "0x0";
  440. return;
  441. }
  442. (*this) << "0x";
  443. uintptr_t p_t = reinterpret_cast<uintptr_t>(p);
  444. bool non_zero = true;
  445. for(int i=sizeof(void*)-1; i>=0; i--){
  446. unsigned char cpnt = (p_t >> (i * 8)) & 0xff;
  447. write_hex(cpnt, non_zero);
  448. if(cpnt != 0) non_zero = false;
  449. }
  450. }
  451. void SStream::write_hex(i64 val){
  452. if(val == 0){
  453. (*this) << "0x0";
  454. return;
  455. }
  456. if(val < 0){
  457. (*this) << "-";
  458. val = -val;
  459. }
  460. (*this) << "0x";
  461. bool non_zero = true;
  462. for(int i=56; i>=0; i-=8){
  463. unsigned char cpnt = (val >> i) & 0xff;
  464. write_hex(cpnt, non_zero);
  465. if(cpnt != 0) non_zero = false;
  466. }
  467. }
  468. #undef PK_STR_ALLOCATE
  469. #undef PK_STR_COPY_INIT
  470. // unary operators
  471. const StrName __repr__ = StrName::get("__repr__");
  472. const StrName __str__ = StrName::get("__str__");
  473. const StrName __hash__ = StrName::get("__hash__");
  474. const StrName __len__ = StrName::get("__len__");
  475. const StrName __iter__ = StrName::get("__iter__");
  476. const StrName __next__ = StrName::get("__next__");
  477. const StrName __neg__ = StrName::get("__neg__");
  478. // logical operators
  479. const StrName __eq__ = StrName::get("__eq__");
  480. const StrName __lt__ = StrName::get("__lt__");
  481. const StrName __le__ = StrName::get("__le__");
  482. const StrName __gt__ = StrName::get("__gt__");
  483. const StrName __ge__ = StrName::get("__ge__");
  484. const StrName __contains__ = StrName::get("__contains__");
  485. // binary operators
  486. const StrName __add__ = StrName::get("__add__");
  487. const StrName __radd__ = StrName::get("__radd__");
  488. const StrName __sub__ = StrName::get("__sub__");
  489. const StrName __rsub__ = StrName::get("__rsub__");
  490. const StrName __mul__ = StrName::get("__mul__");
  491. const StrName __rmul__ = StrName::get("__rmul__");
  492. const StrName __truediv__ = StrName::get("__truediv__");
  493. const StrName __floordiv__ = StrName::get("__floordiv__");
  494. const StrName __mod__ = StrName::get("__mod__");
  495. const StrName __pow__ = StrName::get("__pow__");
  496. const StrName __matmul__ = StrName::get("__matmul__");
  497. const StrName __lshift__ = StrName::get("__lshift__");
  498. const StrName __rshift__ = StrName::get("__rshift__");
  499. const StrName __and__ = StrName::get("__and__");
  500. const StrName __or__ = StrName::get("__or__");
  501. const StrName __xor__ = StrName::get("__xor__");
  502. const StrName __invert__ = StrName::get("__invert__");
  503. // indexer
  504. const StrName __getitem__ = StrName::get("__getitem__");
  505. const StrName __setitem__ = StrName::get("__setitem__");
  506. const StrName __delitem__ = StrName::get("__delitem__");
  507. // specials
  508. const StrName __new__ = StrName::get("__new__");
  509. const StrName __init__ = StrName::get("__init__");
  510. const StrName __call__ = StrName::get("__call__");
  511. const StrName __divmod__ = StrName::get("__divmod__");
  512. const StrName __enter__ = StrName::get("__enter__");
  513. const StrName __exit__ = StrName::get("__exit__");
  514. const StrName __name__ = StrName::get("__name__");
  515. const StrName __all__ = StrName::get("__all__");
  516. const StrName __package__ = StrName::get("__package__");
  517. const StrName __path__ = StrName::get("__path__");
  518. const StrName __class__ = StrName::get("__class__");
  519. const StrName __missing__ = StrName::get("__missing__");
  520. const StrName pk_id_add = StrName::get("add");
  521. const StrName pk_id_set = StrName::get("set");
  522. const StrName pk_id_long = StrName::get("long");
  523. const StrName pk_id_complex = StrName::get("complex");
  524. } // namespace pkpy