text.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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. #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'\0' && 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. feedCharacter(reciever, character);
  327. }
  328. }
  329. // Appends the content of buffer as a BOM-free UTF-8 file into target
  330. static void feedStringFromFileBuffer_UTF8(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  331. for (int64_t i = 0; i < fileLength; i++) {
  332. uint8_t byteA = buffer[i];
  333. if (byteA < (uint32_t)0b10000000) {
  334. // Single byte (1xxxxxxx)
  335. feedCharacter(reciever, (DsrChar)byteA);
  336. } else {
  337. uint32_t character = 0;
  338. int extraBytes = 0;
  339. if (byteA >= (uint32_t)0b11000000) { // At least two leading ones
  340. if (byteA < (uint32_t)0b11100000) { // Less than three leading ones
  341. character = byteA & (uint32_t)0b00011111;
  342. extraBytes = 1;
  343. } else if (byteA < (uint32_t)0b11110000) { // Less than four leading ones
  344. character = byteA & (uint32_t)0b00001111;
  345. extraBytes = 2;
  346. } else if (byteA < (uint32_t)0b11111000) { // Less than five leading ones
  347. character = byteA & (uint32_t)0b00000111;
  348. extraBytes = 3;
  349. } else {
  350. // Invalid UTF-8 format
  351. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  352. }
  353. } else {
  354. // Invalid UTF-8 format
  355. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  356. }
  357. while (extraBytes > 0) {
  358. i += 1; uint32_t nextByte = buffer[i];
  359. character = (character << 6) | (nextByte & 0b00111111);
  360. extraBytes--;
  361. }
  362. feedCharacter(reciever, (DsrChar)character);
  363. }
  364. }
  365. }
  366. template <bool LittleEndian>
  367. uint16_t read16bits(const uint8_t* buffer, int startOffset) {
  368. uint16_t byteA = buffer[startOffset];
  369. uint16_t byteB = buffer[startOffset + 1];
  370. if (LittleEndian) {
  371. return (byteB << 8) | byteA;
  372. } else {
  373. return (byteA << 8) | byteB;
  374. }
  375. }
  376. // Appends the content of buffer as a BOM-free UTF-16 file into target
  377. template <bool LittleEndian>
  378. static void feedStringFromFileBuffer_UTF16(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  379. for (int64_t i = 0; i < fileLength; i += 2) {
  380. // Read the first 16-bit word
  381. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  382. // Check if another word is needed
  383. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  384. // we can just check if it's within the range reserved for 32-bit encoding
  385. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  386. // Not in the reserved range, just a single 16-bit character
  387. feedCharacter(reciever, (DsrChar)wordA);
  388. } else {
  389. // The given range was reserved and therefore using 32 bits
  390. i += 2;
  391. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  392. uint32_t higher10Bits = wordA & (uint32_t)0b1111111111;
  393. uint32_t lower10Bits = wordB & (uint32_t)0b1111111111;
  394. feedCharacter(reciever, (DsrChar)(((higher10Bits << 10) | lower10Bits) + (uint32_t)0x10000));
  395. }
  396. }
  397. }
  398. // Appends the content of buffer as a text file of unknown format into target
  399. static void feedStringFromFileBuffer(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  400. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  401. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  402. feedStringFromFileBuffer_UTF8(reciever, buffer + 3, fileLength - 3);
  403. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  404. feedStringFromFileBuffer_UTF16<false>(reciever, buffer + 2, fileLength - 2);
  405. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  406. feedStringFromFileBuffer_UTF16<true>(reciever, buffer + 2, fileLength - 2);
  407. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  408. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  409. throwError(U"UTF-32 BE format is not yet supported!\n");
  410. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  411. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  412. throwError(U"UTF-32 LE format is not yet supported!\n");
  413. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  414. //feedStringFromFileBuffer_UTF1(receiver, buffer + 3, fileLength - 3);
  415. throwError(U"UTF-1 format is not yet supported!\n");
  416. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  417. //feedStringFromFileBuffer_SCSU(receiver, buffer + 3, fileLength - 3);
  418. throwError(U"SCSU format is not yet supported!\n");
  419. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  420. //feedStringFromFileBuffer_BOCU-1(receiver, buffer + 3, fileLength - 3);
  421. throwError(U"BOCU-1 format is not yet supported!\n");
  422. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  423. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  424. throwError(U"UTF-7 format is not yet supported!\n");
  425. } else {
  426. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  427. feedStringFromFileBuffer_Latin1(reciever, buffer, fileLength);
  428. }
  429. }
  430. String dsr::string_loadFromMemory(Buffer fileContent) {
  431. String result;
  432. // Measure the size of the result by scanning the content in advance
  433. int64_t characterCount = 0;
  434. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  435. characterCount++;
  436. };
  437. feedStringFromFileBuffer(measurer, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  438. // Pre-allocate the correct amount of memory based on the simulation
  439. result.reserve(characterCount);
  440. // Stream output to the result string
  441. UTF32WriterFunction reciever = [&result](DsrChar character) {
  442. result.appendChar(character);
  443. };
  444. feedStringFromFileBuffer(reciever, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  445. return result;
  446. }
  447. // Loads a text file of unknown format
  448. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines
  449. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  450. // TODO: Load files using Unicode filenames when available
  451. TO_RAW_ASCII(asciiFilename, filename);
  452. std::ifstream fileStream(asciiFilename, std::ios_base::in | std::ios_base::binary);
  453. if (fileStream.is_open()) {
  454. String result;
  455. // Get the file's length and allocate an array for the raw encoding
  456. fileStream.seekg (0, fileStream.end);
  457. int64_t fileLength = fileStream.tellg();
  458. fileStream.seekg (0, fileStream.beg);
  459. uint8_t* buffer = (uint8_t*)malloc(fileLength);
  460. fileStream.read((char*)buffer, fileLength);
  461. // Measure the size of the result by scanning the content in advance
  462. int64_t characterCount = 0;
  463. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  464. characterCount++;
  465. };
  466. feedStringFromFileBuffer(measurer, buffer, fileLength);
  467. // Pre-allocate the correct amount of memory based on the simulation
  468. result.reserve(characterCount);
  469. // Stream output to the result string
  470. UTF32WriterFunction reciever = [&result](DsrChar character) {
  471. result.appendChar(character);
  472. };
  473. feedStringFromFileBuffer(reciever, buffer, fileLength);
  474. free(buffer);
  475. return result;
  476. } else {
  477. if (mustExist) {
  478. throwError(U"The text file ", filename, U" could not be opened for reading.\n");
  479. }
  480. // If the file cound not be found and opened, a null string is returned
  481. return String();
  482. }
  483. }
  484. template <CharacterEncoding characterEncoding>
  485. static void encodeCharacter(const ByteWriterFunction &receiver, DsrChar character) {
  486. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  487. // Replace any illegal characters with questionmarks
  488. if (character > 255) { character = U'?'; }
  489. receiver(character);
  490. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  491. // Replace any illegal characters with questionmarks
  492. if (character > 0x10FFFF) { character = U'?'; }
  493. if (character < (1 << 7)) {
  494. // 0xxxxxxx
  495. receiver(character);
  496. } else if (character < (1 << 11)) {
  497. // 110xxxxx 10xxxxxx
  498. receiver((uint32_t)0b11000000 | ((character & ((uint32_t)0b11111 << 6)) >> 6));
  499. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  500. } else if (character < (1 << 16)) {
  501. // 1110xxxx 10xxxxxx 10xxxxxx
  502. receiver((uint32_t)0b11100000 | ((character & ((uint32_t)0b1111 << 12)) >> 12));
  503. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  504. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  505. } else if (character < (1 << 21)) {
  506. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  507. receiver((uint32_t)0b11110000 | ((character & ((uint32_t)0b111 << 18)) >> 18));
  508. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 12)) >> 12));
  509. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  510. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  511. }
  512. } else { // Assuming UTF-16
  513. if (character > 0x10FFFF) { character = U'?'; }
  514. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  515. // xxxxxxxx xxxxxxxx (Limited range)
  516. uint32_t higher8Bits = (character & (uint32_t)0b1111111100000000) >> 8;
  517. uint32_t lower8Bits = character & (uint32_t)0b0000000011111111;
  518. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  519. receiver(higher8Bits);
  520. receiver(lower8Bits);
  521. } else { // Assuming UTF-16 LE
  522. receiver(lower8Bits);
  523. receiver(higher8Bits);
  524. }
  525. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  526. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  527. uint32_t code = character - (uint32_t)0x10000;
  528. uint32_t byteA = ((code & (uint32_t)0b11000000000000000000) >> 18) | (uint32_t)0b11011000;
  529. uint32_t byteB = (code & (uint32_t)0b00111111110000000000) >> 10;
  530. uint32_t byteC = ((code & (uint32_t)0b00000000001100000000) >> 8) | (uint32_t)0b11011100;
  531. uint32_t byteD = code & (uint32_t)0b00000000000011111111;
  532. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  533. receiver(byteA);
  534. receiver(byteB);
  535. receiver(byteC);
  536. receiver(byteD);
  537. } else { // Assuming UTF-16 LE
  538. receiver(byteB);
  539. receiver(byteA);
  540. receiver(byteD);
  541. receiver(byteC);
  542. }
  543. }
  544. }
  545. }
  546. // Template for encoding a whole string
  547. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  548. static void encodeText(const ByteWriterFunction &receiver, String content) {
  549. // Write byte order marks
  550. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  551. receiver(0xEF);
  552. receiver(0xBB);
  553. receiver(0xBF);
  554. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  555. receiver(0xFE);
  556. receiver(0xFF);
  557. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  558. receiver(0xFF);
  559. receiver(0xFE);
  560. }
  561. // Write encoded content
  562. for (int i = 0; i < string_length(content); i++) {
  563. DsrChar character = content[i];
  564. if (character == U'\n') {
  565. if (lineEncoding == LineEncoding::CrLf) {
  566. encodeCharacter<characterEncoding>(receiver, U'\r');
  567. encodeCharacter<characterEncoding>(receiver, U'\n');
  568. } else { // Assuming that lineEncoding == LineEncoding::Lf
  569. encodeCharacter<characterEncoding>(receiver, U'\n');
  570. }
  571. } else {
  572. encodeCharacter<characterEncoding>(receiver, character);
  573. }
  574. }
  575. }
  576. // Macro for converting run-time arguments into template arguments for encodeText
  577. #define ENCODE_TEXT(RECEIVER, CONTENT, CHAR_ENCODING, LINE_ENCODING) \
  578. if (CHAR_ENCODING == CharacterEncoding::Raw_Latin1) { \
  579. if (LINE_ENCODING == LineEncoding::CrLf) { \
  580. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  581. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  582. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::Lf>(RECEIVER, CONTENT); \
  583. } \
  584. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF8) { \
  585. if (LINE_ENCODING == LineEncoding::CrLf) { \
  586. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  587. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  588. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::Lf>(RECEIVER, CONTENT); \
  589. } \
  590. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16BE) { \
  591. if (LINE_ENCODING == LineEncoding::CrLf) { \
  592. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  593. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  594. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::Lf>(RECEIVER, CONTENT); \
  595. } \
  596. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16LE) { \
  597. if (LINE_ENCODING == LineEncoding::CrLf) { \
  598. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  599. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  600. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::Lf>(RECEIVER, CONTENT); \
  601. } \
  602. }
  603. // TODO: Encoding to a buffer first and sending it all at once will be faster on certain operating systems
  604. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  605. // TODO: Load files using Unicode filenames
  606. TO_RAW_ASCII(asciiFilename, filename);
  607. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  608. ByteWriterFunction receiver = [&fileStream](uint8_t value) {
  609. fileStream.write((const char*)&value, 1);
  610. };
  611. if (fileStream.is_open()) {
  612. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding);
  613. fileStream.close();
  614. } else {
  615. throwError("Failed to save ", filename, "\n");
  616. }
  617. }
  618. Buffer dsr::string_saveToMemory(const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  619. int64_t byteCount = 0;
  620. ByteWriterFunction counter = [&byteCount](uint8_t value) {
  621. byteCount++;
  622. };
  623. ENCODE_TEXT(counter, content, characterEncoding, lineEncoding);
  624. Buffer result = buffer_create(byteCount);
  625. SafePointer<uint8_t> byteWriter = buffer_getSafeData<uint8_t>(result, "Buffer for string encoding");
  626. ByteWriterFunction receiver = [&byteWriter](uint8_t value) {
  627. *byteWriter = value;
  628. byteWriter += 1;
  629. };
  630. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding);
  631. return result;
  632. }
  633. const char32_t* dsr::file_separator() {
  634. #ifdef _WIN32
  635. return U"\\";
  636. #else
  637. return U"/";
  638. #endif
  639. }
  640. int ReadableString::length() const {
  641. return this->sectionLength;
  642. }
  643. bool ReadableString::checkBound(int start, int length, bool warning) const {
  644. if (start < 0 || start + length > this->length()) {
  645. if (warning) {
  646. String message;
  647. string_append(message, U"\n");
  648. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  649. string_append(message, U"/\n");
  650. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  651. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  652. string_append(message, U"\\_______________________________________________________________________\n");
  653. throwError(message);
  654. }
  655. return false;
  656. } else {
  657. return true;
  658. }
  659. }
  660. DsrChar ReadableString::read(int index) const {
  661. if (index < 0 || index >= this->sectionLength) {
  662. return '\0';
  663. } else {
  664. return this->readSection[index];
  665. }
  666. }
  667. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  668. ReadableString::ReadableString() {}
  669. ReadableString::~ReadableString() {}
  670. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  671. : readSection(content), sectionLength(sectionLength) {}
  672. ReadableString::ReadableString(const DsrChar *content)
  673. : readSection(content), sectionLength(strlen_utf32(content)) {}
  674. String::String() {}
  675. String::String(const char* source) { this->append(source); }
  676. String::String(const char32_t* source) { this->append(source); }
  677. String::String(const std::string& source) { this->append(source); }
  678. String::String(const ReadableString& source) { this->append(source); }
  679. String::String(const String& source) { this->append(source); }
  680. String::String(Buffer buffer, DsrChar *content, int sectionLength)
  681. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  682. int String::capacity() {
  683. if (this->buffer.get() == nullptr) {
  684. return 0;
  685. } else {
  686. // Get the parent allocation
  687. uint8_t* parentBuffer = buffer_dangerous_getUnsafeData(this->buffer);
  688. // Get the offset from the parent
  689. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  690. // Subtract offset from the buffer size to get the remaining space
  691. return (buffer_getSize(this->buffer) - offset) / sizeof(DsrChar);
  692. }
  693. }
  694. ReadableString ReadableString::getRange(int start, int length) const {
  695. if (length < 1) {
  696. return ReadableString();
  697. } else if (this->checkBound(start, length)) {
  698. return ReadableString(&(this->readSection[start]), length);
  699. } else {
  700. return ReadableString();
  701. }
  702. }
  703. ReadableString String::getRange(int start, int length) const {
  704. if (length < 1) {
  705. return ReadableString();
  706. } else if (this->checkBound(start, length)) {
  707. return String(this->buffer, &(this->writeSection[start]), length);
  708. } else {
  709. return ReadableString();
  710. }
  711. }
  712. static int32_t getNewBufferSize(int32_t minimumSize) {
  713. if (minimumSize <= 128) {
  714. return 128;
  715. } else if (minimumSize <= 512) {
  716. return 512;
  717. } else if (minimumSize <= 2048) {
  718. return 2048;
  719. } else if (minimumSize <= 8192) {
  720. return 8192;
  721. } else if (minimumSize <= 32768) {
  722. return 32768;
  723. } else if (minimumSize <= 131072) {
  724. return 131072;
  725. } else if (minimumSize <= 524288) {
  726. return 524288;
  727. } else if (minimumSize <= 2097152) {
  728. return 2097152;
  729. } else if (minimumSize <= 8388608) {
  730. return 8388608;
  731. } else if (minimumSize <= 33554432) {
  732. return 33554432;
  733. } else if (minimumSize <= 134217728) {
  734. return 134217728;
  735. } else if (minimumSize <= 536870912) {
  736. return 536870912;
  737. } else {
  738. return 2147483647;
  739. }
  740. }
  741. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  742. // Holding oldData alive while copying to the new buffer
  743. Buffer oldBuffer = this->buffer;
  744. const char32_t* oldData = this->readSection;
  745. this->buffer = buffer_create(getNewBufferSize(newLength * sizeof(DsrChar)));
  746. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(buffer_dangerous_getUnsafeData(this->buffer));
  747. if (preserve && oldData) {
  748. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  749. }
  750. }
  751. // Call before writing to the buffer
  752. // This hides that Strings share buffers when assigning by value or taking partial strings
  753. void String::cloneIfShared() {
  754. if (this->buffer.use_count() > 1) {
  755. this->reallocateBuffer(this->sectionLength, true);
  756. }
  757. }
  758. void String::expand(int32_t newLength, bool affectUsedLength) {
  759. if (newLength > this->sectionLength) {
  760. if (newLength > this->capacity()) {
  761. this->reallocateBuffer(newLength, true);
  762. }
  763. }
  764. if (affectUsedLength) {
  765. this->sectionLength = newLength;
  766. }
  767. }
  768. void String::reserve(int32_t minimumLength) {
  769. this->expand(minimumLength, false);
  770. }
  771. void String::write(int index, DsrChar value) {
  772. this->cloneIfShared();
  773. if (index < 0 || index >= this->sectionLength) {
  774. // TODO: Give a warning
  775. } else {
  776. this->writeSection[index] = value;
  777. }
  778. }
  779. void String::clear() {
  780. this->sectionLength = 0;
  781. }
  782. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  783. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  784. // Proof that appending to one string doesn't affect another:
  785. // If it has to reallocate
  786. // * Then it will have its own buffer without conflicts
  787. // If it doesn't have to reallocate
  788. // If it shares the buffer
  789. // If source is empty
  790. // * Then no risk of overwriting neighbor strings if we don't write
  791. // If source isn't empty
  792. // * Then the buffer will be cloned when the first character is written
  793. // If it doesn't share the buffer
  794. // * Then no risk of writing
  795. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  796. int64_t oldLength = (TARGET)->length(); \
  797. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  798. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  799. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  800. } \
  801. }
  802. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  803. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  804. // TODO: Use memcpy when appending input of the same format
  805. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  806. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  807. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  808. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  809. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  810. return source.toStreamIndented(target, indentation);
  811. }
  812. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  813. target.append(indentation);
  814. target.append(value);
  815. return target;
  816. }
  817. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  818. target.append(indentation);
  819. target.append(value);
  820. return target;
  821. }
  822. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  823. target.append(indentation);
  824. target.append(value);
  825. return target;
  826. }
  827. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  828. target.append(indentation);
  829. target.append(value);
  830. return target;
  831. }
  832. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  833. target.append(indentation);
  834. doubleToString_arabic(target, (double)value);
  835. return target;
  836. }
  837. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  838. target.append(indentation);
  839. doubleToString_arabic(target, value);
  840. return target;
  841. }
  842. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  843. target.append(indentation);
  844. intToString_arabic(target, value);
  845. return target;
  846. }
  847. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  848. target.append(indentation);
  849. uintToString_arabic(target, value);
  850. return target;
  851. }
  852. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  853. target.append(indentation);
  854. intToString_arabic(target, (int64_t)value);
  855. return target;
  856. }
  857. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  858. target.append(indentation);
  859. uintToString_arabic(target, (uint64_t)value);
  860. return target;
  861. }
  862. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  863. target.append(indentation);
  864. intToString_arabic(target, (int64_t)value);
  865. return target;
  866. }
  867. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  868. target.append(indentation);
  869. uintToString_arabic(target, (uint64_t)value);
  870. return target;
  871. }
  872. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  873. target.append(indentation);
  874. intToString_arabic(target, (int64_t)value);
  875. return target;
  876. }
  877. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  878. target.append(indentation);
  879. uintToString_arabic(target, (uint64_t)value);
  880. return target;
  881. }
  882. void dsr::throwErrorMessage(const String& message) {
  883. throw std::runtime_error(message.toStdString());
  884. }
  885. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  886. if (!appendResult) {
  887. target.clear();
  888. }
  889. int sectionStart = 0;
  890. for (int i = 0; i < source.length(); i++) {
  891. DsrChar c = source[i];
  892. if (c == separator) {
  893. target.push(string_exclusiveRange(source, sectionStart, i));
  894. sectionStart = i + 1;
  895. }
  896. }
  897. if (source.length() > sectionStart) {
  898. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  899. }
  900. }
  901. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  902. List<ReadableString> result;
  903. string_split_inPlace(result, source, separator);
  904. return result;
  905. }
  906. int64_t dsr::string_toInteger(const ReadableString& source) {
  907. int64_t result;
  908. bool negated;
  909. result = 0;
  910. negated = false;
  911. for (int i = 0; i < source.length(); i++) {
  912. DsrChar c = source[i];
  913. if (c == '-' || c == '~') {
  914. negated = !negated;
  915. } else if (c >= '0' && c <= '9') {
  916. result = (result * 10) + (int)(c - '0');
  917. } else if (c == ',' || c == '.') {
  918. // Truncate any decimals by ignoring them
  919. break;
  920. }
  921. }
  922. if (negated) {
  923. return -result;
  924. } else {
  925. return result;
  926. }
  927. }
  928. double dsr::string_toDouble(const ReadableString& source) {
  929. double result;
  930. bool negated;
  931. bool reachedDecimal;
  932. int digitDivider;
  933. result = 0.0;
  934. negated = false;
  935. reachedDecimal = false;
  936. digitDivider = 1;
  937. for (int i = 0; i < source.length(); i++) {
  938. DsrChar c = source[i];
  939. if (c == '-' || c == '~') {
  940. negated = !negated;
  941. } else if (c >= '0' && c <= '9') {
  942. if (reachedDecimal) {
  943. digitDivider = digitDivider * 10;
  944. result = result + ((double)(c - '0') / (double)digitDivider);
  945. } else {
  946. result = (result * 10) + (double)(c - '0');
  947. }
  948. } else if (c == ',' || c == '.') {
  949. reachedDecimal = true;
  950. }
  951. }
  952. if (negated) {
  953. return -result;
  954. } else {
  955. return result;
  956. }
  957. }
  958. int dsr::string_length(const ReadableString& source) {
  959. return source.length();
  960. }
  961. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  962. for (int i = startIndex; i < source.length(); i++) {
  963. if (source[i] == toFind) {
  964. return i;
  965. }
  966. }
  967. return -1;
  968. }
  969. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  970. for (int i = source.length() - 1; i >= 0; i--) {
  971. if (source[i] == toFind) {
  972. return i;
  973. }
  974. }
  975. return -1;
  976. }
  977. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  978. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  979. }
  980. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  981. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  982. }
  983. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  984. return string_exclusiveRange(source, 0, exclusiveEnd);
  985. }
  986. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  987. return string_inclusiveRange(source, 0, inclusiveEnd);
  988. }
  989. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  990. return string_exclusiveRange(source, inclusiveStart, source.length());
  991. }
  992. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  993. return string_from(source, exclusiveStart + 1);
  994. }
  995. bool dsr::character_isDigit(DsrChar c) {
  996. return c >= U'0' && c <= U'9';
  997. }
  998. bool dsr::character_isIntegerCharacter(DsrChar c) {
  999. return c == U'-' || character_isDigit(c);
  1000. }
  1001. bool dsr::character_isValueCharacter(DsrChar c) {
  1002. return c == U'.' || character_isIntegerCharacter(c);
  1003. }
  1004. bool dsr::character_isWhiteSpace(DsrChar c) {
  1005. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  1006. }
  1007. // Macros for implementing regular expressions with a greedy approach consuming the first match
  1008. // Optional accepts 0 or 1 occurence
  1009. // Forced accepts 1 occurence
  1010. // Star accepts 0..N occurence
  1011. // Plus accepts 1..N occurence
  1012. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  1013. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  1014. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  1015. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  1016. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1017. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  1018. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1019. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  1020. // The greedy approach works here, because there's no ambiguity
  1021. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  1022. int readIndex = 0;
  1023. if (allowWhiteSpace) {
  1024. PATTERN_STAR(WhiteSpace);
  1025. }
  1026. CHARACTER_OPTIONAL(U'-');
  1027. // At least one digit required
  1028. PATTERN_PLUS(IntegerCharacter);
  1029. if (allowWhiteSpace) {
  1030. PATTERN_STAR(WhiteSpace);
  1031. }
  1032. return true;
  1033. }
  1034. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1035. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1036. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1037. if (string_findFirst(source, U'.') == -1) {
  1038. // No decimal detected
  1039. return string_isInteger(source, allowWhiteSpace);
  1040. } else {
  1041. int readIndex = 0;
  1042. if (allowWhiteSpace) {
  1043. PATTERN_STAR(WhiteSpace);
  1044. }
  1045. // Double <- UnsignedDouble | '-' UnsignedDouble
  1046. CHARACTER_OPTIONAL(U'-');
  1047. // UnsignedDouble <- Digit* '.' Digit+
  1048. // Any number of integer digits
  1049. PATTERN_STAR(IntegerCharacter);
  1050. // Only dot for decimal
  1051. CHARACTER_FORCED(U'.')
  1052. // At least one decimal digit
  1053. PATTERN_PLUS(IntegerCharacter);
  1054. if (allowWhiteSpace) {
  1055. PATTERN_STAR(WhiteSpace);
  1056. }
  1057. return true;
  1058. }
  1059. }