stringAPI.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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'\a') { // Audible bell
  285. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  286. } else if (c == U'\b') { // Backspace
  287. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  288. } else if (c == U'\f') { // Form feed
  289. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  290. } else if (c == U'\n') { // Line feed
  291. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  292. } else if (c == U'\r') { // Carriage return
  293. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  294. } else if (c == U'\0') { // Null terminator
  295. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  296. } else {
  297. string_appendChar(result, c);
  298. }
  299. }
  300. }
  301. }
  302. return result;
  303. }
  304. static void uintToString_arabic(String& target, uint64_t value) {
  305. static const int bufferSize = 20;
  306. DsrChar digits[bufferSize];
  307. int64_t usedSize = 0;
  308. if (value == 0) {
  309. string_appendChar(target, U'0');
  310. } else {
  311. while (usedSize < bufferSize) {
  312. DsrChar digit = U'0' + (value % 10u);
  313. digits[usedSize] = digit;
  314. usedSize++;
  315. value /= 10u;
  316. if (value == 0) {
  317. break;
  318. }
  319. }
  320. while (usedSize > 0) {
  321. usedSize--;
  322. string_appendChar(target, digits[usedSize]);
  323. }
  324. }
  325. }
  326. static void intToString_arabic(String& target, int64_t value) {
  327. if (value >= 0) {
  328. uintToString_arabic(target, (uint64_t)value);
  329. } else {
  330. string_appendChar(target, U'-');
  331. uintToString_arabic(target, (uint64_t)(-value));
  332. }
  333. }
  334. static const int MAX_DECIMALS = 16;
  335. static double decimalMultipliers[MAX_DECIMALS] = {
  336. 10.0,
  337. 100.0,
  338. 1000.0,
  339. 10000.0,
  340. 100000.0,
  341. 1000000.0,
  342. 10000000.0,
  343. 100000000.0,
  344. 1000000000.0,
  345. 10000000000.0,
  346. 100000000000.0,
  347. 1000000000000.0,
  348. 10000000000000.0,
  349. 100000000000000.0,
  350. 1000000000000000.0,
  351. 10000000000000000.0
  352. };
  353. static void doubleToString_arabic(String& target, double value, int decimalCount = 6, bool removeTrailingZeroes = true, DsrChar decimalCharacter = U'.', DsrChar negationCharacter = U'-') {
  354. if (decimalCount < 1) decimalCount = 1;
  355. if (decimalCount > MAX_DECIMALS) decimalCount = MAX_DECIMALS;
  356. double remainder = value;
  357. // Get negation
  358. if (remainder < 0.0) {
  359. string_appendChar(target, negationCharacter);
  360. remainder = -remainder;
  361. }
  362. // Get whole part
  363. uint64_t whole = (uint64_t)remainder;
  364. uintToString_arabic(target, whole);
  365. remainder = remainder - whole;
  366. // Print the decimal
  367. string_appendChar(target, decimalCharacter);
  368. // Get decimals
  369. uint64_t scaledDecimals = (uint64_t)((remainder * decimalMultipliers[decimalCount - 1]) + 0.5f);
  370. DsrChar digits[MAX_DECIMALS]; // Using 0 to decimalCount - 1
  371. int writeIndex = decimalCount - 1;
  372. for (int d = 0; d < decimalCount; d++) {
  373. int digit = scaledDecimals % 10;
  374. digits[writeIndex] = U'0' + digit;
  375. scaledDecimals = scaledDecimals / 10;
  376. writeIndex--;
  377. }
  378. if (removeTrailingZeroes) {
  379. // Find the last non-zero decimal, but keep at least one zero.
  380. int lastValue = 0;
  381. for (int d = 0; d < decimalCount; d++) {
  382. if (digits[d] != U'0') lastValue = d;
  383. }
  384. // Print until the last value or the only zero.
  385. for (int d = 0; d <= lastValue; d++) {
  386. string_appendChar(target, digits[d]);
  387. }
  388. } else {
  389. // Print fixed decimals.
  390. for (int d = 0; d < decimalCount; d++) {
  391. string_appendChar(target, digits[d]);
  392. }
  393. }
  394. }
  395. #define TO_RAW_ASCII(TARGET, SOURCE) \
  396. char TARGET[SOURCE.length + 1]; \
  397. for (int64_t i = 0; i < SOURCE.length; i++) { \
  398. TARGET[i] = toAscii(SOURCE[i]); \
  399. } \
  400. TARGET[SOURCE.length] = '\0';
  401. // A function definition for receiving a stream of bytes
  402. // Instead of using std's messy inheritance
  403. using ByteWriterFunction = std::function<void(uint8_t value)>;
  404. // A function definition for receiving a stream of UTF-32 characters
  405. // Instead of using std's messy inheritance
  406. using UTF32WriterFunction = std::function<void(DsrChar character)>;
  407. // Filter out unwanted characters for improved portability
  408. static void feedCharacter(const UTF32WriterFunction &receiver, DsrChar character) {
  409. if (character != U'\0' && character != U'\r') {
  410. receiver(character);
  411. }
  412. }
  413. // Appends the content of buffer as a BOM-free Latin-1 file into target
  414. // fileLength is ignored when nullTerminated is true
  415. template <bool nullTerminated>
  416. static void feedStringFromFileBuffer_Latin1(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength = 0) {
  417. for (int64_t i = 0; i < fileLength || nullTerminated; i++) {
  418. DsrChar character = (DsrChar)(buffer[i]);
  419. if (nullTerminated && character == 0) { return; }
  420. feedCharacter(receiver, character);
  421. }
  422. }
  423. // Appends the content of buffer as a BOM-free UTF-8 file into target
  424. // fileLength is ignored when nullTerminated is true
  425. template <bool nullTerminated>
  426. static void feedStringFromFileBuffer_UTF8(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength = 0) {
  427. for (int64_t i = 0; i < fileLength || nullTerminated; i++) {
  428. uint8_t byteA = buffer[i];
  429. if (byteA < (uint32_t)0b10000000) {
  430. // Single byte (1xxxxxxx)
  431. if (nullTerminated && byteA == 0) { return; }
  432. feedCharacter(receiver, (DsrChar)byteA);
  433. } else {
  434. uint32_t character = 0;
  435. int extraBytes = 0;
  436. if (byteA >= (uint32_t)0b11000000) { // At least two leading ones
  437. if (byteA < (uint32_t)0b11100000) { // Less than three leading ones
  438. character = byteA & (uint32_t)0b00011111;
  439. extraBytes = 1;
  440. } else if (byteA < (uint32_t)0b11110000) { // Less than four leading ones
  441. character = byteA & (uint32_t)0b00001111;
  442. extraBytes = 2;
  443. } else if (byteA < (uint32_t)0b11111000) { // Less than five leading ones
  444. character = byteA & (uint32_t)0b00000111;
  445. extraBytes = 3;
  446. } else {
  447. // Invalid UTF-8 format
  448. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  449. }
  450. } else {
  451. // Invalid UTF-8 format
  452. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  453. }
  454. while (extraBytes > 0) {
  455. i += 1; uint32_t nextByte = buffer[i];
  456. character = (character << 6) | (nextByte & 0b00111111);
  457. extraBytes--;
  458. }
  459. feedCharacter(receiver, (DsrChar)character);
  460. }
  461. }
  462. }
  463. template <bool LittleEndian>
  464. uint16_t read16bits(const uint8_t* buffer, int64_t startOffset) {
  465. uint16_t byteA = buffer[startOffset];
  466. uint16_t byteB = buffer[startOffset + 1];
  467. if (LittleEndian) {
  468. return (byteB << 8) | byteA;
  469. } else {
  470. return (byteA << 8) | byteB;
  471. }
  472. }
  473. // Appends the content of buffer as a BOM-free UTF-16 file into target as UTF-32
  474. // fileLength is ignored when nullTerminated is true
  475. template <bool LittleEndian, bool nullTerminated>
  476. static void feedStringFromFileBuffer_UTF16(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength = 0) {
  477. for (int64_t i = 0; i < fileLength || nullTerminated; i += 2) {
  478. // Read the first 16-bit word
  479. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  480. // Check if another word is needed
  481. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  482. // we can just check if it's within the range reserved for 32-bit encoding
  483. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  484. // Not in the reserved range, just a single 16-bit character
  485. if (nullTerminated && wordA == 0) { return; }
  486. feedCharacter(receiver, (DsrChar)wordA);
  487. } else {
  488. // The given range was reserved and therefore using 32 bits
  489. i += 2;
  490. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  491. uint32_t higher10Bits = wordA & (uint32_t)0b1111111111;
  492. uint32_t lower10Bits = wordB & (uint32_t)0b1111111111;
  493. DsrChar finalChar = (DsrChar)(((higher10Bits << 10) | lower10Bits) + (uint32_t)0x10000);
  494. feedCharacter(receiver, finalChar);
  495. }
  496. }
  497. }
  498. // Sends the decoded UTF-32 characters from the encoded buffer into target.
  499. // The text encoding should be specified using a BOM at the start of buffer, otherwise Latin-1 is assumed.
  500. static void feedStringFromFileBuffer(const UTF32WriterFunction &receiver, const uint8_t* buffer, int64_t fileLength) {
  501. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  502. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  503. feedStringFromFileBuffer_UTF8<false>(receiver, buffer + 3, fileLength - 3);
  504. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  505. feedStringFromFileBuffer_UTF16<false, false>(receiver, buffer + 2, fileLength - 2);
  506. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  507. feedStringFromFileBuffer_UTF16<true, false>(receiver, buffer + 2, fileLength - 2);
  508. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  509. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  510. throwError(U"UTF-32 BE format is not yet supported!\n");
  511. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  512. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  513. throwError(U"UTF-32 LE format is not yet supported!\n");
  514. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  515. //feedStringFromFileBuffer_UTF1(receiver, buffer + 3, fileLength - 3);
  516. throwError(U"UTF-1 format is not yet supported!\n");
  517. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  518. //feedStringFromFileBuffer_SCSU(receiver, buffer + 3, fileLength - 3);
  519. throwError(U"SCSU format is not yet supported!\n");
  520. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  521. //feedStringFromFileBuffer_BOCU-1(receiver, buffer + 3, fileLength - 3);
  522. throwError(U"BOCU-1 format is not yet supported!\n");
  523. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  524. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  525. throwError(U"UTF-7 format is not yet supported!\n");
  526. } else {
  527. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  528. feedStringFromFileBuffer_Latin1<false>(receiver, buffer, fileLength);
  529. }
  530. }
  531. // Sends the decoded UTF-32 characters from the encoded null terminated buffer into target.
  532. // buffer may not contain any BOM, and must be null terminated in the specified encoding.
  533. static void feedStringFromRawData(const UTF32WriterFunction &receiver, const uint8_t* buffer, CharacterEncoding encoding) {
  534. if (encoding == CharacterEncoding::Raw_Latin1) {
  535. feedStringFromFileBuffer_Latin1<true>(receiver, buffer);
  536. } else if (encoding == CharacterEncoding::BOM_UTF8) {
  537. feedStringFromFileBuffer_UTF8<true>(receiver, buffer);
  538. } else if (encoding == CharacterEncoding::BOM_UTF16BE) {
  539. feedStringFromFileBuffer_UTF16<false, true>(receiver, buffer);
  540. } else if (encoding == CharacterEncoding::BOM_UTF16LE) {
  541. feedStringFromFileBuffer_UTF16<true, true>(receiver, buffer);
  542. } else {
  543. throwError("Unhandled encoding in feedStringFromRawData!\n");
  544. }
  545. }
  546. String dsr::string_dangerous_decodeFromData(const void* data, CharacterEncoding encoding) {
  547. String result;
  548. // Measure the size of the result by scanning the content in advance
  549. int64_t characterCount = 0;
  550. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  551. characterCount++;
  552. };
  553. feedStringFromRawData(measurer, (const uint8_t*)data, encoding);
  554. // Pre-allocate the correct amount of memory based on the simulation
  555. string_reserve(result, characterCount);
  556. // Stream output to the result string
  557. UTF32WriterFunction receiver = [&result](DsrChar character) {
  558. string_appendChar(result, character);
  559. };
  560. feedStringFromRawData(receiver, (const uint8_t*)data, encoding);
  561. return result;
  562. }
  563. String dsr::string_loadFromMemory(Buffer fileContent) {
  564. String result;
  565. // Measure the size of the result by scanning the content in advance
  566. int64_t characterCount = 0;
  567. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  568. characterCount++;
  569. };
  570. feedStringFromFileBuffer(measurer, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  571. // Pre-allocate the correct amount of memory based on the simulation
  572. string_reserve(result, characterCount);
  573. // Stream output to the result string
  574. UTF32WriterFunction receiver = [&result](DsrChar character) {
  575. string_appendChar(result, character);
  576. };
  577. feedStringFromFileBuffer(receiver, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  578. return result;
  579. }
  580. // Loads a text file of unknown format
  581. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines
  582. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  583. Buffer encoded = file_loadBuffer(filename, mustExist);
  584. if (!buffer_exists(encoded)) {
  585. return String();
  586. } else {
  587. return string_loadFromMemory(encoded);
  588. }
  589. }
  590. template <CharacterEncoding characterEncoding>
  591. static void encodeCharacter(const ByteWriterFunction &receiver, DsrChar character) {
  592. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  593. // Replace any illegal characters with questionmarks
  594. if (character > 255) { character = U'?'; }
  595. receiver(character);
  596. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  597. // Replace any illegal characters with questionmarks
  598. if (character > 0x10FFFF) { character = U'?'; }
  599. if (character < (1 << 7)) {
  600. // 0xxxxxxx
  601. receiver(character);
  602. } else if (character < (1 << 11)) {
  603. // 110xxxxx 10xxxxxx
  604. receiver((uint32_t)0b11000000 | ((character & ((uint32_t)0b11111 << 6)) >> 6));
  605. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  606. } else if (character < (1 << 16)) {
  607. // 1110xxxx 10xxxxxx 10xxxxxx
  608. receiver((uint32_t)0b11100000 | ((character & ((uint32_t)0b1111 << 12)) >> 12));
  609. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  610. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  611. } else if (character < (1 << 21)) {
  612. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  613. receiver((uint32_t)0b11110000 | ((character & ((uint32_t)0b111 << 18)) >> 18));
  614. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 12)) >> 12));
  615. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  616. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  617. }
  618. } else { // Assuming UTF-16
  619. if (character > 0x10FFFF) { character = U'?'; }
  620. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  621. // xxxxxxxx xxxxxxxx (Limited range)
  622. uint32_t higher8Bits = (character & (uint32_t)0b1111111100000000) >> 8;
  623. uint32_t lower8Bits = character & (uint32_t)0b0000000011111111;
  624. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  625. receiver(higher8Bits);
  626. receiver(lower8Bits);
  627. } else { // Assuming UTF-16 LE
  628. receiver(lower8Bits);
  629. receiver(higher8Bits);
  630. }
  631. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  632. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  633. uint32_t code = character - (uint32_t)0x10000;
  634. uint32_t byteA = ((code & (uint32_t)0b11000000000000000000) >> 18) | (uint32_t)0b11011000;
  635. uint32_t byteB = (code & (uint32_t)0b00111111110000000000) >> 10;
  636. uint32_t byteC = ((code & (uint32_t)0b00000000001100000000) >> 8) | (uint32_t)0b11011100;
  637. uint32_t byteD = code & (uint32_t)0b00000000000011111111;
  638. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  639. receiver(byteA);
  640. receiver(byteB);
  641. receiver(byteC);
  642. receiver(byteD);
  643. } else { // Assuming UTF-16 LE
  644. receiver(byteB);
  645. receiver(byteA);
  646. receiver(byteD);
  647. receiver(byteC);
  648. }
  649. }
  650. }
  651. }
  652. // Template for encoding a whole string
  653. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  654. static void encodeText(const ByteWriterFunction &receiver, String content, bool writeBOM, bool writeNullTerminator) {
  655. if (writeBOM) {
  656. // Write byte order marks
  657. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  658. receiver(0xEF);
  659. receiver(0xBB);
  660. receiver(0xBF);
  661. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  662. receiver(0xFE);
  663. receiver(0xFF);
  664. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  665. receiver(0xFF);
  666. receiver(0xFE);
  667. }
  668. }
  669. // Write encoded content
  670. for (int64_t i = 0; i < string_length(content); i++) {
  671. DsrChar character = content[i];
  672. if (character == U'\n') {
  673. if (lineEncoding == LineEncoding::CrLf) {
  674. encodeCharacter<characterEncoding>(receiver, U'\r');
  675. encodeCharacter<characterEncoding>(receiver, U'\n');
  676. } else { // Assuming that lineEncoding == LineEncoding::Lf
  677. encodeCharacter<characterEncoding>(receiver, U'\n');
  678. }
  679. } else {
  680. encodeCharacter<characterEncoding>(receiver, character);
  681. }
  682. }
  683. if (writeNullTerminator) {
  684. // Terminate internal strings with \0 to prevent getting garbage data after unpadded buffers
  685. if (characterEncoding == CharacterEncoding::BOM_UTF16BE || characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  686. receiver(0);
  687. receiver(0);
  688. } else {
  689. receiver(0);
  690. }
  691. }
  692. }
  693. // Macro for converting run-time arguments into template arguments for encodeText
  694. #define ENCODE_TEXT(RECEIVER, CONTENT, CHAR_ENCODING, LINE_ENCODING, WRITE_BOM, WRITE_NULL_TERMINATOR) \
  695. if (CHAR_ENCODING == CharacterEncoding::Raw_Latin1) { \
  696. if (LINE_ENCODING == LineEncoding::CrLf) { \
  697. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::CrLf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  698. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  699. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::Lf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  700. } \
  701. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF8) { \
  702. if (LINE_ENCODING == LineEncoding::CrLf) { \
  703. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  704. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  705. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  706. } \
  707. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16BE) { \
  708. if (LINE_ENCODING == LineEncoding::CrLf) { \
  709. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  710. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  711. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  712. } \
  713. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16LE) { \
  714. if (LINE_ENCODING == LineEncoding::CrLf) { \
  715. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  716. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  717. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  718. } \
  719. }
  720. // Encoding to a buffer before saving all at once as a binary file.
  721. // This tells the operating system how big the file is in advance and prevent the worst case of stalling for minutes!
  722. bool dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  723. Buffer buffer = string_saveToMemory(content, characterEncoding, lineEncoding);
  724. if (buffer_exists(buffer)) {
  725. return file_saveBuffer(filename, buffer);
  726. } else {
  727. return false;
  728. }
  729. }
  730. Buffer dsr::string_saveToMemory(const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding, bool writeByteOrderMark, bool writeNullTerminator) {
  731. int64_t byteCount = 0;
  732. ByteWriterFunction counter = [&byteCount](uint8_t value) {
  733. byteCount++;
  734. };
  735. ENCODE_TEXT(counter, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  736. Buffer result = buffer_create(byteCount);
  737. SafePointer<uint8_t> byteWriter = buffer_getSafeData<uint8_t>(result, "Buffer for string encoding");
  738. ByteWriterFunction receiver = [&byteWriter](uint8_t value) {
  739. *byteWriter = value;
  740. byteWriter += 1;
  741. };
  742. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  743. return result;
  744. }
  745. static int64_t getNewBufferSize(int64_t minimumSize) {
  746. if (minimumSize <= 128) {
  747. return 128;
  748. } else if (minimumSize <= 512) {
  749. return 512;
  750. } else if (minimumSize <= 2048) {
  751. return 2048;
  752. } else if (minimumSize <= 8192) {
  753. return 8192;
  754. } else if (minimumSize <= 32768) {
  755. return 32768;
  756. } else if (minimumSize <= 131072) {
  757. return 131072;
  758. } else if (minimumSize <= 524288) {
  759. return 524288;
  760. } else if (minimumSize <= 2097152) {
  761. return 2097152;
  762. } else if (minimumSize <= 8388608) {
  763. return 8388608;
  764. } else if (minimumSize <= 33554432) {
  765. return 33554432;
  766. } else if (minimumSize <= 134217728) {
  767. return 134217728;
  768. } else if (minimumSize <= 536870912) {
  769. return 536870912;
  770. } else {
  771. return minimumSize;
  772. }
  773. }
  774. // Replaces the buffer with a new buffer holding at least newLength characters
  775. // Guarantees that the new buffer is not shared by other strings, so that it may be written to freely
  776. static void reallocateBuffer(String &target, int64_t newLength, bool preserve) {
  777. // Holding oldData alive while copying to the new buffer
  778. Buffer oldBuffer = target.buffer; // Kept for reference counting only, do not remove.
  779. const char32_t* oldData = target.readSection;
  780. target.buffer = buffer_create(getNewBufferSize(newLength * sizeof(DsrChar)));
  781. target.readSection = target.writeSection = reinterpret_cast<char32_t*>(buffer_dangerous_getUnsafeData(target.buffer));
  782. if (preserve && oldData) {
  783. memcpy(target.writeSection, oldData, target.length * sizeof(DsrChar));
  784. }
  785. }
  786. // Call before writing to the buffer
  787. // This hides that Strings share buffers when assigning by value or taking partial strings
  788. static void cloneIfShared(String &target) {
  789. if (target.buffer.use_count() > 1) {
  790. reallocateBuffer(target, target.length, true);
  791. }
  792. }
  793. void dsr::string_clear(String& target) {
  794. cloneIfShared(target);
  795. target.length = 0;
  796. }
  797. // The number of DsrChar characters that can be contained in the allocation before reaching the buffer's end
  798. // This doesn't imply that it's always okay to write to the remaining space, because the buffer may be shared
  799. static int64_t getCapacity(const ReadableString &source) {
  800. if (buffer_exists(source.buffer)) {
  801. // Get the allocation
  802. uint8_t* data = buffer_dangerous_getUnsafeData(source.buffer);
  803. uint8_t* start = (uint8_t*)(source.readSection);
  804. // Get the offset from the parent
  805. intptr_t offset = start - data;
  806. // Subtract offset from the buffer size to get the remaining space
  807. return (buffer_getSize(source.buffer) - offset) / sizeof(DsrChar);
  808. } else {
  809. return 0;
  810. }
  811. }
  812. static void expand(String &target, int64_t newLength, bool affectUsedLength) {
  813. cloneIfShared(target);
  814. if (newLength > target.length) {
  815. if (newLength > getCapacity(target)) {
  816. reallocateBuffer(target, newLength, true);
  817. }
  818. if (affectUsedLength) {
  819. target.length = newLength;
  820. }
  821. }
  822. }
  823. void dsr::string_reserve(String& target, int64_t minimumLength) {
  824. expand(target, minimumLength, false);
  825. }
  826. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  827. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  828. // Proof that appending to one string doesn't affect another:
  829. // If it has to reallocate
  830. // * Then it will have its own buffer without conflicts
  831. // If it doesn't have to reallocate
  832. // If it shares the buffer
  833. // If source is empty
  834. // * Then no risk of overwriting neighbor strings if we don't write
  835. // If source isn't empty
  836. // * Then the buffer will be cloned when the first character is written
  837. // If it doesn't share the buffer
  838. // * Then no risk of writing
  839. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  840. int64_t oldLength = (TARGET).length; \
  841. expand((TARGET), oldLength + (int64_t)(LENGTH), true); \
  842. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  843. (TARGET).writeSection[oldLength + i] = ((SOURCE)[i]) & MASK; \
  844. } \
  845. }
  846. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  847. static void atomic_append(String &target, const char* source) { APPEND(target, source, strlen(source), 0xFF); }
  848. // TODO: Use memcpy when appending input of the same format
  849. static void atomic_append(String &target, const ReadableString& source) { APPEND(target, source, source.length, 0xFFFFFFFF); }
  850. static void atomic_append(String &target, const char32_t* source) { APPEND(target, source, strlen_utf32(source), 0xFFFFFFFF); }
  851. static void atomic_append(String &target, const std::string& source) { APPEND(target, source.c_str(), (int64_t)source.size(), 0xFF); }
  852. void dsr::string_appendChar(String& target, DsrChar value) { APPEND(target, &value, 1, 0xFFFFFFFF); }
  853. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  854. return source.toStreamIndented(target, indentation);
  855. }
  856. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  857. atomic_append(target, indentation);
  858. atomic_append(target, value);
  859. return target;
  860. }
  861. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  862. atomic_append(target, indentation);
  863. atomic_append(target, value);
  864. return target;
  865. }
  866. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  867. atomic_append(target, indentation);
  868. atomic_append(target, value);
  869. return target;
  870. }
  871. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  872. atomic_append(target, indentation);
  873. atomic_append(target, value);
  874. return target;
  875. }
  876. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  877. atomic_append(target, indentation);
  878. doubleToString_arabic(target, (double)value);
  879. return target;
  880. }
  881. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  882. atomic_append(target, indentation);
  883. doubleToString_arabic(target, value);
  884. return target;
  885. }
  886. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  887. atomic_append(target, indentation);
  888. intToString_arabic(target, value);
  889. return target;
  890. }
  891. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  892. atomic_append(target, indentation);
  893. uintToString_arabic(target, value);
  894. return target;
  895. }
  896. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  897. atomic_append(target, indentation);
  898. intToString_arabic(target, (int64_t)value);
  899. return target;
  900. }
  901. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  902. atomic_append(target, indentation);
  903. uintToString_arabic(target, (uint64_t)value);
  904. return target;
  905. }
  906. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  907. atomic_append(target, indentation);
  908. intToString_arabic(target, (int64_t)value);
  909. return target;
  910. }
  911. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  912. atomic_append(target, indentation);
  913. uintToString_arabic(target, (uint64_t)value);
  914. return target;
  915. }
  916. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  917. atomic_append(target, indentation);
  918. intToString_arabic(target, (int64_t)value);
  919. return target;
  920. }
  921. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  922. atomic_append(target, indentation);
  923. uintToString_arabic(target, (uint64_t)value);
  924. return target;
  925. }
  926. static const std::function<void(const ReadableString &message, MessageType type)> defaultMessageAction = [](const ReadableString &message, MessageType type) {
  927. if (type == MessageType::Error) {
  928. throw std::runtime_error(message.toStdString());
  929. } else {
  930. message.toStream(std::cout);
  931. }
  932. };
  933. static std::function<void(const ReadableString &message, MessageType type)> globalMessageAction = defaultMessageAction;
  934. void dsr::string_sendMessage(const ReadableString &message, MessageType type) {
  935. globalMessageAction(message, type);
  936. if (type == MessageType::Error) {
  937. throw std::runtime_error("The message handler provided using string_assignMessageHandler did not throw an exception or terminate the program for the given error!\n");
  938. }
  939. }
  940. void dsr::string_sendMessage_default(const ReadableString &message, MessageType type) {
  941. defaultMessageAction(message, type);
  942. }
  943. void dsr::string_assignMessageHandler(std::function<void(const ReadableString &message, MessageType type)> newHandler) {
  944. globalMessageAction = newHandler;
  945. }
  946. void dsr::string_unassignMessageHandler() {
  947. globalMessageAction = defaultMessageAction;
  948. }
  949. void dsr::string_split_callback(std::function<void(ReadableString separatedText)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  950. int64_t sectionStart = 0;
  951. for (int64_t i = 0; i < source.length; i++) {
  952. DsrChar c = source[i];
  953. if (c == separator) {
  954. ReadableString element = string_exclusiveRange(source, sectionStart, i);
  955. if (removeWhiteSpace) {
  956. action(string_removeOuterWhiteSpace(element));
  957. } else {
  958. action(element);
  959. }
  960. sectionStart = i + 1;
  961. }
  962. }
  963. if (source.length > sectionStart) {
  964. if (removeWhiteSpace) {
  965. action(string_removeOuterWhiteSpace(string_exclusiveRange(source, sectionStart, source.length)));
  966. } else {
  967. action(string_exclusiveRange(source, sectionStart, source.length));
  968. }
  969. }
  970. }
  971. List<String> dsr::string_split(const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  972. List<String> result;
  973. String commonBuffer;
  974. if (buffer_exists(source.buffer)) {
  975. // Re-use the existing buffer
  976. commonBuffer = createSubString_shared(source.readSection, source.length, source.buffer, const_cast<char32_t*>(source.readSection));
  977. } else {
  978. // Clone the whole input into one allocation to avoid fragmenting the heap with many small allocations
  979. commonBuffer = source;
  980. }
  981. // Source is allocated as String
  982. string_split_callback([&result, removeWhiteSpace](String element) {
  983. if (removeWhiteSpace) {
  984. result.push(string_removeOuterWhiteSpace(element));
  985. } else {
  986. result.push(element);
  987. }
  988. }, commonBuffer, separator, removeWhiteSpace);
  989. return result;
  990. }
  991. int64_t dsr::string_splitCount(const ReadableString& source, DsrChar separator) {
  992. int64_t result;
  993. string_split_callback([&result](ReadableString element) {
  994. result++;
  995. }, source, separator);
  996. return result;
  997. }
  998. int64_t dsr::string_toInteger(const ReadableString& source) {
  999. int64_t result;
  1000. bool negated;
  1001. result = 0;
  1002. negated = false;
  1003. for (int64_t i = 0; i < source.length; i++) {
  1004. DsrChar c = source[i];
  1005. if (c == '-' || c == '~') {
  1006. negated = !negated;
  1007. } else if (c >= '0' && c <= '9') {
  1008. result = (result * 10) + (int)(c - '0');
  1009. } else if (c == ',' || c == '.') {
  1010. // Truncate any decimals by ignoring them
  1011. break;
  1012. }
  1013. }
  1014. if (negated) {
  1015. return -result;
  1016. } else {
  1017. return result;
  1018. }
  1019. }
  1020. double dsr::string_toDouble(const ReadableString& source) {
  1021. double result;
  1022. bool negated;
  1023. bool reachedDecimal;
  1024. int64_t digitDivider;
  1025. result = 0.0;
  1026. negated = false;
  1027. reachedDecimal = false;
  1028. digitDivider = 1;
  1029. for (int64_t i = 0; i < source.length; i++) {
  1030. DsrChar c = source[i];
  1031. if (c == '-' || c == '~') {
  1032. negated = !negated;
  1033. } else if (c >= '0' && c <= '9') {
  1034. if (reachedDecimal) {
  1035. digitDivider = digitDivider * 10;
  1036. result = result + ((double)(c - '0') / (double)digitDivider);
  1037. } else {
  1038. result = (result * 10) + (double)(c - '0');
  1039. }
  1040. } else if (c == ',' || c == '.') {
  1041. reachedDecimal = true;
  1042. }
  1043. }
  1044. if (negated) {
  1045. return -result;
  1046. } else {
  1047. return result;
  1048. }
  1049. }
  1050. int64_t dsr::string_length(const ReadableString& source) {
  1051. return source.length;
  1052. }
  1053. int64_t dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int64_t startIndex) {
  1054. for (int64_t i = startIndex; i < source.length; i++) {
  1055. if (source[i] == toFind) {
  1056. return i;
  1057. }
  1058. }
  1059. return -1;
  1060. }
  1061. int64_t dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  1062. for (int64_t i = source.length - 1; i >= 0; i--) {
  1063. if (source[i] == toFind) {
  1064. return i;
  1065. }
  1066. }
  1067. return -1;
  1068. }
  1069. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t exclusiveEnd) {
  1070. // Return empty string for each complete miss
  1071. if (inclusiveStart >= source.length || exclusiveEnd <= 0) { return ReadableString(); }
  1072. // Automatically clamping to valid range
  1073. if (inclusiveStart < 0) { inclusiveStart = 0; }
  1074. if (exclusiveEnd > source.length) { exclusiveEnd = source.length; }
  1075. // Return the overlapping interval
  1076. return createSubString(&(source.readSection[inclusiveStart]), exclusiveEnd - inclusiveStart, source.buffer);
  1077. }
  1078. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t inclusiveEnd) {
  1079. return string_exclusiveRange(source, inclusiveStart, inclusiveEnd + 1);
  1080. }
  1081. ReadableString dsr::string_before(const ReadableString& source, int64_t exclusiveEnd) {
  1082. return string_exclusiveRange(source, 0, exclusiveEnd);
  1083. }
  1084. ReadableString dsr::string_until(const ReadableString& source, int64_t inclusiveEnd) {
  1085. return string_inclusiveRange(source, 0, inclusiveEnd);
  1086. }
  1087. ReadableString dsr::string_from(const ReadableString& source, int64_t inclusiveStart) {
  1088. return string_exclusiveRange(source, inclusiveStart, source.length);
  1089. }
  1090. ReadableString dsr::string_after(const ReadableString& source, int64_t exclusiveStart) {
  1091. return string_from(source, exclusiveStart + 1);
  1092. }
  1093. bool dsr::character_isDigit(DsrChar c) {
  1094. return c >= U'0' && c <= U'9';
  1095. }
  1096. bool dsr::character_isIntegerCharacter(DsrChar c) {
  1097. return c == U'-' || character_isDigit(c);
  1098. }
  1099. bool dsr::character_isValueCharacter(DsrChar c) {
  1100. return c == U'.' || character_isIntegerCharacter(c);
  1101. }
  1102. bool dsr::character_isWhiteSpace(DsrChar c) {
  1103. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  1104. }
  1105. // Macros for implementing regular expressions with a greedy approach consuming the first match
  1106. // Optional accepts 0 or 1 occurence
  1107. // Forced accepts 1 occurence
  1108. // Star accepts 0..N occurence
  1109. // Plus accepts 1..N occurence
  1110. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  1111. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  1112. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  1113. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  1114. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1115. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  1116. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1117. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  1118. // The greedy approach works here, because there's no ambiguity
  1119. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  1120. int64_t readIndex = 0;
  1121. if (allowWhiteSpace) {
  1122. PATTERN_STAR(WhiteSpace);
  1123. }
  1124. CHARACTER_OPTIONAL(U'-');
  1125. // At least one digit required
  1126. PATTERN_PLUS(IntegerCharacter);
  1127. if (allowWhiteSpace) {
  1128. PATTERN_STAR(WhiteSpace);
  1129. }
  1130. return readIndex == source.length;
  1131. }
  1132. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1133. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1134. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1135. if (string_findFirst(source, U'.') == -1) {
  1136. // No decimal detected
  1137. return string_isInteger(source, allowWhiteSpace);
  1138. } else {
  1139. int64_t readIndex = 0;
  1140. if (allowWhiteSpace) {
  1141. PATTERN_STAR(WhiteSpace);
  1142. }
  1143. // Double <- UnsignedDouble | '-' UnsignedDouble
  1144. CHARACTER_OPTIONAL(U'-');
  1145. // UnsignedDouble <- Digit* '.' Digit+
  1146. // Any number of integer digits
  1147. PATTERN_STAR(IntegerCharacter);
  1148. // Only dot for decimal
  1149. CHARACTER_FORCED(U'.')
  1150. // At least one decimal digit
  1151. PATTERN_PLUS(IntegerCharacter);
  1152. if (allowWhiteSpace) {
  1153. PATTERN_STAR(WhiteSpace);
  1154. }
  1155. return readIndex == source.length;
  1156. }
  1157. }
  1158. int64_t dsr::string_getBufferUseCount(const ReadableString& text) {
  1159. return text.buffer.use_count();
  1160. }