stringAPI.cpp 41 KB

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