stringAPI.cpp 45 KB

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