text.cpp 39 KB

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