text.cpp 42 KB

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