text.cpp 39 KB

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