text.cpp 39 KB

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