text.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2019 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include "text.h"
  24. #include <fstream>
  25. #include <streambuf>
  26. #include <cstring>
  27. #include <stdexcept>
  28. using namespace dsr;
  29. static int strlen_utf32(const char32_t *content) {
  30. int length = 0;
  31. while (content[length] != 0) {
  32. length++;
  33. }
  34. return length;
  35. }
  36. static char toAscii(DsrChar c) {
  37. if (c > 127) {
  38. return '?';
  39. } else {
  40. return c;
  41. }
  42. }
  43. String& Printable::toStream(String& target) const {
  44. return this->toStreamIndented(target, U"");
  45. }
  46. String Printable::toStringIndented(const ReadableString& indentation) const {
  47. String result;
  48. this->toStreamIndented(result, indentation);
  49. return result;
  50. }
  51. String Printable::toString() const {
  52. return this->toStringIndented(U"");
  53. }
  54. std::ostream& Printable::toStreamIndented(std::ostream& out, const ReadableString& indentation) const {
  55. String result;
  56. this->toStreamIndented(result, indentation);
  57. for (int i = 0; i < result.length(); i++) {
  58. out.put(toAscii(result.read(i)));
  59. }
  60. return out;
  61. }
  62. std::ostream& Printable::toStream(std::ostream& out) const {
  63. return this->toStreamIndented(out, U"");
  64. }
  65. std::string Printable::toStdString() const {
  66. std::ostringstream result;
  67. this->toStream(result);
  68. return result.str();
  69. }
  70. Printable::~Printable() {}
  71. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  72. if (a.length() != b.length()) {
  73. return false;
  74. } else {
  75. for (int i = 0; i < a.length(); i++) {
  76. if (a.read(i) != b.read(i)) {
  77. return false;
  78. }
  79. }
  80. return true;
  81. }
  82. }
  83. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  84. if (a.length() != b.length()) {
  85. return false;
  86. } else {
  87. for (int i = 0; i < a.length(); i++) {
  88. if (towupper(a.read(i)) != towupper(b.read(i))) {
  89. return false;
  90. }
  91. }
  92. return true;
  93. }
  94. }
  95. std::ostream& ReadableString::toStream(std::ostream& out) const {
  96. for (int i = 0; i < this->length(); i++) {
  97. out.put(toAscii(this->read(i)));
  98. }
  99. return out;
  100. }
  101. std::string ReadableString::toStdString() const {
  102. std::ostringstream result;
  103. this->toStream(result);
  104. return result.str();
  105. }
  106. String dsr::string_upperCase(const ReadableString &text) {
  107. String result;
  108. result.reserve(text.length());
  109. for (int i = 0; i < text.length(); i++) {
  110. result.appendChar(towupper(text[i]));
  111. }
  112. return result;
  113. }
  114. String dsr::string_lowerCase(const ReadableString &text) {
  115. String result;
  116. result.reserve(text.length());
  117. for (int i = 0; i < text.length(); i++) {
  118. result.appendChar(towlower(text[i]));
  119. }
  120. return result;
  121. }
  122. String dsr::string_removeAllWhiteSpace(const ReadableString &text) {
  123. String result;
  124. result.reserve(text.length());
  125. for (int i = 0; i < text.length(); i++) {
  126. DsrChar c = text[i];
  127. if (!character_isWhiteSpace(c)) {
  128. result.appendChar(c);
  129. }
  130. }
  131. return result;
  132. }
  133. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  134. int first = -1;
  135. int last = -1;
  136. for (int i = 0; i < text.length(); i++) {
  137. DsrChar c = text[i];
  138. if (!character_isWhiteSpace(c)) {
  139. first = i;
  140. break;
  141. }
  142. }
  143. for (int i = text.length() - 1; i >= 0; i--) {
  144. DsrChar c = text[i];
  145. if (!character_isWhiteSpace(c)) {
  146. last = i;
  147. break;
  148. }
  149. }
  150. if (first == -1) {
  151. // Only white space
  152. return ReadableString();
  153. } else {
  154. // Subset
  155. return string_inclusiveRange(text, first, last);
  156. }
  157. }
  158. String dsr::string_mangleQuote(const ReadableString &rawText) {
  159. String result;
  160. result.reserve(rawText.length() + 2);
  161. result.appendChar(U'\"'); // Begin quote
  162. for (int i = 0; i < rawText.length(); i++) {
  163. DsrChar c = rawText[i];
  164. if (c == U'\"') { // Double quote
  165. result.append(U"\\\"");
  166. } else if (c == U'\\') { // Backslash
  167. result.append(U"\\\\");
  168. } else if (c == U'\a') { // Audible bell
  169. result.append(U"\\a");
  170. } else if (c == U'\b') { // Backspace
  171. result.append(U"\\b");
  172. } else if (c == U'\f') { // Form feed
  173. result.append(U"\\f");
  174. } else if (c == U'\n') { // Line feed
  175. result.append(U"\\n");
  176. } else if (c == U'\r') { // Carriage return
  177. result.append(U"\\r");
  178. } else if (c == U'\t') { // Horizontal tab
  179. result.append(U"\\t");
  180. } else if (c == U'\v') { // Vertical tab
  181. result.append(U"\\v");
  182. } else if (c == U'\0') { // Null terminator
  183. result.append(U"\\0");
  184. } else {
  185. result.appendChar(c);
  186. }
  187. }
  188. result.appendChar(U'\"'); // End quote
  189. return result;
  190. }
  191. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  192. int firstQuote = string_findFirst(mangledText, '\"');
  193. int lastQuote = string_findLast(mangledText, '\"');
  194. String result;
  195. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  196. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, "\n");
  197. } else {
  198. for (int i = firstQuote + 1; i < lastQuote; i++) {
  199. DsrChar c = mangledText[i];
  200. if (c == U'\\') { // Escape character
  201. DsrChar c2 = mangledText[i + 1];
  202. if (c2 == U'\"') { // Double quote
  203. result.appendChar(U'\"');
  204. } else if (c2 == U'\\') { // Back slash
  205. result.appendChar(U'\\');
  206. } else if (c2 == U'a') { // Audible bell
  207. result.appendChar(U'\a');
  208. } else if (c2 == U'b') { // Backspace
  209. result.appendChar(U'\b');
  210. } else if (c2 == U'f') { // Form feed
  211. result.appendChar(U'\f');
  212. } else if (c2 == U'n') { // Line feed
  213. result.appendChar(U'\n');
  214. } else if (c2 == U'r') { // Carriage return
  215. result.appendChar(U'\r');
  216. } else if (c2 == U't') { // Horizontal tab
  217. result.appendChar(U'\t');
  218. } else if (c2 == U'v') { // Vertical tab
  219. result.appendChar(U'\v');
  220. } else if (c2 == U'0') { // Null terminator
  221. result.appendChar(U'\0');
  222. }
  223. i++; // Consume both characters
  224. } else {
  225. // Detect bad input
  226. if (c == U'\"') { // Double quote
  227. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, "\n");
  228. } else if (c == U'\\') { // Back slash
  229. throwError(U"Unmangled back slash detected in string_unmangleQuote!\n", mangledText, "\n");
  230. } else if (c == U'\a') { // Audible bell
  231. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  232. } else if (c == U'\b') { // Backspace
  233. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  234. } else if (c == U'\f') { // Form feed
  235. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  236. } else if (c == U'\n') { // Line feed
  237. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  238. } else if (c == U'\r') { // Carriage return
  239. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  240. } else if (c == U'\0') { // Null terminator
  241. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  242. } else {
  243. result.appendChar(c);
  244. }
  245. }
  246. }
  247. }
  248. return result;
  249. }
  250. static void uintToString_arabic(String& target, uint64_t value) {
  251. static const int bufferSize = 20;
  252. DsrChar digits[bufferSize];
  253. int usedSize = 0;
  254. if (value == 0) {
  255. target.appendChar(U'0');
  256. } else {
  257. while (usedSize < bufferSize) {
  258. DsrChar digit = U'0' + (value % 10u);
  259. digits[usedSize] = digit;
  260. usedSize++;
  261. value /= 10u;
  262. if (value == 0) {
  263. break;
  264. }
  265. }
  266. while (usedSize > 0) {
  267. usedSize--;
  268. target.appendChar(digits[usedSize]);
  269. }
  270. }
  271. }
  272. static void intToString_arabic(String& target, int64_t value) {
  273. if (value >= 0) {
  274. uintToString_arabic(target, (uint64_t)value);
  275. } else {
  276. target.appendChar(U'-');
  277. uintToString_arabic(target, (uint64_t)(-value));
  278. }
  279. }
  280. // TODO: Implement own version to ensure that nothing strange is happening from buggy std implementations
  281. static void doubleToString_arabic(String& target, double value) {
  282. std::ostringstream buffer;
  283. buffer << std::fixed << value; // Generate using a fixed number of decimals
  284. std::string result = buffer.str();
  285. // Remove trailing zero decimal digits
  286. int decimalCount = 0;
  287. int lastValueIndex = -1;
  288. for (int c = 0; c < (int)result.length(); c++) {
  289. if (result[c] == '.') {
  290. decimalCount++;
  291. } else if (result[c] == ',') {
  292. result[c] = '.'; // Convert nationalized french decimal serialization into international decimals
  293. decimalCount++;
  294. } else if (decimalCount > 0 && result[c] >= '1' && result[c] <= '9') {
  295. lastValueIndex = c;
  296. } else if (decimalCount == 0 && result[c] >= '0' && result[c] <= '9') {
  297. lastValueIndex = c;
  298. }
  299. }
  300. for (int c = 0; c <= lastValueIndex; c++) {
  301. target.appendChar(result[c]);
  302. }
  303. }
  304. #define TO_RAW_ASCII(TARGET, SOURCE) \
  305. char TARGET[SOURCE.length() + 1]; \
  306. for (int i = 0; i < SOURCE.length(); i++) { \
  307. TARGET[i] = toAscii(SOURCE[i]); \
  308. } \
  309. TARGET[SOURCE.length()] = '\0';
  310. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  311. // TODO: Load files using Unicode filenames
  312. TO_RAW_ASCII(asciiFilename, filename);
  313. std::ifstream inputFile(asciiFilename);
  314. if (inputFile.is_open()) {
  315. std::stringstream outputBuffer;
  316. // TODO: Feed directly to String
  317. outputBuffer << inputFile.rdbuf();
  318. std::string content = outputBuffer.str();
  319. String result;
  320. result.reserve(content.size());
  321. for (int i = 0; i < (int)(content.size()); i++) {
  322. result.appendChar(content[i]);
  323. }
  324. inputFile.close();
  325. return result;
  326. } else {
  327. if (mustExist) {
  328. throwError("Failed to load ", filename, "\n");
  329. }
  330. // If the file cound not be found and opened, a null string is returned
  331. return String();
  332. }
  333. }
  334. void dsr::string_save(const ReadableString& filename, const ReadableString& content) {
  335. // TODO: Load files using Unicode filenames
  336. TO_RAW_ASCII(asciiFilename, filename);
  337. TO_RAW_ASCII(asciiContent, content);
  338. std::ofstream outputFile;
  339. outputFile.open(asciiFilename);
  340. if (outputFile.is_open()) {
  341. outputFile << asciiContent;
  342. outputFile.close();
  343. } else {
  344. throwError("Failed to save ", filename, "\n");
  345. }
  346. }
  347. const char32_t* dsr::file_separator() {
  348. #ifdef _WIN32
  349. return U"\\";
  350. #else
  351. return U"/";
  352. #endif
  353. }
  354. int ReadableString::length() const {
  355. return this->sectionLength;
  356. }
  357. bool ReadableString::checkBound(int start, int length, bool warning) const {
  358. if (start < 0 || start + length > this->length()) {
  359. if (warning) {
  360. String message;
  361. string_append(message, U"\n");
  362. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  363. string_append(message, U"/\n");
  364. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  365. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  366. string_append(message, U"\\_______________________________________________________________________\n");
  367. throwError(message);
  368. }
  369. return false;
  370. } else {
  371. return true;
  372. }
  373. }
  374. DsrChar ReadableString::read(int index) const {
  375. if (index < 0 || index >= this->sectionLength) {
  376. return '\0';
  377. } else {
  378. return this->readSection[index];
  379. }
  380. }
  381. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  382. ReadableString::ReadableString() {}
  383. ReadableString::~ReadableString() {}
  384. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  385. : readSection(content), sectionLength(sectionLength) {}
  386. ReadableString::ReadableString(const DsrChar *content)
  387. : readSection(content), sectionLength(strlen_utf32(content)) {}
  388. String::String() {}
  389. String::String(const char* source) { this->append(source); }
  390. String::String(const char32_t* source) { this->append(source); }
  391. String::String(const std::string& source) { this->append(source); }
  392. String::String(const ReadableString& source) { this->append(source); }
  393. String::String(const String& source) { this->append(source); }
  394. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  395. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  396. int String::capacity() {
  397. if (this->buffer.get() == nullptr) {
  398. return 0;
  399. } else {
  400. // Get the parent allocation
  401. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  402. // Get the offset from the parent
  403. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  404. // Subtract offset from the buffer size to get the remaining space
  405. return (this->buffer->size - offset) / sizeof(DsrChar);
  406. }
  407. }
  408. ReadableString ReadableString::getRange(int start, int length) const {
  409. if (length < 1) {
  410. return ReadableString();
  411. } else if (this->checkBound(start, length)) {
  412. return ReadableString(&(this->readSection[start]), length);
  413. } else {
  414. return ReadableString();
  415. }
  416. }
  417. ReadableString String::getRange(int start, int length) const {
  418. if (length < 1) {
  419. return ReadableString();
  420. } else if (this->checkBound(start, length)) {
  421. return String(this->buffer, &(this->writeSection[start]), length);
  422. } else {
  423. return ReadableString();
  424. }
  425. }
  426. static int32_t getNewBufferSize(int32_t minimumSize) {
  427. if (minimumSize <= 128) {
  428. return 128;
  429. } else if (minimumSize <= 512) {
  430. return 512;
  431. } else if (minimumSize <= 2048) {
  432. return 2048;
  433. } else if (minimumSize <= 8192) {
  434. return 8192;
  435. } else if (minimumSize <= 32768) {
  436. return 32768;
  437. } else if (minimumSize <= 131072) {
  438. return 131072;
  439. } else if (minimumSize <= 524288) {
  440. return 524288;
  441. } else if (minimumSize <= 2097152) {
  442. return 2097152;
  443. } else if (minimumSize <= 8388608) {
  444. return 8388608;
  445. } else if (minimumSize <= 33554432) {
  446. return 33554432;
  447. } else if (minimumSize <= 134217728) {
  448. return 134217728;
  449. } else if (minimumSize <= 536870912) {
  450. return 536870912;
  451. } else {
  452. return 2147483647;
  453. }
  454. }
  455. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  456. // Holding oldData alive while copying to the new buffer
  457. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  458. const char32_t* oldData = this->readSection;
  459. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  460. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  461. if (preserve && oldData) {
  462. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  463. }
  464. }
  465. // Call before writing to the buffer
  466. // This hides that Strings share buffers when assigning by value or taking partial strings
  467. void String::cloneIfShared() {
  468. if (this->buffer.use_count() > 1) {
  469. this->reallocateBuffer(this->sectionLength, true);
  470. }
  471. }
  472. void String::expand(int32_t newLength, bool affectUsedLength) {
  473. if (newLength > this->sectionLength) {
  474. if (newLength > this->capacity()) {
  475. this->reallocateBuffer(newLength, true);
  476. }
  477. }
  478. if (affectUsedLength) {
  479. this->sectionLength = newLength;
  480. }
  481. }
  482. void String::reserve(int32_t minimumLength) {
  483. this->expand(minimumLength, false);
  484. }
  485. void String::write(int index, DsrChar value) {
  486. this->cloneIfShared();
  487. if (index < 0 || index >= this->sectionLength) {
  488. // TODO: Give a warning
  489. } else {
  490. this->writeSection[index] = value;
  491. }
  492. }
  493. void String::clear() {
  494. this->sectionLength = 0;
  495. }
  496. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  497. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  498. // Proof that appending to one string doesn't affect another:
  499. // If it has to reallocate
  500. // * Then it will have its own buffer without conflicts
  501. // If it doesn't have to reallocate
  502. // If it shares the buffer
  503. // If source is empty
  504. // * Then no risk of overwriting neighbor strings if we don't write
  505. // If source isn't empty
  506. // * Then the buffer will be cloned when the first character is written
  507. // If it doesn't share the buffer
  508. // * Then no risk of writing
  509. #define APPEND(TARGET, SOURCE, LENGTH) { \
  510. int oldLength = (TARGET)->length(); \
  511. (TARGET)->expand(oldLength + (int)(LENGTH), true); \
  512. for (int i = 0; i < (int)(LENGTH); i++) { \
  513. (TARGET)->write(oldLength + i, (SOURCE)[i]); \
  514. } \
  515. }
  516. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  517. void String::append(const char* source) { APPEND(this, source, strlen(source)); }
  518. // TODO: Use memcpy when appending input of the same format
  519. void String::append(const ReadableString& source) { APPEND(this, source, source.length()); }
  520. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source)); }
  521. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size()); }
  522. void String::appendChar(DsrChar source) { APPEND(this, &source, 1); }
  523. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  524. return source.toStreamIndented(target, indentation);
  525. }
  526. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  527. target.append(indentation);
  528. target.append(value);
  529. return target;
  530. }
  531. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  532. target.append(indentation);
  533. target.append(value);
  534. return target;
  535. }
  536. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  537. target.append(indentation);
  538. target.append(value);
  539. return target;
  540. }
  541. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  542. target.append(indentation);
  543. target.append(value);
  544. return target;
  545. }
  546. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  547. target.append(indentation);
  548. doubleToString_arabic(target, (double)value);
  549. return target;
  550. }
  551. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  552. target.append(indentation);
  553. doubleToString_arabic(target, value);
  554. return target;
  555. }
  556. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  557. target.append(indentation);
  558. intToString_arabic(target, value);
  559. return target;
  560. }
  561. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  562. target.append(indentation);
  563. uintToString_arabic(target, value);
  564. return target;
  565. }
  566. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  567. target.append(indentation);
  568. intToString_arabic(target, (int64_t)value);
  569. return target;
  570. }
  571. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  572. target.append(indentation);
  573. uintToString_arabic(target, (uint64_t)value);
  574. return target;
  575. }
  576. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  577. target.append(indentation);
  578. intToString_arabic(target, (int64_t)value);
  579. return target;
  580. }
  581. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  582. target.append(indentation);
  583. uintToString_arabic(target, (uint64_t)value);
  584. return target;
  585. }
  586. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  587. target.append(indentation);
  588. intToString_arabic(target, (int64_t)value);
  589. return target;
  590. }
  591. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  592. target.append(indentation);
  593. uintToString_arabic(target, (uint64_t)value);
  594. return target;
  595. }
  596. void dsr::throwErrorMessage(const String& message) {
  597. throw std::runtime_error(message.toStdString());
  598. }
  599. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  600. if (!appendResult) {
  601. target.clear();
  602. }
  603. int sectionStart = 0;
  604. for (int i = 0; i < source.length(); i++) {
  605. DsrChar c = source[i];
  606. if (c == separator) {
  607. target.push(string_exclusiveRange(source, sectionStart, i));
  608. sectionStart = i + 1;
  609. }
  610. }
  611. if (source.length() > sectionStart) {
  612. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  613. }
  614. }
  615. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  616. List<ReadableString> result;
  617. string_split_inPlace(result, source, separator);
  618. return result;
  619. }
  620. int64_t dsr::string_toInteger(const ReadableString& source) {
  621. int64_t result;
  622. bool negated;
  623. result = 0;
  624. negated = false;
  625. for (int i = 0; i < source.length(); i++) {
  626. DsrChar c = source[i];
  627. if (c == '-' || c == '~') {
  628. negated = !negated;
  629. } else if (c >= '0' && c <= '9') {
  630. result = (result * 10) + (int)(c - '0');
  631. } else if (c == ',' || c == '.') {
  632. // Truncate any decimals by ignoring them
  633. break;
  634. }
  635. }
  636. if (negated) {
  637. return -result;
  638. } else {
  639. return result;
  640. }
  641. }
  642. double dsr::string_toDouble(const ReadableString& source) {
  643. double result;
  644. bool negated;
  645. bool reachedDecimal;
  646. int digitDivider;
  647. result = 0.0;
  648. negated = false;
  649. reachedDecimal = false;
  650. digitDivider = 1;
  651. for (int i = 0; i < source.length(); i++) {
  652. DsrChar c = source[i];
  653. if (c == '-' || c == '~') {
  654. negated = !negated;
  655. } else if (c >= '0' && c <= '9') {
  656. if (reachedDecimal) {
  657. digitDivider = digitDivider * 10;
  658. result = result + ((double)(c - '0') / (double)digitDivider);
  659. } else {
  660. result = (result * 10) + (double)(c - '0');
  661. }
  662. } else if (c == ',' || c == '.') {
  663. reachedDecimal = true;
  664. }
  665. }
  666. if (negated) {
  667. return -result;
  668. } else {
  669. return result;
  670. }
  671. }
  672. int dsr::string_length(const ReadableString& source) {
  673. return source.length();
  674. }
  675. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  676. for (int i = startIndex; i < source.length(); i++) {
  677. if (source[i] == toFind) {
  678. return i;
  679. }
  680. }
  681. return -1;
  682. }
  683. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  684. for (int i = source.length() - 1; i >= 0; i--) {
  685. if (source[i] == toFind) {
  686. return i;
  687. }
  688. }
  689. return -1;
  690. }
  691. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  692. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  693. }
  694. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  695. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  696. }
  697. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  698. return string_exclusiveRange(source, 0, exclusiveEnd);
  699. }
  700. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  701. return string_inclusiveRange(source, 0, inclusiveEnd);
  702. }
  703. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  704. return string_exclusiveRange(source, inclusiveStart, source.length());
  705. }
  706. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  707. return string_from(source, exclusiveStart + 1);
  708. }
  709. bool dsr::character_isDigit(DsrChar c) {
  710. return c >= U'0' && c <= U'9';
  711. }
  712. bool dsr::character_isIntegerCharacter(DsrChar c) {
  713. return c == U'-' || character_isDigit(c);
  714. }
  715. bool dsr::character_isValueCharacter(DsrChar c) {
  716. return c == U'.' || character_isIntegerCharacter(c);
  717. }
  718. bool dsr::character_isWhiteSpace(DsrChar c) {
  719. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  720. }
  721. // Macros for implementing regular expressions with a greedy approach consuming the first match
  722. // Optional accepts 0 or 1 occurence
  723. // Forced accepts 1 occurence
  724. // Star accepts 0..N occurence
  725. // Plus accepts 1..N occurence
  726. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  727. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  728. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  729. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  730. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  731. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  732. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  733. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  734. // The greedy approach works here, because there's no ambiguity
  735. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  736. int readIndex = 0;
  737. if (allowWhiteSpace) {
  738. PATTERN_STAR(WhiteSpace);
  739. }
  740. CHARACTER_OPTIONAL(U'-');
  741. // At least one digit required
  742. PATTERN_PLUS(IntegerCharacter);
  743. if (allowWhiteSpace) {
  744. PATTERN_STAR(WhiteSpace);
  745. }
  746. return true;
  747. }
  748. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  749. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  750. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  751. if (string_findFirst(source, U'.') == -1) {
  752. // No decimal detected
  753. return string_isInteger(source, allowWhiteSpace);
  754. } else {
  755. int readIndex = 0;
  756. if (allowWhiteSpace) {
  757. PATTERN_STAR(WhiteSpace);
  758. }
  759. // Double <- UnsignedDouble | '-' UnsignedDouble
  760. CHARACTER_OPTIONAL(U'-');
  761. // UnsignedDouble <- Digit* '.' Digit+
  762. // Any number of integer digits
  763. PATTERN_STAR(IntegerCharacter);
  764. // Only dot for decimal
  765. CHARACTER_FORCED(U'.')
  766. // At least one decimal digit
  767. PATTERN_PLUS(IntegerCharacter);
  768. if (allowWhiteSpace) {
  769. PATTERN_STAR(WhiteSpace);
  770. }
  771. return true;
  772. }
  773. }