stringAPI.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2020 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. // Gets access to private members by making them public for the whole module
  24. #define DFPSR_INTERNAL_ACCESS
  25. #include <fstream>
  26. #include <streambuf>
  27. #include <cstring>
  28. #include <string>
  29. #include <stdexcept>
  30. #include "stringAPI.h"
  31. #include "../api/fileAPI.h"
  32. using namespace dsr;
  33. static void atomic_append(String &target, const char* source);
  34. static void atomic_append(String &target, const ReadableString& source);
  35. static void atomic_append(String &target, const char32_t* source);
  36. static void atomic_append(String &target, const std::string& source);
  37. static int64_t strlen_utf32(const char32_t *content) {
  38. int64_t length = 0;
  39. while (content[length] != 0) {
  40. length++;
  41. }
  42. return length;
  43. }
  44. static char toAscii(DsrChar c) {
  45. if (c > 127) {
  46. return '?';
  47. } else {
  48. return c;
  49. }
  50. }
  51. ReadableString::ReadableString() {}
  52. ReadableString::~ReadableString() {}
  53. ReadableString::ReadableString(const DsrChar *content)
  54. : readSection(content), length(strlen_utf32(content)) {}
  55. ReadableString::ReadableString(const String& source) {
  56. this->readSection = source.readSection;
  57. this->length = source.length;
  58. this->buffer = source.buffer;
  59. }
  60. // Not the fastest constructor, but won't bloat the public header
  61. // Hopefully most compilers know how to optimize this
  62. static ReadableString createSubString(const DsrChar *content, int64_t length, const Buffer &buffer) {
  63. ReadableString result;
  64. result.readSection = content;
  65. result.length = length;
  66. result.buffer = buffer;
  67. return result;
  68. }
  69. static String createSubString_shared(const DsrChar *content, int64_t length, const Buffer &buffer, char32_t* writeSection) {
  70. String result;
  71. result.readSection = content;
  72. result.length = length;
  73. result.buffer = buffer;
  74. result.writeSection = writeSection;
  75. return result;
  76. }
  77. String::String() {}
  78. String::String(const char* source) { atomic_append(*this, source); }
  79. String::String(const char32_t* source) { atomic_append(*this, source); }
  80. String::String(const std::string& source) { atomic_append(*this, source); }
  81. String::String(const String& source) {
  82. // Share immutable buffer
  83. this->readSection = source.readSection;
  84. this->length = source.length;
  85. this->buffer = source.buffer;
  86. this->writeSection = source.writeSection;
  87. }
  88. String::String(const ReadableString& source) {
  89. if (buffer_exists(source.buffer)) {
  90. this->readSection = source.readSection;
  91. this->length = source.length;
  92. this->buffer = source.buffer;
  93. this->writeSection = const_cast<char32_t*>(source.readSection); // Still safe because of immutability
  94. } else {
  95. // No buffer to share, just appending the content
  96. atomic_append(*this, source);
  97. }
  98. }
  99. DsrChar ReadableString::operator[] (int64_t index) const {
  100. if (index < 0 || index >= this->length) {
  101. return U'\0';
  102. } else {
  103. return this->readSection[index];
  104. }
  105. }
  106. String& Printable::toStream(String& target) const {
  107. return this->toStreamIndented(target, U"");
  108. }
  109. String Printable::toStringIndented(const ReadableString& indentation) const {
  110. String result;
  111. this->toStreamIndented(result, indentation);
  112. return result;
  113. }
  114. String Printable::toString() const {
  115. return this->toStringIndented(U"");
  116. }
  117. std::ostream& Printable::toStreamIndented(std::ostream& out, const ReadableString& indentation) const {
  118. String result;
  119. this->toStreamIndented(result, indentation);
  120. for (int64_t i = 0; i < result.length; i++) {
  121. out.put(toAscii(result.readSection[i]));
  122. }
  123. return out;
  124. }
  125. std::ostream& Printable::toStream(std::ostream& out) const {
  126. return this->toStreamIndented(out, U"");
  127. }
  128. std::string Printable::toStdString() const {
  129. std::ostringstream result;
  130. this->toStream(result);
  131. return result.str();
  132. }
  133. Printable::~Printable() {}
  134. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  135. if (a.length != b.length) {
  136. return false;
  137. } else {
  138. for (int64_t i = 0; i < a.length; i++) {
  139. if (a.readSection[i] != b.readSection[i]) {
  140. return false;
  141. }
  142. }
  143. return true;
  144. }
  145. }
  146. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  147. if (a.length != b.length) {
  148. return false;
  149. } else {
  150. for (int64_t i = 0; i < a.length; i++) {
  151. if (towupper(a.readSection[i]) != towupper(b.readSection[i])) {
  152. return false;
  153. }
  154. }
  155. return true;
  156. }
  157. }
  158. std::ostream& ReadableString::toStream(std::ostream& out) const {
  159. for (int64_t i = 0; i < this->length; i++) {
  160. out.put(toAscii(this->readSection[i]));
  161. }
  162. return out;
  163. }
  164. std::string ReadableString::toStdString() const {
  165. std::ostringstream result;
  166. this->toStream(result);
  167. return result.str();
  168. }
  169. String dsr::string_upperCase(const ReadableString &text) {
  170. String result;
  171. string_reserve(result, text.length);
  172. for (int64_t i = 0; i < text.length; i++) {
  173. string_appendChar(result, towupper(text[i]));
  174. }
  175. return result;
  176. }
  177. String dsr::string_lowerCase(const ReadableString &text) {
  178. String result;
  179. string_reserve(result, text.length);
  180. for (int64_t i = 0; i < text.length; i++) {
  181. string_appendChar(result, towlower(text[i]));
  182. }
  183. return result;
  184. }
  185. static int64_t findFirstNonWhite(const ReadableString &text) {
  186. for (int64_t i = 0; i < text.length; i++) {
  187. DsrChar c = text[i];
  188. if (!character_isWhiteSpace(c)) {
  189. return i;
  190. }
  191. }
  192. return -1;
  193. }
  194. static int64_t findLastNonWhite(const ReadableString &text) {
  195. for (int64_t i = text.length - 1; i >= 0; i--) {
  196. DsrChar c = text[i];
  197. if (!character_isWhiteSpace(c)) {
  198. return i;
  199. }
  200. }
  201. return -1;
  202. }
  203. // Allow passing literals without allocating heap memory for the result
  204. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  205. int64_t first = findFirstNonWhite(text);
  206. int64_t last = findLastNonWhite(text);
  207. if (first == -1) {
  208. // Only white space
  209. return ReadableString();
  210. } else {
  211. // Subset
  212. return string_inclusiveRange(text, first, last);
  213. }
  214. }
  215. String dsr::string_mangleQuote(const ReadableString &rawText) {
  216. String result;
  217. string_reserve(result, rawText.length + 2);
  218. string_appendChar(result, U'\"'); // Begin quote
  219. for (int64_t i = 0; i < rawText.length; i++) {
  220. DsrChar c = rawText[i];
  221. if (c == U'\"') { // Double quote
  222. string_append(result, U"\\\"");
  223. } else if (c == U'\\') { // Backslash
  224. string_append(result, U"\\\\");
  225. } else if (c == U'\a') { // Audible bell
  226. string_append(result, U"\\a");
  227. } else if (c == U'\b') { // Backspace
  228. string_append(result, U"\\b");
  229. } else if (c == U'\f') { // Form feed
  230. string_append(result, U"\\f");
  231. } else if (c == U'\n') { // Line feed
  232. string_append(result, U"\\n");
  233. } else if (c == U'\r') { // Carriage return
  234. string_append(result, U"\\r");
  235. } else if (c == U'\t') { // Horizontal tab
  236. string_append(result, U"\\t");
  237. } else if (c == U'\v') { // Vertical tab
  238. string_append(result, U"\\v");
  239. } else if (c == U'\0') { // Null terminator
  240. string_append(result, U"\\0");
  241. } else {
  242. string_appendChar(result, c);
  243. }
  244. }
  245. string_appendChar(result, U'\"'); // End quote
  246. return result;
  247. }
  248. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  249. int64_t firstQuote = string_findFirst(mangledText, '\"');
  250. int64_t lastQuote = string_findLast(mangledText, '\"');
  251. String result;
  252. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  253. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, "\n");
  254. } else {
  255. for (int64_t i = firstQuote + 1; i < lastQuote; i++) {
  256. DsrChar c = mangledText[i];
  257. if (c == U'\\') { // Escape character
  258. DsrChar c2 = mangledText[i + 1];
  259. if (c2 == U'\"') { // Double quote
  260. string_appendChar(result, U'\"');
  261. } else if (c2 == U'\\') { // Back slash
  262. string_appendChar(result, U'\\');
  263. } else if (c2 == U'a') { // Audible bell
  264. string_appendChar(result, U'\a');
  265. } else if (c2 == U'b') { // Backspace
  266. string_appendChar(result, U'\b');
  267. } else if (c2 == U'f') { // Form feed
  268. string_appendChar(result, U'\f');
  269. } else if (c2 == U'n') { // Line feed
  270. string_appendChar(result, U'\n');
  271. } else if (c2 == U'r') { // Carriage return
  272. string_appendChar(result, U'\r');
  273. } else if (c2 == U't') { // Horizontal tab
  274. string_appendChar(result, U'\t');
  275. } else if (c2 == U'v') { // Vertical tab
  276. string_appendChar(result, U'\v');
  277. } else if (c2 == U'0') { // Null terminator
  278. string_appendChar(result, U'\0');
  279. }
  280. i++; // Consume both characters
  281. } else {
  282. // Detect bad input
  283. if (c == U'\"') { // Double quote
  284. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, "\n");
  285. } else if (c == U'\a') { // Audible bell
  286. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  287. } else if (c == U'\b') { // Backspace
  288. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  289. } else if (c == U'\f') { // Form feed
  290. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  291. } else if (c == U'\n') { // Line feed
  292. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  293. } else if (c == U'\r') { // Carriage return
  294. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  295. } else if (c == U'\0') { // Null terminator
  296. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  297. } else {
  298. string_appendChar(result, c);
  299. }
  300. }
  301. }
  302. }
  303. return result;
  304. }
  305. static void uintToString_arabic(String& target, uint64_t value) {
  306. static const int bufferSize = 20;
  307. DsrChar digits[bufferSize];
  308. int64_t usedSize = 0;
  309. if (value == 0) {
  310. string_appendChar(target, U'0');
  311. } else {
  312. while (usedSize < bufferSize) {
  313. DsrChar digit = U'0' + (value % 10u);
  314. digits[usedSize] = digit;
  315. usedSize++;
  316. value /= 10u;
  317. if (value == 0) {
  318. break;
  319. }
  320. }
  321. while (usedSize > 0) {
  322. usedSize--;
  323. string_appendChar(target, digits[usedSize]);
  324. }
  325. }
  326. }
  327. static void intToString_arabic(String& target, int64_t value) {
  328. if (value >= 0) {
  329. uintToString_arabic(target, (uint64_t)value);
  330. } else {
  331. string_appendChar(target, U'-');
  332. uintToString_arabic(target, (uint64_t)(-value));
  333. }
  334. }
  335. static const int MAX_DECIMALS = 16;
  336. static double decimalMultipliers[MAX_DECIMALS] = {
  337. 10.0,
  338. 100.0,
  339. 1000.0,
  340. 10000.0,
  341. 100000.0,
  342. 1000000.0,
  343. 10000000.0,
  344. 100000000.0,
  345. 1000000000.0,
  346. 10000000000.0,
  347. 100000000000.0,
  348. 1000000000000.0,
  349. 10000000000000.0,
  350. 100000000000000.0,
  351. 1000000000000000.0,
  352. 10000000000000000.0
  353. };
  354. static void doubleToString_arabic(String& target, double value, int decimalCount = 6, bool removeTrailingZeroes = true, DsrChar decimalCharacter = U'.', DsrChar negationCharacter = U'-') {
  355. if (decimalCount < 1) decimalCount = 1;
  356. if (decimalCount > MAX_DECIMALS) decimalCount = MAX_DECIMALS;
  357. double remainder = value;
  358. // Get negation
  359. if (remainder < 0.0) {
  360. string_appendChar(target, negationCharacter);
  361. remainder = -remainder;
  362. }
  363. // Get whole part
  364. uint64_t whole = (uint64_t)remainder;
  365. uintToString_arabic(target, whole);
  366. remainder = remainder - whole;
  367. // Print the decimal
  368. string_appendChar(target, decimalCharacter);
  369. // Get decimals
  370. uint64_t scaledDecimals = (uint64_t)((remainder * decimalMultipliers[decimalCount - 1]) + 0.5f);
  371. DsrChar digits[MAX_DECIMALS]; // Using 0 to decimalCount - 1
  372. int writeIndex = decimalCount - 1;
  373. for (int d = 0; d < decimalCount; d++) {
  374. int digit = scaledDecimals % 10;
  375. digits[writeIndex] = U'0' + digit;
  376. scaledDecimals = scaledDecimals / 10;
  377. writeIndex--;
  378. }
  379. if (removeTrailingZeroes) {
  380. // Find the last non-zero decimal, but keep at least one zero.
  381. int lastValue = 0;
  382. for (int d = 0; d < decimalCount; d++) {
  383. if (digits[d] != U'0') lastValue = d;
  384. }
  385. // Print until the last value or the only zero.
  386. for (int d = 0; d <= lastValue; d++) {
  387. string_appendChar(target, digits[d]);
  388. }
  389. } else {
  390. // Print fixed decimals.
  391. for (int d = 0; d < decimalCount; d++) {
  392. string_appendChar(target, digits[d]);
  393. }
  394. }
  395. }
  396. #define TO_RAW_ASCII(TARGET, SOURCE) \
  397. char TARGET[SOURCE.length + 1]; \
  398. for (int64_t i = 0; i < SOURCE.length; i++) { \
  399. TARGET[i] = toAscii(SOURCE[i]); \
  400. } \
  401. TARGET[SOURCE.length] = '\0';
  402. // A function definition for receiving a stream of bytes
  403. // Instead of using std's messy inheritance
  404. using ByteWriterFunction = std::function<void(uint8_t value)>;
  405. // A function definition for receiving a stream of UTF-32 characters
  406. // Instead of using std's messy inheritance
  407. using UTF32WriterFunction = std::function<void(DsrChar character)>;
  408. // Filter out unwanted characters for improved portability
  409. static void feedCharacter(const UTF32WriterFunction &receiver, DsrChar character) {
  410. if (character != U'\0' && character != U'\r') {
  411. receiver(character);
  412. }
  413. }
  414. // Appends the content of buffer as a BOM-free Latin-1 file into target
  415. // fileLength is ignored when nullTerminated is true
  416. template <bool nullTerminated>
  417. static void feedStringFromFileBuffer_Latin1(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength = 0) {
  418. for (int64_t i = 0; i < fileLength || nullTerminated; i++) {
  419. DsrChar character = (DsrChar)(buffer[i]);
  420. if (nullTerminated && character == 0) { return; }
  421. feedCharacter(receiver, character);
  422. }
  423. }
  424. // Appends the content of buffer as a BOM-free UTF-8 file into target
  425. // fileLength is ignored when nullTerminated is true
  426. template <bool nullTerminated>
  427. static void feedStringFromFileBuffer_UTF8(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength = 0) {
  428. for (int64_t i = 0; i < fileLength || nullTerminated; i++) {
  429. uint8_t byteA = buffer[i];
  430. if (byteA < (uint32_t)0b10000000) {
  431. // Single byte (1xxxxxxx)
  432. if (nullTerminated && byteA == 0) { return; }
  433. feedCharacter(receiver, (DsrChar)byteA);
  434. } else {
  435. uint32_t character = 0;
  436. int extraBytes = 0;
  437. if (byteA >= (uint32_t)0b11000000) { // At least two leading ones
  438. if (byteA < (uint32_t)0b11100000) { // Less than three leading ones
  439. character = byteA & (uint32_t)0b00011111;
  440. extraBytes = 1;
  441. } else if (byteA < (uint32_t)0b11110000) { // Less than four leading ones
  442. character = byteA & (uint32_t)0b00001111;
  443. extraBytes = 2;
  444. } else if (byteA < (uint32_t)0b11111000) { // Less than five leading ones
  445. character = byteA & (uint32_t)0b00000111;
  446. extraBytes = 3;
  447. } else {
  448. // Invalid UTF-8 format
  449. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  450. }
  451. } else {
  452. // Invalid UTF-8 format
  453. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  454. }
  455. while (extraBytes > 0) {
  456. i += 1; uint32_t nextByte = buffer[i];
  457. character = (character << 6) | (nextByte & 0b00111111);
  458. extraBytes--;
  459. }
  460. feedCharacter(receiver, (DsrChar)character);
  461. }
  462. }
  463. }
  464. template <bool LittleEndian>
  465. uint16_t read16bits(const uint8_t* buffer, int64_t startOffset) {
  466. uint16_t byteA = buffer[startOffset];
  467. uint16_t byteB = buffer[startOffset + 1];
  468. if (LittleEndian) {
  469. return (byteB << 8) | byteA;
  470. } else {
  471. return (byteA << 8) | byteB;
  472. }
  473. }
  474. // Appends the content of buffer as a BOM-free UTF-16 file into target as UTF-32
  475. // fileLength is ignored when nullTerminated is true
  476. template <bool LittleEndian, bool nullTerminated>
  477. static void feedStringFromFileBuffer_UTF16(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength = 0) {
  478. for (int64_t i = 0; i < fileLength || nullTerminated; i += 2) {
  479. // Read the first 16-bit word
  480. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  481. // Check if another word is needed
  482. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  483. // we can just check if it's within the range reserved for 32-bit encoding
  484. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  485. // Not in the reserved range, just a single 16-bit character
  486. if (nullTerminated && wordA == 0) { return; }
  487. feedCharacter(receiver, (DsrChar)wordA);
  488. } else {
  489. // The given range was reserved and therefore using 32 bits
  490. i += 2;
  491. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  492. uint32_t higher10Bits = wordA & (uint32_t)0b1111111111;
  493. uint32_t lower10Bits = wordB & (uint32_t)0b1111111111;
  494. DsrChar finalChar = (DsrChar)(((higher10Bits << 10) | lower10Bits) + (uint32_t)0x10000);
  495. feedCharacter(receiver, finalChar);
  496. }
  497. }
  498. }
  499. // Sends the decoded UTF-32 characters from the encoded buffer into target.
  500. // The text encoding should be specified using a BOM at the start of buffer, otherwise Latin-1 is assumed.
  501. static void feedStringFromFileBuffer(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength) {
  502. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  503. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  504. feedStringFromFileBuffer_UTF8<false>(receiver, buffer + 3, fileLength - 3);
  505. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  506. feedStringFromFileBuffer_UTF16<false, false>(receiver, buffer + 2, fileLength - 2);
  507. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  508. feedStringFromFileBuffer_UTF16<true, false>(receiver, buffer + 2, fileLength - 2);
  509. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  510. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  511. throwError(U"UTF-32 BE format is not yet supported!\n");
  512. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  513. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  514. throwError(U"UTF-32 LE format is not yet supported!\n");
  515. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  516. //feedStringFromFileBuffer_UTF1(receiver, buffer + 3, fileLength - 3);
  517. throwError(U"UTF-1 format is not yet supported!\n");
  518. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  519. //feedStringFromFileBuffer_SCSU(receiver, buffer + 3, fileLength - 3);
  520. throwError(U"SCSU format is not yet supported!\n");
  521. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  522. //feedStringFromFileBuffer_BOCU-1(receiver, buffer + 3, fileLength - 3);
  523. throwError(U"BOCU-1 format is not yet supported!\n");
  524. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  525. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  526. throwError(U"UTF-7 format is not yet supported!\n");
  527. } else {
  528. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  529. feedStringFromFileBuffer_Latin1<false>(receiver, buffer, fileLength);
  530. }
  531. }
  532. // Sends the decoded UTF-32 characters from the encoded null terminated buffer into target.
  533. // buffer may not contain any BOM, and must be null terminated in the specified encoding.
  534. static void feedStringFromRawData(const UTF32WriterFunction &receiver, const uint8_t* buffer, CharacterEncoding encoding) {
  535. if (encoding == CharacterEncoding::Raw_Latin1) {
  536. feedStringFromFileBuffer_Latin1<true>(receiver, buffer);
  537. } else if (encoding == CharacterEncoding::BOM_UTF8) {
  538. feedStringFromFileBuffer_UTF8<true>(receiver, buffer);
  539. } else if (encoding == CharacterEncoding::BOM_UTF16BE) {
  540. feedStringFromFileBuffer_UTF16<false, true>(receiver, buffer);
  541. } else if (encoding == CharacterEncoding::BOM_UTF16LE) {
  542. feedStringFromFileBuffer_UTF16<true, true>(receiver, buffer);
  543. } else {
  544. throwError("Unhandled encoding in feedStringFromRawData!\n");
  545. }
  546. }
  547. String dsr::string_dangerous_decodeFromData(const void* data, CharacterEncoding encoding) {
  548. String result;
  549. // Measure the size of the result by scanning the content in advance
  550. int64_t characterCount = 0;
  551. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  552. characterCount++;
  553. };
  554. feedStringFromRawData(measurer, (const uint8_t*)data, encoding);
  555. // Pre-allocate the correct amount of memory based on the simulation
  556. string_reserve(result, characterCount);
  557. // Stream output to the result string
  558. UTF32WriterFunction receiver = [&result](DsrChar character) {
  559. string_appendChar(result, character);
  560. };
  561. feedStringFromRawData(receiver, (const uint8_t*)data, encoding);
  562. return result;
  563. }
  564. String dsr::string_loadFromMemory(Buffer fileContent) {
  565. String result;
  566. // Measure the size of the result by scanning the content in advance
  567. int64_t characterCount = 0;
  568. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  569. characterCount++;
  570. };
  571. feedStringFromFileBuffer(measurer, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  572. // Pre-allocate the correct amount of memory based on the simulation
  573. string_reserve(result, characterCount);
  574. // Stream output to the result string
  575. UTF32WriterFunction receiver = [&result](DsrChar character) {
  576. string_appendChar(result, character);
  577. };
  578. feedStringFromFileBuffer(receiver, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  579. return result;
  580. }
  581. // Loads a text file of unknown format
  582. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines
  583. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  584. Buffer encoded = file_loadBuffer(filename, mustExist);
  585. if (!buffer_exists(encoded)) {
  586. return String();
  587. } else {
  588. return string_loadFromMemory(encoded);
  589. }
  590. }
  591. template <CharacterEncoding characterEncoding>
  592. static void encodeCharacter(const ByteWriterFunction &receiver, DsrChar character) {
  593. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  594. // Replace any illegal characters with questionmarks
  595. if (character > 255) { character = U'?'; }
  596. receiver(character);
  597. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  598. // Replace any illegal characters with questionmarks
  599. if (character > 0x10FFFF) { character = U'?'; }
  600. if (character < (1 << 7)) {
  601. // 0xxxxxxx
  602. receiver(character);
  603. } else if (character < (1 << 11)) {
  604. // 110xxxxx 10xxxxxx
  605. receiver((uint32_t)0b11000000 | ((character & ((uint32_t)0b11111 << 6)) >> 6));
  606. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  607. } else if (character < (1 << 16)) {
  608. // 1110xxxx 10xxxxxx 10xxxxxx
  609. receiver((uint32_t)0b11100000 | ((character & ((uint32_t)0b1111 << 12)) >> 12));
  610. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  611. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  612. } else if (character < (1 << 21)) {
  613. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  614. receiver((uint32_t)0b11110000 | ((character & ((uint32_t)0b111 << 18)) >> 18));
  615. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 12)) >> 12));
  616. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  617. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  618. }
  619. } else { // Assuming UTF-16
  620. if (character > 0x10FFFF) { character = U'?'; }
  621. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  622. // xxxxxxxx xxxxxxxx (Limited range)
  623. uint32_t higher8Bits = (character & (uint32_t)0b1111111100000000) >> 8;
  624. uint32_t lower8Bits = character & (uint32_t)0b0000000011111111;
  625. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  626. receiver(higher8Bits);
  627. receiver(lower8Bits);
  628. } else { // Assuming UTF-16 LE
  629. receiver(lower8Bits);
  630. receiver(higher8Bits);
  631. }
  632. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  633. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  634. uint32_t code = character - (uint32_t)0x10000;
  635. uint32_t byteA = ((code & (uint32_t)0b11000000000000000000) >> 18) | (uint32_t)0b11011000;
  636. uint32_t byteB = (code & (uint32_t)0b00111111110000000000) >> 10;
  637. uint32_t byteC = ((code & (uint32_t)0b00000000001100000000) >> 8) | (uint32_t)0b11011100;
  638. uint32_t byteD = code & (uint32_t)0b00000000000011111111;
  639. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  640. receiver(byteA);
  641. receiver(byteB);
  642. receiver(byteC);
  643. receiver(byteD);
  644. } else { // Assuming UTF-16 LE
  645. receiver(byteB);
  646. receiver(byteA);
  647. receiver(byteD);
  648. receiver(byteC);
  649. }
  650. }
  651. }
  652. }
  653. // Template for encoding a whole string
  654. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  655. static void encodeText(const ByteWriterFunction &receiver, String content, bool writeBOM, bool writeNullTerminator) {
  656. if (writeBOM) {
  657. // Write byte order marks
  658. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  659. receiver(0xEF);
  660. receiver(0xBB);
  661. receiver(0xBF);
  662. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  663. receiver(0xFE);
  664. receiver(0xFF);
  665. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  666. receiver(0xFF);
  667. receiver(0xFE);
  668. }
  669. }
  670. // Write encoded content
  671. for (int64_t i = 0; i < string_length(content); i++) {
  672. DsrChar character = content[i];
  673. if (character == U'\n') {
  674. if (lineEncoding == LineEncoding::CrLf) {
  675. encodeCharacter<characterEncoding>(receiver, U'\r');
  676. encodeCharacter<characterEncoding>(receiver, U'\n');
  677. } else { // Assuming that lineEncoding == LineEncoding::Lf
  678. encodeCharacter<characterEncoding>(receiver, U'\n');
  679. }
  680. } else {
  681. encodeCharacter<characterEncoding>(receiver, character);
  682. }
  683. }
  684. if (writeNullTerminator) {
  685. // Terminate internal strings with \0 to prevent getting garbage data after unpadded buffers
  686. if (characterEncoding == CharacterEncoding::BOM_UTF16BE || characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  687. receiver(0);
  688. receiver(0);
  689. } else {
  690. receiver(0);
  691. }
  692. }
  693. }
  694. // Macro for converting run-time arguments into template arguments for encodeText
  695. #define ENCODE_TEXT(RECEIVER, CONTENT, CHAR_ENCODING, LINE_ENCODING, WRITE_BOM, WRITE_NULL_TERMINATOR) \
  696. if (CHAR_ENCODING == CharacterEncoding::Raw_Latin1) { \
  697. if (LINE_ENCODING == LineEncoding::CrLf) { \
  698. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::CrLf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  699. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  700. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::Lf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  701. } \
  702. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF8) { \
  703. if (LINE_ENCODING == LineEncoding::CrLf) { \
  704. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  705. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  706. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  707. } \
  708. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16BE) { \
  709. if (LINE_ENCODING == LineEncoding::CrLf) { \
  710. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  711. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  712. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  713. } \
  714. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16LE) { \
  715. if (LINE_ENCODING == LineEncoding::CrLf) { \
  716. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  717. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  718. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  719. } \
  720. }
  721. // Encoding to a buffer before saving all at once as a binary file.
  722. // This tells the operating system how big the file is in advance and prevent the worst case of stalling for minutes!
  723. bool dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  724. Buffer buffer = string_saveToMemory(content, characterEncoding, lineEncoding);
  725. if (buffer_exists(buffer)) {
  726. return file_saveBuffer(filename, buffer);
  727. } else {
  728. return false;
  729. }
  730. }
  731. Buffer dsr::string_saveToMemory(const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding, bool writeByteOrderMark, bool writeNullTerminator) {
  732. int64_t byteCount = 0;
  733. ByteWriterFunction counter = [&byteCount](uint8_t value) {
  734. byteCount++;
  735. };
  736. ENCODE_TEXT(counter, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  737. Buffer result = buffer_create(byteCount);
  738. SafePointer<uint8_t> byteWriter = buffer_getSafeData<uint8_t>(result, "Buffer for string encoding");
  739. ByteWriterFunction receiver = [&byteWriter](uint8_t value) {
  740. *byteWriter = value;
  741. byteWriter += 1;
  742. };
  743. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  744. return result;
  745. }
  746. static int64_t getNewBufferSize(int64_t minimumSize) {
  747. if (minimumSize <= 128) {
  748. return 128;
  749. } else if (minimumSize <= 512) {
  750. return 512;
  751. } else if (minimumSize <= 2048) {
  752. return 2048;
  753. } else if (minimumSize <= 8192) {
  754. return 8192;
  755. } else if (minimumSize <= 32768) {
  756. return 32768;
  757. } else if (minimumSize <= 131072) {
  758. return 131072;
  759. } else if (minimumSize <= 524288) {
  760. return 524288;
  761. } else if (minimumSize <= 2097152) {
  762. return 2097152;
  763. } else if (minimumSize <= 8388608) {
  764. return 8388608;
  765. } else if (minimumSize <= 33554432) {
  766. return 33554432;
  767. } else if (minimumSize <= 134217728) {
  768. return 134217728;
  769. } else if (minimumSize <= 536870912) {
  770. return 536870912;
  771. } else {
  772. return minimumSize;
  773. }
  774. }
  775. // Replaces the buffer with a new buffer holding at least newLength characters
  776. // Guarantees that the new buffer is not shared by other strings, so that it may be written to freely
  777. static void reallocateBuffer(String &target, int64_t newLength, bool preserve) {
  778. // Holding oldData alive while copying to the new buffer
  779. Buffer oldBuffer = target.buffer; // Kept for reference counting only, do not remove.
  780. const char32_t* oldData = target.readSection;
  781. target.buffer = buffer_create(getNewBufferSize(newLength * sizeof(DsrChar)));
  782. target.readSection = target.writeSection = reinterpret_cast<char32_t*>(buffer_dangerous_getUnsafeData(target.buffer));
  783. if (preserve && oldData) {
  784. memcpy(target.writeSection, oldData, target.length * sizeof(DsrChar));
  785. }
  786. }
  787. // Call before writing to the buffer
  788. // This hides that Strings share buffers when assigning by value or taking partial strings
  789. static void cloneIfShared(String &target) {
  790. if (target.buffer.use_count() > 1) {
  791. reallocateBuffer(target, target.length, true);
  792. }
  793. }
  794. void dsr::string_clear(String& target) {
  795. cloneIfShared(target);
  796. target.length = 0;
  797. }
  798. // The number of DsrChar characters that can be contained in the allocation before reaching the buffer's end
  799. // This doesn't imply that it's always okay to write to the remaining space, because the buffer may be shared
  800. static int64_t getCapacity(const ReadableString &source) {
  801. if (buffer_exists(source.buffer)) {
  802. // Get the allocation
  803. uint8_t* data = buffer_dangerous_getUnsafeData(source.buffer);
  804. uint8_t* start = (uint8_t*)(source.readSection);
  805. // Get the offset from the parent
  806. intptr_t offset = start - data;
  807. // Subtract offset from the buffer size to get the remaining space
  808. return (buffer_getSize(source.buffer) - offset) / sizeof(DsrChar);
  809. } else {
  810. return 0;
  811. }
  812. }
  813. static void expand(String &target, int64_t newLength, bool affectUsedLength) {
  814. cloneIfShared(target);
  815. if (newLength > target.length) {
  816. if (newLength > getCapacity(target)) {
  817. reallocateBuffer(target, newLength, true);
  818. }
  819. if (affectUsedLength) {
  820. target.length = newLength;
  821. }
  822. }
  823. }
  824. void dsr::string_reserve(String& target, int64_t minimumLength) {
  825. expand(target, minimumLength, false);
  826. }
  827. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  828. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  829. // Proof that appending to one string doesn't affect another:
  830. // If it has to reallocate
  831. // * Then it will have its own buffer without conflicts
  832. // If it doesn't have to reallocate
  833. // If it shares the buffer
  834. // If source is empty
  835. // * Then no risk of overwriting neighbor strings if we don't write
  836. // If source isn't empty
  837. // * Then the buffer will be cloned when the first character is written
  838. // If it doesn't share the buffer
  839. // * Then no risk of writing
  840. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  841. int64_t oldLength = (TARGET).length; \
  842. expand((TARGET), oldLength + (int64_t)(LENGTH), true); \
  843. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  844. (TARGET).writeSection[oldLength + i] = ((SOURCE)[i]) & MASK; \
  845. } \
  846. }
  847. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  848. static void atomic_append(String &target, const char* source) { APPEND(target, source, strlen(source), 0xFF); }
  849. // TODO: Use memcpy when appending input of the same format
  850. static void atomic_append(String &target, const ReadableString& source) { APPEND(target, source, source.length, 0xFFFFFFFF); }
  851. static void atomic_append(String &target, const char32_t* source) { APPEND(target, source, strlen_utf32(source), 0xFFFFFFFF); }
  852. static void atomic_append(String &target, const std::string& source) { APPEND(target, source.c_str(), (int64_t)source.size(), 0xFF); }
  853. void dsr::string_appendChar(String& target, DsrChar value) { APPEND(target, &value, 1, 0xFFFFFFFF); }
  854. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  855. return source.toStreamIndented(target, indentation);
  856. }
  857. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  858. atomic_append(target, indentation);
  859. atomic_append(target, value);
  860. return target;
  861. }
  862. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  863. atomic_append(target, indentation);
  864. atomic_append(target, value);
  865. return target;
  866. }
  867. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  868. atomic_append(target, indentation);
  869. atomic_append(target, value);
  870. return target;
  871. }
  872. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  873. atomic_append(target, indentation);
  874. doubleToString_arabic(target, (double)value);
  875. return target;
  876. }
  877. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  878. atomic_append(target, indentation);
  879. doubleToString_arabic(target, value);
  880. return target;
  881. }
  882. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  883. atomic_append(target, indentation);
  884. intToString_arabic(target, value);
  885. return target;
  886. }
  887. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  888. atomic_append(target, indentation);
  889. uintToString_arabic(target, value);
  890. return target;
  891. }
  892. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  893. atomic_append(target, indentation);
  894. intToString_arabic(target, (int64_t)value);
  895. return target;
  896. }
  897. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  898. atomic_append(target, indentation);
  899. uintToString_arabic(target, (uint64_t)value);
  900. return target;
  901. }
  902. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  903. atomic_append(target, indentation);
  904. intToString_arabic(target, (int64_t)value);
  905. return target;
  906. }
  907. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  908. atomic_append(target, indentation);
  909. uintToString_arabic(target, (uint64_t)value);
  910. return target;
  911. }
  912. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  913. atomic_append(target, indentation);
  914. intToString_arabic(target, (int64_t)value);
  915. return target;
  916. }
  917. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  918. atomic_append(target, indentation);
  919. uintToString_arabic(target, (uint64_t)value);
  920. return target;
  921. }
  922. static const std::function<void(const ReadableString &message, MessageType type)> defaultMessageAction = [](const ReadableString &message, MessageType type) {
  923. if (type == MessageType::Error) {
  924. throw std::runtime_error(message.toStdString());
  925. } else {
  926. message.toStream(std::cout);
  927. }
  928. };
  929. static std::function<void(const ReadableString &message, MessageType type)> globalMessageAction = defaultMessageAction;
  930. void dsr::string_sendMessage(const ReadableString &message, MessageType type) {
  931. globalMessageAction(message, type);
  932. if (type == MessageType::Error) {
  933. throw std::runtime_error("The message handler provided using string_assignMessageHandler did not throw an exception or terminate the program for the given error!\n");
  934. }
  935. }
  936. void dsr::string_sendMessage_default(const ReadableString &message, MessageType type) {
  937. defaultMessageAction(message, type);
  938. }
  939. void dsr::string_assignMessageHandler(std::function<void(const ReadableString &message, MessageType type)> newHandler) {
  940. globalMessageAction = newHandler;
  941. }
  942. void dsr::string_unassignMessageHandler() {
  943. globalMessageAction = defaultMessageAction;
  944. }
  945. void dsr::string_split_callback(std::function<void(ReadableString separatedText)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  946. int64_t sectionStart = 0;
  947. for (int64_t i = 0; i < source.length; i++) {
  948. DsrChar c = source[i];
  949. if (c == separator) {
  950. ReadableString element = string_exclusiveRange(source, sectionStart, i);
  951. if (removeWhiteSpace) {
  952. action(string_removeOuterWhiteSpace(element));
  953. } else {
  954. action(element);
  955. }
  956. sectionStart = i + 1;
  957. }
  958. }
  959. if (source.length > sectionStart) {
  960. if (removeWhiteSpace) {
  961. action(string_removeOuterWhiteSpace(string_exclusiveRange(source, sectionStart, source.length)));
  962. } else {
  963. action(string_exclusiveRange(source, sectionStart, source.length));
  964. }
  965. }
  966. }
  967. List<String> dsr::string_split(const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  968. List<String> result;
  969. String commonBuffer;
  970. if (buffer_exists(source.buffer)) {
  971. // Re-use the existing buffer
  972. commonBuffer = createSubString_shared(source.readSection, source.length, source.buffer, const_cast<char32_t*>(source.readSection));
  973. } else {
  974. // Clone the whole input into one allocation to avoid fragmenting the heap with many small allocations
  975. commonBuffer = source;
  976. }
  977. // Source is allocated as String
  978. string_split_callback([&result, removeWhiteSpace](String element) {
  979. if (removeWhiteSpace) {
  980. result.push(string_removeOuterWhiteSpace(element));
  981. } else {
  982. result.push(element);
  983. }
  984. }, commonBuffer, separator, removeWhiteSpace);
  985. return result;
  986. }
  987. int64_t dsr::string_splitCount(const ReadableString& source, DsrChar separator) {
  988. int64_t result;
  989. string_split_callback([&result](ReadableString element) {
  990. result++;
  991. }, source, separator);
  992. return result;
  993. }
  994. int64_t dsr::string_toInteger(const ReadableString& source) {
  995. int64_t result;
  996. bool negated;
  997. result = 0;
  998. negated = false;
  999. for (int64_t i = 0; i < source.length; i++) {
  1000. DsrChar c = source[i];
  1001. if (c == '-' || c == '~') {
  1002. negated = !negated;
  1003. } else if (c >= '0' && c <= '9') {
  1004. result = (result * 10) + (int)(c - '0');
  1005. } else if (c == ',' || c == '.') {
  1006. // Truncate any decimals by ignoring them
  1007. break;
  1008. }
  1009. }
  1010. if (negated) {
  1011. return -result;
  1012. } else {
  1013. return result;
  1014. }
  1015. }
  1016. double dsr::string_toDouble(const ReadableString& source) {
  1017. double result;
  1018. bool negated;
  1019. bool reachedDecimal;
  1020. int64_t digitDivider;
  1021. result = 0.0;
  1022. negated = false;
  1023. reachedDecimal = false;
  1024. digitDivider = 1;
  1025. for (int64_t i = 0; i < source.length; i++) {
  1026. DsrChar c = source[i];
  1027. if (c == '-' || c == '~') {
  1028. negated = !negated;
  1029. } else if (c >= '0' && c <= '9') {
  1030. if (reachedDecimal) {
  1031. digitDivider = digitDivider * 10;
  1032. result = result + ((double)(c - '0') / (double)digitDivider);
  1033. } else {
  1034. result = (result * 10) + (double)(c - '0');
  1035. }
  1036. } else if (c == ',' || c == '.') {
  1037. reachedDecimal = true;
  1038. }
  1039. }
  1040. if (negated) {
  1041. return -result;
  1042. } else {
  1043. return result;
  1044. }
  1045. }
  1046. int64_t dsr::string_length(const ReadableString& source) {
  1047. return source.length;
  1048. }
  1049. int64_t dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int64_t startIndex) {
  1050. for (int64_t i = startIndex; i < source.length; i++) {
  1051. if (source[i] == toFind) {
  1052. return i;
  1053. }
  1054. }
  1055. return -1;
  1056. }
  1057. int64_t dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  1058. for (int64_t i = source.length - 1; i >= 0; i--) {
  1059. if (source[i] == toFind) {
  1060. return i;
  1061. }
  1062. }
  1063. return -1;
  1064. }
  1065. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t exclusiveEnd) {
  1066. // Return empty string for each complete miss
  1067. if (inclusiveStart >= source.length || exclusiveEnd <= 0) { return ReadableString(); }
  1068. // Automatically clamping to valid range
  1069. if (inclusiveStart < 0) { inclusiveStart = 0; }
  1070. if (exclusiveEnd > source.length) { exclusiveEnd = source.length; }
  1071. // Return the overlapping interval
  1072. return createSubString(&(source.readSection[inclusiveStart]), exclusiveEnd - inclusiveStart, source.buffer);
  1073. }
  1074. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t inclusiveEnd) {
  1075. return string_exclusiveRange(source, inclusiveStart, inclusiveEnd + 1);
  1076. }
  1077. ReadableString dsr::string_before(const ReadableString& source, int64_t exclusiveEnd) {
  1078. return string_exclusiveRange(source, 0, exclusiveEnd);
  1079. }
  1080. ReadableString dsr::string_until(const ReadableString& source, int64_t inclusiveEnd) {
  1081. return string_inclusiveRange(source, 0, inclusiveEnd);
  1082. }
  1083. ReadableString dsr::string_from(const ReadableString& source, int64_t inclusiveStart) {
  1084. return string_exclusiveRange(source, inclusiveStart, source.length);
  1085. }
  1086. ReadableString dsr::string_after(const ReadableString& source, int64_t exclusiveStart) {
  1087. return string_from(source, exclusiveStart + 1);
  1088. }
  1089. bool dsr::character_isDigit(DsrChar c) {
  1090. return c >= U'0' && c <= U'9';
  1091. }
  1092. bool dsr::character_isIntegerCharacter(DsrChar c) {
  1093. return c == U'-' || character_isDigit(c);
  1094. }
  1095. bool dsr::character_isValueCharacter(DsrChar c) {
  1096. return c == U'.' || character_isIntegerCharacter(c);
  1097. }
  1098. bool dsr::character_isWhiteSpace(DsrChar c) {
  1099. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  1100. }
  1101. // Macros for implementing regular expressions with a greedy approach consuming the first match
  1102. // Optional accepts 0 or 1 occurence
  1103. // Forced accepts 1 occurence
  1104. // Star accepts 0..N occurence
  1105. // Plus accepts 1..N occurence
  1106. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  1107. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  1108. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  1109. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  1110. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1111. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  1112. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1113. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  1114. // The greedy approach works here, because there's no ambiguity
  1115. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  1116. int64_t readIndex = 0;
  1117. if (allowWhiteSpace) {
  1118. PATTERN_STAR(WhiteSpace);
  1119. }
  1120. CHARACTER_OPTIONAL(U'-');
  1121. // At least one digit required
  1122. PATTERN_PLUS(IntegerCharacter);
  1123. if (allowWhiteSpace) {
  1124. PATTERN_STAR(WhiteSpace);
  1125. }
  1126. return readIndex == source.length;
  1127. }
  1128. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1129. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1130. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1131. if (string_findFirst(source, U'.') == -1) {
  1132. // No decimal detected
  1133. return string_isInteger(source, allowWhiteSpace);
  1134. } else {
  1135. int64_t readIndex = 0;
  1136. if (allowWhiteSpace) {
  1137. PATTERN_STAR(WhiteSpace);
  1138. }
  1139. // Double <- UnsignedDouble | '-' UnsignedDouble
  1140. CHARACTER_OPTIONAL(U'-');
  1141. // UnsignedDouble <- Digit* '.' Digit+
  1142. // Any number of integer digits
  1143. PATTERN_STAR(IntegerCharacter);
  1144. // Only dot for decimal
  1145. CHARACTER_FORCED(U'.')
  1146. // At least one decimal digit
  1147. PATTERN_PLUS(IntegerCharacter);
  1148. if (allowWhiteSpace) {
  1149. PATTERN_STAR(WhiteSpace);
  1150. }
  1151. return readIndex == source.length;
  1152. }
  1153. }
  1154. int64_t dsr::string_getBufferUseCount(const ReadableString& text) {
  1155. return text.buffer.use_count();
  1156. }