text.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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_utf16(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. static bool isWhiteSpace(DsrChar c) {
  44. return c <= U' ' || c == U'\t' || c == U'\r';
  45. }
  46. int ReadableString::findFirst(DsrChar toFind, int startIndex) const {
  47. for (int i = startIndex; i < this->length(); i++) {
  48. if (this->readSection[i] == toFind) {
  49. return i;
  50. }
  51. }
  52. return -1;
  53. }
  54. int ReadableString::findLast(DsrChar toFind) const {
  55. for (int i = this->length() - 1; i >= 0; i--) {
  56. if (this->readSection[i] == toFind) {
  57. return i;
  58. }
  59. }
  60. return -1;
  61. }
  62. ReadableString ReadableString::exclusiveRange(int inclusiveStart, int exclusiveEnd) const {
  63. return this->getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  64. }
  65. ReadableString ReadableString::inclusiveRange(int inclusiveStart, int inclusiveEnd) const {
  66. return this->getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  67. }
  68. ReadableString ReadableString::before(int exclusiveEnd) const {
  69. return this->exclusiveRange(0, exclusiveEnd);
  70. }
  71. ReadableString ReadableString::until(int inclusiveEnd) const {
  72. return this->inclusiveRange(0, inclusiveEnd);
  73. }
  74. ReadableString ReadableString::from(int inclusiveStart) const {
  75. return this->exclusiveRange(inclusiveStart, this->length());
  76. }
  77. ReadableString ReadableString::after(int exclusiveStart) const {
  78. return this->from(exclusiveStart + 1);
  79. }
  80. List<ReadableString> ReadableString::split(DsrChar separator) const {
  81. List<ReadableString> result;
  82. int lineStart = 0;
  83. for (int i = 0; i < this->length(); i++) {
  84. DsrChar c = this->readSection[i];
  85. if (c == separator) {
  86. result.push(this->exclusiveRange(lineStart, i));
  87. lineStart = i + 1;
  88. }
  89. }
  90. if (this->length() > lineStart) {
  91. result.push(this->exclusiveRange(lineStart, this->length()));;
  92. }
  93. return result;
  94. }
  95. int64_t ReadableString::toInteger() const {
  96. int64_t result;
  97. bool negated;
  98. result = 0;
  99. negated = false;
  100. for (int i = 0; i < this->length(); i++) {
  101. DsrChar c = this->readSection[i];
  102. if (c == '-' || c == '~') {
  103. negated = !negated;
  104. } else if (c >= '0' && c <= '9') {
  105. result = (result * 10) + (int)(c - '0');
  106. } else if (c == ',' || c == '.') {
  107. // Truncate any decimals by ignoring them
  108. break;
  109. }
  110. }
  111. if (negated) {
  112. return -result;
  113. } else {
  114. return result;
  115. }
  116. }
  117. double ReadableString::toDouble() const {
  118. double result;
  119. bool negated;
  120. bool reachedDecimal;
  121. int digitDivider;
  122. result = 0.0;
  123. negated = false;
  124. reachedDecimal = false;
  125. digitDivider = 1;
  126. for (int i = 0; i < this->length(); i++) {
  127. DsrChar c = this->readSection[i];
  128. if (c == '-' || c == '~') {
  129. negated = !negated;
  130. } else if (c >= '0' && c <= '9') {
  131. if (reachedDecimal) {
  132. digitDivider = digitDivider * 10;
  133. result = result + ((double)(c - '0') / (double)digitDivider);
  134. } else {
  135. result = (result * 10) + (double)(c - '0');
  136. }
  137. } else if (c == ',' || c == '.') {
  138. reachedDecimal = true;
  139. }
  140. }
  141. if (negated) {
  142. return -result;
  143. } else {
  144. return result;
  145. }
  146. }
  147. String& Printable::toStream(String& target) const {
  148. return this->toStreamIndented(target, U"");
  149. }
  150. String Printable::toStringIndented(const ReadableString& indentation) const {
  151. String result;
  152. this->toStreamIndented(result, indentation);
  153. return result;
  154. }
  155. String Printable::toString() const {
  156. return this->toStringIndented(U"");
  157. }
  158. std::ostream& Printable::toStreamIndented(std::ostream& out, const ReadableString& indentation) const {
  159. String result;
  160. this->toStreamIndented(result, indentation);
  161. for (int i = 0; i < result.length(); i++) {
  162. out.put(toAscii(result.read(i)));
  163. }
  164. return out;
  165. }
  166. std::ostream& Printable::toStream(std::ostream& out) const {
  167. return this->toStreamIndented(out, U"");
  168. }
  169. std::string Printable::toStdString() const {
  170. std::ostringstream result;
  171. this->toStream(result);
  172. return result.str();
  173. }
  174. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  175. if (a.length() != b.length()) {
  176. return false;
  177. } else {
  178. for (int i = 0; i < a.length(); i++) {
  179. if (a.read(i) != b.read(i)) {
  180. return false;
  181. }
  182. }
  183. return true;
  184. }
  185. }
  186. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  187. if (a.length() != b.length()) {
  188. return false;
  189. } else {
  190. for (int i = 0; i < a.length(); i++) {
  191. if (towupper(a.read(i)) != towupper(b.read(i))) {
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. }
  198. std::ostream& ReadableString::toStream(std::ostream& out) const {
  199. for (int i = 0; i < this->length(); i++) {
  200. out.put(toAscii(this->read(i)));
  201. }
  202. return out;
  203. }
  204. std::string ReadableString::toStdString() const {
  205. std::ostringstream result;
  206. this->toStream(result);
  207. return result.str();
  208. }
  209. String dsr::string_upperCase(const ReadableString &text) {
  210. String result;
  211. result.reserve(text.length());
  212. for (int i = 0; i < text.length(); i++) {
  213. result.appendChar(towupper(text[i]));
  214. }
  215. return result;
  216. }
  217. String dsr::string_lowerCase(const ReadableString &text) {
  218. String result;
  219. result.reserve(text.length());
  220. for (int i = 0; i < text.length(); i++) {
  221. result.appendChar(towlower(text[i]));
  222. }
  223. return result;
  224. }
  225. String dsr::string_removeAllWhiteSpace(const ReadableString &text) {
  226. String result;
  227. result.reserve(text.length());
  228. for (int i = 0; i < text.length(); i++) {
  229. DsrChar c = text[i];
  230. if (!isWhiteSpace(c)) {
  231. result.appendChar(c);
  232. }
  233. }
  234. return result;
  235. }
  236. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  237. int first = -1;
  238. int last = -1;
  239. for (int i = 0; i < text.length(); i++) {
  240. DsrChar c = text[i];
  241. if (!isWhiteSpace(c)) {
  242. first = i;
  243. break;
  244. }
  245. }
  246. for (int i = text.length() - 1; i >= 0; i--) {
  247. DsrChar c = text[i];
  248. if (!isWhiteSpace(c)) {
  249. last = i;
  250. break;
  251. }
  252. }
  253. if (first == -1) {
  254. // Only white space
  255. return ReadableString();
  256. } else {
  257. // Subset
  258. return text.inclusiveRange(first, last);
  259. }
  260. }
  261. int64_t dsr::string_parseInteger(const ReadableString& content) {
  262. return content.toInteger();
  263. }
  264. double dsr::string_parseDouble(const ReadableString& content) {
  265. return content.toDouble();
  266. }
  267. String dsr::string_mangleQuote(const ReadableString &rawText) {
  268. String result;
  269. result.reserve(rawText.length() + 2);
  270. result.appendChar(U'\"'); // Begin quote
  271. for (int i = 0; i < rawText.length(); i++) {
  272. DsrChar c = rawText[i];
  273. if (c == U'\"') { // Double quote
  274. result.append(U"\\\"");
  275. } else if (c == U'\\') { // Backslash
  276. result.append(U"\\\\");
  277. } else if (c == U'\a') { // Audible bell
  278. result.append(U"\\a");
  279. } else if (c == U'\b') { // Backspace
  280. result.append(U"\\b");
  281. } else if (c == U'\f') { // Form feed
  282. result.append(U"\\f");
  283. } else if (c == U'\n') { // Line feed
  284. result.append(U"\\n");
  285. } else if (c == U'\r') { // Carriage return
  286. result.append(U"\\r");
  287. } else if (c == U'\t') { // Horizontal tab
  288. result.append(U"\\t");
  289. } else if (c == U'\v') { // Vertical tab
  290. result.append(U"\\v");
  291. } else if (c == U'\0') { // Null terminator
  292. result.append(U"\\0");
  293. } else {
  294. result.appendChar(c);
  295. }
  296. }
  297. result.appendChar(U'\"'); // End quote
  298. return result;
  299. }
  300. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  301. int firstQuote = mangledText.findFirst('\"');
  302. int lastQuote = mangledText.findLast('\"');
  303. String result;
  304. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  305. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, "\n");
  306. } else {
  307. for (int i = firstQuote + 1; i < lastQuote; i++) {
  308. DsrChar c = mangledText[i];
  309. if (c == U'\\') { // Escape character
  310. DsrChar c2 = mangledText[i + 1];
  311. if (c2 == U'\"') { // Double quote
  312. result.appendChar(U'\"');
  313. } else if (c2 == U'\\') { // Back slash
  314. result.appendChar(U'\\');
  315. } else if (c2 == U'a') { // Audible bell
  316. result.appendChar(U'\a');
  317. } else if (c2 == U'b') { // Backspace
  318. result.appendChar(U'\b');
  319. } else if (c2 == U'f') { // Form feed
  320. result.appendChar(U'\f');
  321. } else if (c2 == U'n') { // Line feed
  322. result.appendChar(U'\n');
  323. } else if (c2 == U'r') { // Carriage return
  324. result.appendChar(U'\r');
  325. } else if (c2 == U't') { // Horizontal tab
  326. result.appendChar(U'\t');
  327. } else if (c2 == U'v') { // Vertical tab
  328. result.appendChar(U'\v');
  329. } else if (c2 == U'0') { // Null terminator
  330. result.appendChar(U'\0');
  331. }
  332. i++; // Consume both characters
  333. } else {
  334. // Detect bad input
  335. if (c == U'\"') { // Double quote
  336. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, "\n");
  337. } else if (c == U'\\') { // Back slash
  338. throwError(U"Unmangled back slash detected in string_unmangleQuote!\n", mangledText, "\n");
  339. } else if (c == U'\a') { // Audible bell
  340. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  341. } else if (c == U'\b') { // Backspace
  342. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  343. } else if (c == U'\f') { // Form feed
  344. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  345. } else if (c == U'\n') { // Line feed
  346. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  347. } else if (c == U'\r') { // Carriage return
  348. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  349. } else if (c == U'\t') { // Horizontal tab
  350. throwError(U"Unmangled horizontal tab detected in string_unmangleQuote!\n", mangledText, "\n");
  351. } else if (c == U'\v') { // Vertical tab
  352. throwError(U"Unmangled vertical tab detected in string_unmangleQuote!\n", mangledText, "\n");
  353. } else if (c == U'\0') { // Null terminator
  354. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  355. } else {
  356. result.appendChar(c);
  357. }
  358. }
  359. }
  360. }
  361. return result;
  362. }
  363. void dsr::uintToString_arabic(String& target, uint64_t value) {
  364. static const int bufferSize = 20;
  365. DsrChar digits[bufferSize];
  366. int usedSize = 0;
  367. if (value == 0) {
  368. target.appendChar(U'0');
  369. } else {
  370. while (usedSize < bufferSize) {
  371. DsrChar digit = U'0' + (value % 10u);
  372. digits[usedSize] = digit;
  373. usedSize++;
  374. value /= 10u;
  375. if (value == 0) {
  376. break;
  377. }
  378. }
  379. while (usedSize > 0) {
  380. usedSize--;
  381. target.appendChar(digits[usedSize]);
  382. }
  383. }
  384. }
  385. void dsr::intToString_arabic(String& target, int64_t value) {
  386. if (value >= 0) {
  387. uintToString_arabic(target, (uint64_t)value);
  388. } else {
  389. target.appendChar(U'-');
  390. uintToString_arabic(target, (uint64_t)(-value));
  391. }
  392. }
  393. // TODO: Implement own version to ensure that nothing strange is happening from buggy std implementations
  394. void dsr::doubleToString_arabic(String& target, double value) {
  395. std::ostringstream buffer;
  396. buffer << std::fixed << value; // Generate using a fixed number of decimals
  397. std::string result = buffer.str();
  398. // Remove trailing zero decimal digits
  399. int decimalCount = 0;
  400. int lastValueIndex = -1;
  401. for (int c = 0; c < (int)result.length(); c++) {
  402. if (result[c] == '.') {
  403. decimalCount++;
  404. } else if (result[c] == ',') {
  405. result[c] = '.'; // Convert nationalized french decimal serialization into international decimals
  406. decimalCount++;
  407. } else if (decimalCount > 0 && result[c] >= '1' && result[c] <= '9') {
  408. lastValueIndex = c;
  409. } else if (decimalCount == 0 && result[c] >= '0' && result[c] <= '9') {
  410. lastValueIndex = c;
  411. }
  412. }
  413. for (int c = 0; c <= lastValueIndex; c++) {
  414. target.appendChar(result[c]);
  415. }
  416. }
  417. #define TO_RAW_ASCII(TARGET, SOURCE) \
  418. char TARGET[SOURCE.length() + 1]; \
  419. for (int i = 0; i < SOURCE.length(); i++) { \
  420. TARGET[i] = toAscii(SOURCE[i]); \
  421. } \
  422. TARGET[SOURCE.length()] = '\0';
  423. String dsr::string_load(const ReadableString& filename) {
  424. // TODO: Load files using Unicode filenames
  425. TO_RAW_ASCII(asciiFilename, filename);
  426. std::ifstream inputFile(asciiFilename);
  427. if (inputFile.is_open()) {
  428. std::stringstream outputBuffer;
  429. // TODO: Feed directly to String
  430. outputBuffer << inputFile.rdbuf();
  431. std::string content = outputBuffer.str();
  432. String result;
  433. result.reserve(content.size());
  434. for (int i = 0; i < (int)(content.size()); i++) {
  435. result.appendChar(content[i]);
  436. }
  437. inputFile.close();
  438. return result;
  439. } else {
  440. throwError("Failed to load ", filename, "\n");
  441. return U"";
  442. }
  443. }
  444. void dsr::string_save(const ReadableString& filename, const ReadableString& content) {
  445. // TODO: Load files using Unicode filenames
  446. TO_RAW_ASCII(asciiFilename, filename);
  447. TO_RAW_ASCII(asciiContent, content);
  448. std::ofstream outputFile;
  449. outputFile.open(asciiFilename);
  450. if (outputFile.is_open()) {
  451. outputFile << asciiContent;
  452. outputFile.close();
  453. } else {
  454. throwError("Failed to save ", filename, "\n");
  455. }
  456. }
  457. const char32_t* dsr::file_separator() {
  458. #ifdef _WIN32
  459. return U"\\";
  460. #else
  461. return U"/";
  462. #endif
  463. }
  464. int ReadableString::length() const {
  465. return this->sectionLength;
  466. }
  467. bool ReadableString::checkBound(int start, int length, bool warning) const {
  468. if (start < 0 || start + length > this->length()) {
  469. if (warning) {
  470. String message;
  471. string_append(message, U"\n");
  472. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  473. string_append(message, U"/\n");
  474. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  475. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  476. string_append(message, U"\\_______________________________________________________________________\n");
  477. throwError(message);
  478. }
  479. return false;
  480. } else {
  481. return true;
  482. }
  483. }
  484. DsrChar ReadableString::read(int index) const {
  485. if (index < 0 || index >= this->sectionLength) {
  486. return '\0';
  487. } else {
  488. return this->readSection[index];
  489. }
  490. }
  491. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  492. Printable::~Printable() {}
  493. ReadableString::ReadableString() {}
  494. ReadableString::~ReadableString() {}
  495. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  496. : readSection(content), sectionLength(sectionLength) {}
  497. ReadableString::ReadableString(const DsrChar *content)
  498. : readSection(content), sectionLength(strlen_utf16(content)) {}
  499. String::String() {}
  500. String::String(const char* source) { this->append(source); }
  501. String::String(const char32_t* source) { this->append(source); }
  502. String::String(const std::string& source) { this->append(source); }
  503. String::String(const ReadableString& source) { this->append(source); }
  504. String::String(const String& source) { this->append(source); }
  505. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  506. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  507. int String::capacity() {
  508. if (this->buffer.get() == nullptr) {
  509. return 0;
  510. } else {
  511. // Get the parent allocation
  512. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  513. // Get the offset from the parent
  514. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  515. // Subtract offset from the buffer size to get the remaining space
  516. return (this->buffer->size - offset) / sizeof(DsrChar);
  517. }
  518. }
  519. ReadableString ReadableString::getRange(int start, int length) const {
  520. if (length < 1) {
  521. return ReadableString();
  522. } else if (this->checkBound(start, length)) {
  523. return ReadableString(&(this->readSection[start]), length);
  524. } else {
  525. return ReadableString();
  526. }
  527. }
  528. ReadableString String::getRange(int start, int length) const {
  529. if (length < 1) {
  530. return ReadableString();
  531. } else if (this->checkBound(start, length)) {
  532. return String(this->buffer, &(this->writeSection[start]), length);
  533. } else {
  534. return ReadableString();
  535. }
  536. }
  537. static int32_t getNewBufferSize(int32_t minimumSize) {
  538. if (minimumSize <= 128) {
  539. return 128;
  540. } else if (minimumSize <= 512) {
  541. return 512;
  542. } else if (minimumSize <= 2048) {
  543. return 2048;
  544. } else if (minimumSize <= 8192) {
  545. return 8192;
  546. } else if (minimumSize <= 32768) {
  547. return 32768;
  548. } else if (minimumSize <= 131072) {
  549. return 131072;
  550. } else if (minimumSize <= 524288) {
  551. return 524288;
  552. } else if (minimumSize <= 2097152) {
  553. return 2097152;
  554. } else if (minimumSize <= 8388608) {
  555. return 8388608;
  556. } else if (minimumSize <= 33554432) {
  557. return 33554432;
  558. } else if (minimumSize <= 134217728) {
  559. return 134217728;
  560. } else if (minimumSize <= 536870912) {
  561. return 536870912;
  562. } else {
  563. return 2147483647;
  564. }
  565. }
  566. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  567. // Holding oldData alive while copying to the new buffer
  568. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  569. const char32_t* oldData = this->readSection;
  570. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  571. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  572. if (preserve && oldData) {
  573. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  574. }
  575. }
  576. // Call before writing to the buffer
  577. // This hides that Strings share buffers when assigning by value or taking partial strings
  578. void String::cloneIfShared() {
  579. if (this->buffer.use_count() > 1) {
  580. this->reallocateBuffer(this->sectionLength, true);
  581. }
  582. }
  583. void String::expand(int32_t newLength, bool affectUsedLength) {
  584. if (newLength > this->sectionLength) {
  585. if (newLength > this->capacity()) {
  586. this->reallocateBuffer(newLength, true);
  587. }
  588. }
  589. if (affectUsedLength) {
  590. this->sectionLength = newLength;
  591. }
  592. }
  593. void String::reserve(int32_t minimumLength) {
  594. this->expand(minimumLength, false);
  595. }
  596. void String::write(int index, DsrChar value) {
  597. this->cloneIfShared();
  598. if (index < 0 || index >= this->sectionLength) {
  599. // TODO: Give a warning
  600. } else {
  601. this->writeSection[index] = value;
  602. }
  603. }
  604. void String::clear() {
  605. this->sectionLength = 0;
  606. }
  607. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  608. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  609. // Proof that appending to one string doesn't affect another:
  610. // If it has to reallocate
  611. // * Then it will have its own buffer without conflicts
  612. // If it doesn't have to reallocate
  613. // If it shares the buffer
  614. // If source is empty
  615. // * Then no risk of overwriting neighbor strings if we don't write
  616. // If source isn't empty
  617. // * Then the buffer will be cloned when the first character is written
  618. // If it doesn't share the buffer
  619. // * Then no risk of writing
  620. #define APPEND(TARGET, SOURCE, LENGTH) { \
  621. int oldLength = (TARGET)->length(); \
  622. (TARGET)->expand(oldLength + (int)(LENGTH), true); \
  623. for (int i = 0; i < (int)(LENGTH); i++) { \
  624. (TARGET)->write(oldLength + i, (SOURCE)[i]); \
  625. } \
  626. }
  627. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  628. void String::append(const char* source) { APPEND(this, source, strlen(source)); }
  629. // TODO: Use memcpy when appending input of the same format
  630. void String::append(const ReadableString& source) { APPEND(this, source, source.length()); }
  631. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf16(source)); }
  632. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size()); }
  633. void String::appendChar(DsrChar source) { APPEND(this, &source, 1); }
  634. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  635. return source.toStreamIndented(target, indentation);
  636. }
  637. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  638. target.append(indentation);
  639. target.append(value);
  640. return target;
  641. }
  642. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  643. target.append(indentation);
  644. target.append(value);
  645. return target;
  646. }
  647. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  648. target.append(indentation);
  649. target.append(value);
  650. return target;
  651. }
  652. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  653. target.append(indentation);
  654. target.append(value);
  655. return target;
  656. }
  657. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  658. target.append(indentation);
  659. doubleToString_arabic(target, (double)value);
  660. return target;
  661. }
  662. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  663. target.append(indentation);
  664. doubleToString_arabic(target, value);
  665. return target;
  666. }
  667. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  668. target.append(indentation);
  669. intToString_arabic(target, value);
  670. return target;
  671. }
  672. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  673. target.append(indentation);
  674. uintToString_arabic(target, value);
  675. return target;
  676. }
  677. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  678. target.append(indentation);
  679. intToString_arabic(target, (int64_t)value);
  680. return target;
  681. }
  682. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  683. target.append(indentation);
  684. uintToString_arabic(target, (uint64_t)value);
  685. return target;
  686. }
  687. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  688. target.append(indentation);
  689. intToString_arabic(target, (int64_t)value);
  690. return target;
  691. }
  692. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  693. target.append(indentation);
  694. uintToString_arabic(target, (uint64_t)value);
  695. return target;
  696. }
  697. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  698. target.append(indentation);
  699. intToString_arabic(target, (int64_t)value);
  700. return target;
  701. }
  702. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  703. target.append(indentation);
  704. uintToString_arabic(target, (uint64_t)value);
  705. return target;
  706. }
  707. void dsr::throwErrorMessage(const String& message) {
  708. throw std::runtime_error(message.toStdString());
  709. }