text.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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. static inline void byteToStream(std::ostream &target, uint8_t value) {
  311. target.write((const char*)&value, 1);
  312. }
  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 & 0b00011111;
  347. extraBytes = 2;
  348. } else if (byteA < 0b11111000) { // Less than five leading ones
  349. character = byteA & 0b00011111;
  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(target, 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(target, 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(target, 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(target, 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(target, 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 encodeCharacterToStream(std::ostream &target, DsrChar character) {
  489. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  490. // Replace any illegal characters with questionmarks
  491. AT_MOST_BITS(8);
  492. byteToStream(target, 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. byteToStream(target, character);
  499. } else if (character < (1 << 11)) {
  500. // 110xxxxx 10xxxxxx
  501. byteToStream(target, 0b11000000 | ((character & (0b11111 << 6)) >> 6));
  502. byteToStream(target, 0b10000000 | (character & 0b111111));
  503. } else if (character < (1 << 16)) {
  504. // 1110xxxx 10xxxxxx 10xxxxxx
  505. byteToStream(target, 0b11100000 | ((character & (0b1111 << 12)) >> 12));
  506. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  507. byteToStream(target, 0b10000000 | (character & 0b111111));
  508. } else if (character < (1 << 21)) {
  509. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  510. byteToStream(target, 0b11110000 | ((character & (0b111 << 18)) >> 18));
  511. byteToStream(target, 0b10000000 | ((character & (0b111111 << 12)) >> 12));
  512. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  513. byteToStream(target, 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. byteToStream(target, higher8Bits);
  523. byteToStream(target, lower8Bits);
  524. } else { // Assuming UTF-16 LE
  525. byteToStream(target, lower8Bits);
  526. byteToStream(target, 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. byteToStream(target, byteA);
  539. byteToStream(target, byteB);
  540. byteToStream(target, byteC);
  541. byteToStream(target, byteD);
  542. } else { // Assuming UTF-16 LE
  543. byteToStream(target, byteB);
  544. byteToStream(target, byteA);
  545. byteToStream(target, byteD);
  546. byteToStream(target, byteC);
  547. }
  548. }
  549. }
  550. }
  551. // Template for writing a whole string to a file
  552. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  553. static void writeCharacterToStream(std::ostream &target, String content) {
  554. // Write byte order marks
  555. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  556. byteToStream(target, 0xEF);
  557. byteToStream(target, 0xBB);
  558. byteToStream(target, 0xBF);
  559. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  560. byteToStream(target, 0xFE);
  561. byteToStream(target, 0xFF);
  562. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  563. byteToStream(target, 0xFF);
  564. byteToStream(target, 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. encodeCharacterToStream<characterEncoding>(target, U'\r');
  572. encodeCharacterToStream<characterEncoding>(target, U'\n');
  573. } else { // Assuming that lineEncoding == LineEncoding::Lf
  574. encodeCharacterToStream<characterEncoding>(target, U'\n');
  575. }
  576. } else {
  577. encodeCharacterToStream<characterEncoding>(target, character);
  578. }
  579. }
  580. }
  581. // Macros for dynamcally selecting templates
  582. #define WRITE_TEXT_STRING(CHAR_ENCODING, LINE_ENCODING) \
  583. writeCharacterToStream<CHAR_ENCODING, LINE_ENCODING>(fileStream, content);
  584. #define WRITE_TEXT_LINE_ENCODINGS(CHAR_ENCODING) \
  585. if (lineEncoding == LineEncoding::CrLf) { \
  586. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::CrLf); \
  587. } else if (lineEncoding == LineEncoding::Lf) { \
  588. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::Lf); \
  589. }
  590. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  591. // TODO: Load files using Unicode filenames
  592. TO_RAW_ASCII(asciiFilename, filename);
  593. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  594. if (fileStream.is_open()) {
  595. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  596. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::Raw_Latin1);
  597. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  598. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF8);
  599. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  600. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16BE);
  601. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  602. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16LE);
  603. }
  604. fileStream.close();
  605. } else {
  606. throwError("Failed to save ", filename, "\n");
  607. }
  608. }
  609. const char32_t* dsr::file_separator() {
  610. #ifdef _WIN32
  611. return U"\\";
  612. #else
  613. return U"/";
  614. #endif
  615. }
  616. int ReadableString::length() const {
  617. return this->sectionLength;
  618. }
  619. bool ReadableString::checkBound(int start, int length, bool warning) const {
  620. if (start < 0 || start + length > this->length()) {
  621. if (warning) {
  622. String message;
  623. string_append(message, U"\n");
  624. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  625. string_append(message, U"/\n");
  626. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  627. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  628. string_append(message, U"\\_______________________________________________________________________\n");
  629. throwError(message);
  630. }
  631. return false;
  632. } else {
  633. return true;
  634. }
  635. }
  636. DsrChar ReadableString::read(int index) const {
  637. if (index < 0 || index >= this->sectionLength) {
  638. return '\0';
  639. } else {
  640. return this->readSection[index];
  641. }
  642. }
  643. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  644. ReadableString::ReadableString() {}
  645. ReadableString::~ReadableString() {}
  646. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  647. : readSection(content), sectionLength(sectionLength) {}
  648. ReadableString::ReadableString(const DsrChar *content)
  649. : readSection(content), sectionLength(strlen_utf32(content)) {}
  650. String::String() {}
  651. String::String(const char* source) { this->append(source); }
  652. String::String(const char32_t* source) { this->append(source); }
  653. String::String(const std::string& source) { this->append(source); }
  654. String::String(const ReadableString& source) { this->append(source); }
  655. String::String(const String& source) { this->append(source); }
  656. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  657. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  658. int String::capacity() {
  659. if (this->buffer.get() == nullptr) {
  660. return 0;
  661. } else {
  662. // Get the parent allocation
  663. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  664. // Get the offset from the parent
  665. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  666. // Subtract offset from the buffer size to get the remaining space
  667. return (this->buffer->size - offset) / sizeof(DsrChar);
  668. }
  669. }
  670. ReadableString ReadableString::getRange(int start, int length) const {
  671. if (length < 1) {
  672. return ReadableString();
  673. } else if (this->checkBound(start, length)) {
  674. return ReadableString(&(this->readSection[start]), length);
  675. } else {
  676. return ReadableString();
  677. }
  678. }
  679. ReadableString String::getRange(int start, int length) const {
  680. if (length < 1) {
  681. return ReadableString();
  682. } else if (this->checkBound(start, length)) {
  683. return String(this->buffer, &(this->writeSection[start]), length);
  684. } else {
  685. return ReadableString();
  686. }
  687. }
  688. static int32_t getNewBufferSize(int32_t minimumSize) {
  689. if (minimumSize <= 128) {
  690. return 128;
  691. } else if (minimumSize <= 512) {
  692. return 512;
  693. } else if (minimumSize <= 2048) {
  694. return 2048;
  695. } else if (minimumSize <= 8192) {
  696. return 8192;
  697. } else if (minimumSize <= 32768) {
  698. return 32768;
  699. } else if (minimumSize <= 131072) {
  700. return 131072;
  701. } else if (minimumSize <= 524288) {
  702. return 524288;
  703. } else if (minimumSize <= 2097152) {
  704. return 2097152;
  705. } else if (minimumSize <= 8388608) {
  706. return 8388608;
  707. } else if (minimumSize <= 33554432) {
  708. return 33554432;
  709. } else if (minimumSize <= 134217728) {
  710. return 134217728;
  711. } else if (minimumSize <= 536870912) {
  712. return 536870912;
  713. } else {
  714. return 2147483647;
  715. }
  716. }
  717. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  718. // Holding oldData alive while copying to the new buffer
  719. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  720. const char32_t* oldData = this->readSection;
  721. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  722. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  723. if (preserve && oldData) {
  724. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  725. }
  726. }
  727. // Call before writing to the buffer
  728. // This hides that Strings share buffers when assigning by value or taking partial strings
  729. void String::cloneIfShared() {
  730. if (this->buffer.use_count() > 1) {
  731. this->reallocateBuffer(this->sectionLength, true);
  732. }
  733. }
  734. void String::expand(int32_t newLength, bool affectUsedLength) {
  735. if (newLength > this->sectionLength) {
  736. if (newLength > this->capacity()) {
  737. this->reallocateBuffer(newLength, true);
  738. }
  739. }
  740. if (affectUsedLength) {
  741. this->sectionLength = newLength;
  742. }
  743. }
  744. void String::reserve(int32_t minimumLength) {
  745. this->expand(minimumLength, false);
  746. }
  747. void String::write(int index, DsrChar value) {
  748. this->cloneIfShared();
  749. if (index < 0 || index >= this->sectionLength) {
  750. // TODO: Give a warning
  751. } else {
  752. this->writeSection[index] = value;
  753. }
  754. }
  755. void String::clear() {
  756. this->sectionLength = 0;
  757. }
  758. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  759. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  760. // Proof that appending to one string doesn't affect another:
  761. // If it has to reallocate
  762. // * Then it will have its own buffer without conflicts
  763. // If it doesn't have to reallocate
  764. // If it shares the buffer
  765. // If source is empty
  766. // * Then no risk of overwriting neighbor strings if we don't write
  767. // If source isn't empty
  768. // * Then the buffer will be cloned when the first character is written
  769. // If it doesn't share the buffer
  770. // * Then no risk of writing
  771. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  772. int64_t oldLength = (TARGET)->length(); \
  773. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  774. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  775. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  776. } \
  777. }
  778. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  779. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  780. // TODO: Use memcpy when appending input of the same format
  781. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  782. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  783. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  784. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  785. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  786. return source.toStreamIndented(target, indentation);
  787. }
  788. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  789. target.append(indentation);
  790. target.append(value);
  791. return target;
  792. }
  793. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  794. target.append(indentation);
  795. target.append(value);
  796. return target;
  797. }
  798. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  799. target.append(indentation);
  800. target.append(value);
  801. return target;
  802. }
  803. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  804. target.append(indentation);
  805. target.append(value);
  806. return target;
  807. }
  808. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  809. target.append(indentation);
  810. doubleToString_arabic(target, (double)value);
  811. return target;
  812. }
  813. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  814. target.append(indentation);
  815. doubleToString_arabic(target, value);
  816. return target;
  817. }
  818. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  819. target.append(indentation);
  820. intToString_arabic(target, value);
  821. return target;
  822. }
  823. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  824. target.append(indentation);
  825. uintToString_arabic(target, value);
  826. return target;
  827. }
  828. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  829. target.append(indentation);
  830. intToString_arabic(target, (int64_t)value);
  831. return target;
  832. }
  833. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  834. target.append(indentation);
  835. uintToString_arabic(target, (uint64_t)value);
  836. return target;
  837. }
  838. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  839. target.append(indentation);
  840. intToString_arabic(target, (int64_t)value);
  841. return target;
  842. }
  843. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  844. target.append(indentation);
  845. uintToString_arabic(target, (uint64_t)value);
  846. return target;
  847. }
  848. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  849. target.append(indentation);
  850. intToString_arabic(target, (int64_t)value);
  851. return target;
  852. }
  853. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  854. target.append(indentation);
  855. uintToString_arabic(target, (uint64_t)value);
  856. return target;
  857. }
  858. void dsr::throwErrorMessage(const String& message) {
  859. throw std::runtime_error(message.toStdString());
  860. }
  861. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  862. if (!appendResult) {
  863. target.clear();
  864. }
  865. int sectionStart = 0;
  866. for (int i = 0; i < source.length(); i++) {
  867. DsrChar c = source[i];
  868. if (c == separator) {
  869. target.push(string_exclusiveRange(source, sectionStart, i));
  870. sectionStart = i + 1;
  871. }
  872. }
  873. if (source.length() > sectionStart) {
  874. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  875. }
  876. }
  877. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  878. List<ReadableString> result;
  879. string_split_inPlace(result, source, separator);
  880. return result;
  881. }
  882. int64_t dsr::string_toInteger(const ReadableString& source) {
  883. int64_t result;
  884. bool negated;
  885. result = 0;
  886. negated = false;
  887. for (int i = 0; i < source.length(); i++) {
  888. DsrChar c = source[i];
  889. if (c == '-' || c == '~') {
  890. negated = !negated;
  891. } else if (c >= '0' && c <= '9') {
  892. result = (result * 10) + (int)(c - '0');
  893. } else if (c == ',' || c == '.') {
  894. // Truncate any decimals by ignoring them
  895. break;
  896. }
  897. }
  898. if (negated) {
  899. return -result;
  900. } else {
  901. return result;
  902. }
  903. }
  904. double dsr::string_toDouble(const ReadableString& source) {
  905. double result;
  906. bool negated;
  907. bool reachedDecimal;
  908. int digitDivider;
  909. result = 0.0;
  910. negated = false;
  911. reachedDecimal = false;
  912. digitDivider = 1;
  913. for (int i = 0; i < source.length(); i++) {
  914. DsrChar c = source[i];
  915. if (c == '-' || c == '~') {
  916. negated = !negated;
  917. } else if (c >= '0' && c <= '9') {
  918. if (reachedDecimal) {
  919. digitDivider = digitDivider * 10;
  920. result = result + ((double)(c - '0') / (double)digitDivider);
  921. } else {
  922. result = (result * 10) + (double)(c - '0');
  923. }
  924. } else if (c == ',' || c == '.') {
  925. reachedDecimal = true;
  926. }
  927. }
  928. if (negated) {
  929. return -result;
  930. } else {
  931. return result;
  932. }
  933. }
  934. int dsr::string_length(const ReadableString& source) {
  935. return source.length();
  936. }
  937. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  938. for (int i = startIndex; i < source.length(); i++) {
  939. if (source[i] == toFind) {
  940. return i;
  941. }
  942. }
  943. return -1;
  944. }
  945. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  946. for (int i = source.length() - 1; i >= 0; i--) {
  947. if (source[i] == toFind) {
  948. return i;
  949. }
  950. }
  951. return -1;
  952. }
  953. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  954. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  955. }
  956. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  957. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  958. }
  959. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  960. return string_exclusiveRange(source, 0, exclusiveEnd);
  961. }
  962. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  963. return string_inclusiveRange(source, 0, inclusiveEnd);
  964. }
  965. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  966. return string_exclusiveRange(source, inclusiveStart, source.length());
  967. }
  968. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  969. return string_from(source, exclusiveStart + 1);
  970. }
  971. bool dsr::character_isDigit(DsrChar c) {
  972. return c >= U'0' && c <= U'9';
  973. }
  974. bool dsr::character_isIntegerCharacter(DsrChar c) {
  975. return c == U'-' || character_isDigit(c);
  976. }
  977. bool dsr::character_isValueCharacter(DsrChar c) {
  978. return c == U'.' || character_isIntegerCharacter(c);
  979. }
  980. bool dsr::character_isWhiteSpace(DsrChar c) {
  981. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  982. }
  983. // Macros for implementing regular expressions with a greedy approach consuming the first match
  984. // Optional accepts 0 or 1 occurence
  985. // Forced accepts 1 occurence
  986. // Star accepts 0..N occurence
  987. // Plus accepts 1..N occurence
  988. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  989. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  990. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  991. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  992. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  993. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  994. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  995. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  996. // The greedy approach works here, because there's no ambiguity
  997. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  998. int readIndex = 0;
  999. if (allowWhiteSpace) {
  1000. PATTERN_STAR(WhiteSpace);
  1001. }
  1002. CHARACTER_OPTIONAL(U'-');
  1003. // At least one digit required
  1004. PATTERN_PLUS(IntegerCharacter);
  1005. if (allowWhiteSpace) {
  1006. PATTERN_STAR(WhiteSpace);
  1007. }
  1008. return true;
  1009. }
  1010. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1011. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1012. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1013. if (string_findFirst(source, U'.') == -1) {
  1014. // No decimal detected
  1015. return string_isInteger(source, allowWhiteSpace);
  1016. } else {
  1017. int readIndex = 0;
  1018. if (allowWhiteSpace) {
  1019. PATTERN_STAR(WhiteSpace);
  1020. }
  1021. // Double <- UnsignedDouble | '-' UnsignedDouble
  1022. CHARACTER_OPTIONAL(U'-');
  1023. // UnsignedDouble <- Digit* '.' Digit+
  1024. // Any number of integer digits
  1025. PATTERN_STAR(IntegerCharacter);
  1026. // Only dot for decimal
  1027. CHARACTER_FORCED(U'.')
  1028. // At least one decimal digit
  1029. PATTERN_PLUS(IntegerCharacter);
  1030. if (allowWhiteSpace) {
  1031. PATTERN_STAR(WhiteSpace);
  1032. }
  1033. return true;
  1034. }
  1035. }