stringAPI.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2025 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 DSR_INTERNAL_ACCESS
  25. #include <iostream>
  26. #include <sstream>
  27. #include <fstream>
  28. #include <streambuf>
  29. #include <thread>
  30. #include <mutex>
  31. #include <stdexcept>
  32. #include <cmath>
  33. #include "stringAPI.h"
  34. #include "../api/fileAPI.h"
  35. #include "../settings.h"
  36. using namespace dsr;
  37. // The print buffer keeps its buffer size from previous printing to avoid reallocating memory every time something is printed.
  38. // It is stored separatelly for each calling thread to avoid conflicts.
  39. static thread_local String printBuffer;
  40. String &dsr::string_getPrintBuffer() {
  41. return printBuffer;
  42. }
  43. static void atomic_append_ascii(String &target, const char* source);
  44. static void atomic_append_readable(String &target, const ReadableString& source);
  45. static void atomic_append_utf32(String &target, const DsrChar* source);
  46. static intptr_t strlen_utf32(const DsrChar *content) {
  47. intptr_t length = 0;
  48. while (content[length] != 0) {
  49. length++;
  50. }
  51. return length;
  52. }
  53. static char toAscii(DsrChar c) {
  54. if (c > 127) {
  55. return '?';
  56. } else {
  57. return c;
  58. }
  59. }
  60. ReadableString::ReadableString(const DsrChar *content)
  61. : view(content, strlen_utf32(content)) {}
  62. String::String() {}
  63. String::String(const char* source) { atomic_append_ascii(*this, source); }
  64. String::String(const DsrChar* source) { atomic_append_utf32(*this, source); }
  65. String& Printable::toStream(String& target) const {
  66. return this->toStreamIndented(target, U"");
  67. }
  68. String Printable::toStringIndented(const ReadableString& indentation) const {
  69. String result;
  70. this->toStreamIndented(result, indentation);
  71. return result;
  72. }
  73. String Printable::toString() const {
  74. return this->toStringIndented(U"");
  75. }
  76. Printable::~Printable() {}
  77. // TODO: Handle the remaining Unicode characters after ȳ (563).
  78. DsrChar dsr::character_upperCase(DsrChar character) {
  79. if (U'a' <= character && character <= U'z') { // a (97) to z (122) Ascii
  80. return character - (U'a' - U'A');
  81. } else if (U'à' <= character && character <= U'ö') { // à (224) to ö (246) Latin-1
  82. return character - (U'à' - U'À');
  83. } else if (U'ø' <= character && character <= U'þ') { // ø (248) to þ (254) Latin-1
  84. return character - (U'ø' - U'Ø');
  85. } else if (character == U'ÿ') { // ÿ (255) Latin Extended-A
  86. return U'Ÿ'; // Ÿ (376)
  87. } else if (U'Ā' <= character && character <= U'ķ') { // Ā (256) to ķ (311) Latin Extended-A
  88. return character & ~DsrChar(1);
  89. } else if (U'Ĺ' <= character && character <= U'ň' && !(character & 1)) { // Even from Ĺ (313) to ň (328) Latin Extended-A
  90. return character - 1;
  91. } else if (U'Ŋ' <= character && character <= U'ŷ') { // Ŋ (330) to ŷ (375) Latin Extended-A
  92. return character & ~DsrChar(1);
  93. } else if (character == U'ź') { // ź (378) Latin Extended-A
  94. return U'Ź'; // Ź (377)
  95. } else if (character == U'ż') { // ż (380) Latin Extended-A
  96. return U'Ż'; // Ż (379)
  97. } else if (character == U'ž') { // ž (382) Latin Extended-A
  98. return U'Ž'; // Ž (381)
  99. } else if (character == U'ƃ') { // ƃ (387) Latin Extended-B
  100. return U'Ƃ'; // Ƃ (386)
  101. } else if (character == U'ƅ') { // ƅ (389) Latin Extended-B
  102. return U'Ƅ'; // Ƅ (388)
  103. } else if (character == U'ƈ') { // ƈ (392) Latin Extended-B
  104. return U'Ƈ'; // Ƈ (391)
  105. } else if (character == U'ƌ') { // ƌ (396) Latin Extended-B
  106. return U'Ƌ'; // Ƌ (395)
  107. } else if (character == U'ƒ') { // ƒ (402) Latin Extended-B
  108. return U'Ƒ'; // Ƒ (401)
  109. } else if (character == U'ƙ') { // ƙ (409) Latin Extended-B
  110. return U'Ƙ'; // Ƙ (408)
  111. } else if (character == U'ơ') { // ơ (417) Latin Extended-B
  112. return U'Ơ'; // Ơ (416)
  113. } else if (character == U'ƣ') { // ƣ (419) Latin Extended-B
  114. return U'Ƣ'; // Ƣ (418)
  115. } else if (character == U'ƥ') { // ƥ (421) Latin Extended-B
  116. return U'Ƥ'; // Ƥ (420)
  117. } else if (character == U'ƨ') { // ƨ (424) Latin Extended-B
  118. return U'Ƨ'; // Ƨ (423)
  119. } else if (character == U'ƭ') { // ƭ (429) Latin Extended-B
  120. return U'Ƭ'; // Ƭ (428)
  121. } else if (character == U'ư') { // ư (432) Latin Extended-B
  122. return U'Ư'; // Ư (431)
  123. } else if (character == U'ƴ') { // ƴ (436) Latin Extended-B
  124. return U'Ƴ'; // Ƴ (435)
  125. } else if (character == U'ƶ') { // ƶ (438) Latin Extended-B
  126. return U'Ƶ'; // Ƶ (437)
  127. } else if (character == U'ƹ') { // ƹ (441) Latin Extended-B
  128. return U'Ƹ'; // Ƹ (440)
  129. } else if (character == U'ƽ') { // ƽ (445) Latin Extended-B
  130. return U'Ƽ'; // Ƽ (444)
  131. } else if (character == U'dž' || character == U'Dž') { // dž, Dž (454, 453) Latin Extended-B
  132. return U'DŽ'; // DŽ (454)
  133. } else if (character == U'lj' || character == U'Lj') { // lj, Lj (457, 456) Latin Extended-B
  134. return U'LJ'; // LJ (457)
  135. } else if (character == U'nj' || character == U'Nj') { // nj, Nj (460, 459) Latin Extended-B
  136. return U'NJ'; // NJ (460)
  137. } else if (U'Ǎ' <= character && character <= U'ǜ' && !(character & 1)) { // Even from Ǎ (461) to ǜ (476) Latin Extended-B Pinyin
  138. return character - 1;
  139. // Unhandled: ǝ (477)
  140. } else if (U'Ǟ' <= character && character <= U'ǯ') { // Ǟ (478) to ǯ (495) Latin Extended-B
  141. return character & ~DsrChar(1);
  142. // Unhandled: ǰ (496)
  143. } else if (character == U'dz' || character == U'Dz') { // dž, Dž (499, 498) Latin Extended-B
  144. return U'DZ'; // DŽ (497)
  145. } else if (character == U'ǵ') { // ǵ (501) Latin Extended-B
  146. return U'Ǵ'; // Ǵ (500)
  147. // Unhandled: Ƕ Ƿ
  148. } else if (U'Ǹ' <= character && character <= U'ȳ') { // Ǹ (504) to ȳ (563) Latin Extended-B
  149. return character & ~DsrChar(1);
  150. } else {
  151. return character;
  152. }
  153. }
  154. DsrChar dsr::character_lowerCase(DsrChar character) {
  155. if (U'A' <= character && character <= U'Z') { // A (65) to Z (90) Ascii
  156. return character + (U'a' - U'A');
  157. } else if (U'À' <= character && character <= U'Ö') { // À (192) to Ö (214) Latin-1
  158. return character + (U'à' - U'À');
  159. } else if (U'Ø' <= character && character <= U'Þ') { // Ø (216) to Þ (222) Latin-1
  160. return character + (U'ø' - U'Ø');
  161. } else if (character == U'Ÿ') { // Ÿ (376) Latin Extended-A
  162. return U'ÿ'; // ÿ (255)
  163. } else if (U'Ā' <= character && character <= U'ķ') { // Ā (256) to ķ (311) Latin Extended-A
  164. return character | DsrChar(1);
  165. } else if (U'Ĺ' <= character && character <= U'ň' && character & 1) { // Odd from Ĺ (313) to ň (328) Latin Extended-A
  166. return character + 1;
  167. } else if (U'Ŋ' <= character && character <= U'ŷ') { // Ŋ (330) to ŷ (375) Latin Extended-A
  168. return character | DsrChar(1);
  169. } else if (character == U'Ź') { // Ź (377) Latin Extended-A
  170. return U'ź'; // ź (378)
  171. } else if (character == U'Ż') { // Ż (379) Latin Extended-A
  172. return U'ż'; // ż (380)
  173. } else if (character == U'Ž') { // Ž (381) Latin Extended-A
  174. return U'ž'; // ž (382)
  175. } else if (character == U'Ƃ') { // Ƃ (386) Latin Extended-B
  176. return U'ƃ'; // ƃ (387)
  177. } else if (character == U'Ƅ') { // Ƅ (388) Latin Extended-B
  178. return U'ƅ'; // ƅ (389)
  179. } else if (character == U'Ƈ') { // Ƈ (391) Latin Extended-B
  180. return U'ƈ'; // ƈ (392)
  181. } else if (character == U'Ƌ') { // Ƌ (395) Latin Extended-B
  182. return U'ƌ'; // ƌ (396)
  183. } else if (character == U'Ƒ') { // Ƒ (401) Latin Extended-B
  184. return U'ƒ'; // ƒ (402)
  185. } else if (character == U'Ƙ') { // Ƙ (408) Latin Extended-B
  186. return U'ƙ'; // ƙ (409)
  187. } else if (character == U'Ơ') { // Ơ (416) Latin Extended-B
  188. return U'ơ'; // ơ (417)
  189. } else if (character == U'Ƣ') { // Ƣ (418) Latin Extended-B
  190. return U'ƣ'; // ƣ (419)
  191. } else if (character == U'Ƥ') { // Ƥ (420) Latin Extended-B
  192. return U'ƥ'; // ƥ (421)
  193. } else if (character == U'Ƨ') { // Ƨ (423) Latin Extended-B
  194. return U'ƨ'; // ƨ (424)
  195. } else if (character == U'Ƭ') { // Ƭ (428) Latin Extended-B
  196. return U'ƭ'; // ƭ (429)
  197. } else if (character == U'Ư') { // Ư (431) Latin Extended-B
  198. return U'ư'; // ư (432)
  199. } else if (character == U'Ƴ') { // Ƴ (435) Latin Extended-B
  200. return U'ƴ'; // ƴ (436)
  201. } else if (character == U'Ƶ') { // Ƶ (437) Latin Extended-B
  202. return U'ƶ'; // ƶ (438)
  203. } else if (character == U'Ƹ') { // Ƹ (440) Latin Extended-B
  204. return U'ƹ'; // ƹ (441)
  205. } else if (character == U'Ƽ') { // Ƽ (444) Latin Extended-B
  206. return U'ƽ'; // ƽ (445)
  207. } else if (character == U'DŽ' || character == U'Dž') { // DŽ, Dž (452, 453) Latin Extended-B
  208. return U'dž'; // dž (454)
  209. } else if (character == U'LJ' || character == U'Lj') { // LJ, Lj (455, 456) Latin Extended-B
  210. return U'lj'; // lj (457)
  211. } else if (character == U'NJ' || character == U'Nj') { // NJ, Nj (458, 459) Latin Extended-B
  212. return U'nj'; // nj (460)
  213. } else if (U'Ǎ' <= character && character <= U'ǜ' && character & 1) { // Odd from Ǎ (461) to ǜ (476) Latin Extended-B Pinyin
  214. return character + 1;
  215. } else if (U'Ǟ' <= character && character <= U'ǯ') { // Ǟ (478) to ǯ (495) Latin Extended-B
  216. return character & DsrChar(1);
  217. } else if (character == U'DZ' || character == U'Dz') { // DŽ, Dž (497, 498) Latin Extended-B
  218. return U'dz'; // DŽdz499)
  219. } else if (character == U'Ǵ') { // Ǵ (500) Latin Extended-B
  220. return U'ǵ'; // ǵ (501)
  221. } else if (U'Ǹ' <= character && character <= U'ȳ') { // Ǹ (504) to ȳ (563) Latin Extended-B
  222. return character & DsrChar(1);
  223. } else {
  224. return character;
  225. }
  226. }
  227. String dsr::string_upperCase(const ReadableString &text) {
  228. String result;
  229. string_reserve(result, text.view.length);
  230. for (intptr_t i = 0; i < text.view.length; i++) {
  231. string_appendChar(result, character_upperCase(text[i]));
  232. }
  233. return result;
  234. }
  235. String dsr::string_lowerCase(const ReadableString &text) {
  236. String result;
  237. string_reserve(result, text.view.length);
  238. for (intptr_t i = 0; i < text.view.length; i++) {
  239. string_appendChar(result, character_lowerCase(text[i]));
  240. }
  241. return result;
  242. }
  243. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  244. if (a.view.length != b.view.length) {
  245. return false;
  246. } else {
  247. for (intptr_t i = 0; i < a.view.length; i++) {
  248. if (a[i] != b[i]) {
  249. return false;
  250. }
  251. }
  252. return true;
  253. }
  254. }
  255. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  256. if (a.view.length != b.view.length) {
  257. return false;
  258. } else {
  259. for (intptr_t i = 0; i < a.view.length; i++) {
  260. if (character_upperCase(a[i]) != character_upperCase(b[i])) {
  261. return false;
  262. }
  263. }
  264. return true;
  265. }
  266. }
  267. static intptr_t findFirstNonWhite(const ReadableString &text) {
  268. for (intptr_t i = 0; i < text.view.length; i++) {
  269. DsrChar c = text[i];
  270. if (!character_isWhiteSpace(c)) {
  271. return i;
  272. }
  273. }
  274. return -1;
  275. }
  276. static intptr_t findLastNonWhite(const ReadableString &text) {
  277. for (intptr_t i = text.view.length - 1; i >= 0; i--) {
  278. DsrChar c = text[i];
  279. if (!character_isWhiteSpace(c)) {
  280. return i;
  281. }
  282. }
  283. return -1;
  284. }
  285. // Allow passing literals without allocating heap memory for the result
  286. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  287. intptr_t first = findFirstNonWhite(text);
  288. intptr_t last = findLastNonWhite(text);
  289. if (first == -1) {
  290. // Only white space
  291. return ReadableString();
  292. } else {
  293. // Subset
  294. return string_inclusiveRange(text, first, last);
  295. }
  296. }
  297. String dsr::string_mangleQuote(const ReadableString &rawText) {
  298. String result;
  299. string_reserve(result, rawText.view.length + 2);
  300. string_appendChar(result, U'\"'); // Begin quote
  301. for (intptr_t i = 0; i < rawText.view.length; i++) {
  302. DsrChar c = rawText[i];
  303. if (c == U'\"') { // Double quote
  304. string_append(result, U"\\\"");
  305. } else if (c == U'\\') { // Backslash
  306. string_append(result, U"\\\\");
  307. } else if (c == U'\a') { // Audible bell
  308. string_append(result, U"\\a");
  309. } else if (c == U'\b') { // Backspace
  310. string_append(result, U"\\b");
  311. } else if (c == U'\f') { // Form feed
  312. string_append(result, U"\\f");
  313. } else if (c == U'\n') { // Line feed
  314. string_append(result, U"\\n");
  315. } else if (c == U'\r') { // Carriage return
  316. string_append(result, U"\\r");
  317. } else if (c == U'\t') { // Horizontal tab
  318. string_append(result, U"\\t");
  319. } else if (c == U'\v') { // Vertical tab
  320. string_append(result, U"\\v");
  321. } else if (c == U'\0') { // Null terminator
  322. string_append(result, U"\\0");
  323. } else {
  324. string_appendChar(result, c);
  325. }
  326. }
  327. string_appendChar(result, U'\"'); // End quote
  328. return result;
  329. }
  330. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  331. intptr_t firstQuote = string_findFirst(mangledText, '\"');
  332. intptr_t lastQuote = string_findLast(mangledText, '\"');
  333. String result;
  334. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  335. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, U"\n");
  336. } else {
  337. for (intptr_t i = firstQuote + 1; i < lastQuote; i++) {
  338. DsrChar c = mangledText[i];
  339. if (c == U'\\') { // Escape character
  340. DsrChar c2 = mangledText[i + 1];
  341. if (c2 == U'\"') { // Double quote
  342. string_appendChar(result, U'\"');
  343. } else if (c2 == U'\\') { // Back slash
  344. string_appendChar(result, U'\\');
  345. } else if (c2 == U'a') { // Audible bell
  346. string_appendChar(result, U'\a');
  347. } else if (c2 == U'b') { // Backspace
  348. string_appendChar(result, U'\b');
  349. } else if (c2 == U'f') { // Form feed
  350. string_appendChar(result, U'\f');
  351. } else if (c2 == U'n') { // Line feed
  352. string_appendChar(result, U'\n');
  353. } else if (c2 == U'r') { // Carriage return
  354. string_appendChar(result, U'\r');
  355. } else if (c2 == U't') { // Horizontal tab
  356. string_appendChar(result, U'\t');
  357. } else if (c2 == U'v') { // Vertical tab
  358. string_appendChar(result, U'\v');
  359. } else if (c2 == U'0') { // Null terminator
  360. string_appendChar(result, U'\0');
  361. }
  362. i++; // Consume both characters
  363. } else {
  364. // Detect bad input
  365. if (c == U'\"') { // Double quote
  366. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, U"\n");
  367. } else if (c == U'\a') { // Audible bell
  368. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, U"\n");
  369. } else if (c == U'\b') { // Backspace
  370. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, U"\n");
  371. } else if (c == U'\f') { // Form feed
  372. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, U"\n");
  373. } else if (c == U'\n') { // Line feed
  374. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, U"\n");
  375. } else if (c == U'\r') { // Carriage return
  376. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, U"\n");
  377. } else if (c == U'\0') { // Null terminator
  378. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, U"\n");
  379. } else {
  380. string_appendChar(result, c);
  381. }
  382. }
  383. }
  384. }
  385. return result;
  386. }
  387. void dsr::string_fromUnsigned(String& target, uint64_t value) {
  388. static const int bufferSize = 20;
  389. DsrChar digits[bufferSize];
  390. int64_t usedSize = 0;
  391. if (value == 0) {
  392. string_appendChar(target, U'0');
  393. } else {
  394. while (usedSize < bufferSize) {
  395. DsrChar digit = U'0' + (value % 10u);
  396. digits[usedSize] = digit;
  397. usedSize++;
  398. value /= 10u;
  399. if (value == 0) {
  400. break;
  401. }
  402. }
  403. while (usedSize > 0) {
  404. usedSize--;
  405. string_appendChar(target, digits[usedSize]);
  406. }
  407. }
  408. }
  409. void dsr::string_fromSigned(String& target, int64_t value, DsrChar negationCharacter) {
  410. if (value >= 0) {
  411. string_fromUnsigned(target, (uint64_t)value);
  412. } else {
  413. string_appendChar(target, negationCharacter);
  414. string_fromUnsigned(target, (uint64_t)(-value));
  415. }
  416. }
  417. static const int MAX_DECIMALS = 16;
  418. static double decimalMultipliers[MAX_DECIMALS] = {
  419. 10.0,
  420. 100.0,
  421. 1000.0,
  422. 10000.0,
  423. 100000.0,
  424. 1000000.0,
  425. 10000000.0,
  426. 100000000.0,
  427. 1000000000.0,
  428. 10000000000.0,
  429. 100000000000.0,
  430. 1000000000000.0,
  431. 10000000000000.0,
  432. 100000000000000.0,
  433. 1000000000000000.0,
  434. 10000000000000000.0
  435. };
  436. static double roundingOffsets[MAX_DECIMALS] = {
  437. 0.05,
  438. 0.005,
  439. 0.0005,
  440. 0.00005,
  441. 0.000005,
  442. 0.0000005,
  443. 0.00000005,
  444. 0.000000005,
  445. 0.0000000005,
  446. 0.00000000005,
  447. 0.000000000005,
  448. 0.0000000000005,
  449. 0.00000000000005,
  450. 0.000000000000005,
  451. 0.0000000000000005,
  452. 0.00000000000000005
  453. };
  454. static uint64_t decimalLimits[MAX_DECIMALS] = {
  455. 9,
  456. 99,
  457. 999,
  458. 9999,
  459. 99999,
  460. 999999,
  461. 9999999,
  462. 99999999,
  463. 999999999,
  464. 9999999999,
  465. 99999999999,
  466. 999999999999,
  467. 9999999999999,
  468. 99999999999999,
  469. 999999999999999,
  470. 9999999999999999
  471. };
  472. void dsr::string_fromDouble(String& target, double value, int decimalCount, bool removeTrailingZeroes, DsrChar decimalCharacter, DsrChar negationCharacter) {
  473. if (decimalCount < 1) decimalCount = 1;
  474. if (decimalCount > MAX_DECIMALS) decimalCount = MAX_DECIMALS;
  475. double remainder = value;
  476. // Get negation
  477. if (remainder < 0.0) {
  478. string_appendChar(target, negationCharacter);
  479. remainder = -remainder;
  480. }
  481. // Apply an offset to make the following truncation round to the closest printable decimal.
  482. int offsetIndex = decimalCount - 1;
  483. remainder += roundingOffsets[offsetIndex];
  484. // Get whole part
  485. uint64_t whole = (uint64_t)remainder;
  486. string_fromUnsigned(target, whole);
  487. // Remove the whole part from the remainder.
  488. remainder = remainder - whole;
  489. // Print the decimal
  490. string_appendChar(target, decimalCharacter);
  491. // Get decimals
  492. uint64_t scaledDecimals = uint64_t(remainder * decimalMultipliers[offsetIndex]);
  493. // Limit decimals to all nines prevent losing a whole unit from fraction overflow.
  494. uint64_t limit = decimalLimits[offsetIndex];
  495. if (scaledDecimals > limit) scaledDecimals = limit;
  496. DsrChar digits[MAX_DECIMALS]; // Using 0 to decimalCount - 1
  497. int writeIndex = decimalCount - 1;
  498. for (int d = 0; d < decimalCount; d++) {
  499. int digit = scaledDecimals % 10;
  500. digits[writeIndex] = U'0' + digit;
  501. scaledDecimals = scaledDecimals / 10;
  502. writeIndex--;
  503. }
  504. if (removeTrailingZeroes) {
  505. // Find the last non-zero decimal, but keep at least one zero.
  506. int lastValue = 0;
  507. for (int d = 0; d < decimalCount; d++) {
  508. if (digits[d] != U'0') lastValue = d;
  509. }
  510. // Print until the last value or the only zero.
  511. for (int d = 0; d <= lastValue; d++) {
  512. string_appendChar(target, digits[d]);
  513. }
  514. } else {
  515. // Print fixed decimals.
  516. for (int d = 0; d < decimalCount; d++) {
  517. string_appendChar(target, digits[d]);
  518. }
  519. }
  520. }
  521. #define TO_RAW_ASCII(TARGET, SOURCE) \
  522. char TARGET[SOURCE.view.length + 1]; \
  523. for (intptr_t i = 0; i < SOURCE.view.length; i++) { \
  524. TARGET[i] = toAscii(SOURCE[i]); \
  525. } \
  526. TARGET[SOURCE.view.length] = '\0';
  527. // A function definition for receiving a stream of bytes
  528. // Instead of using std's messy inheritance
  529. using ByteWriterFunction = std::function<void(uint8_t value)>;
  530. // A function definition for receiving a stream of UTF-32 characters
  531. // Instead of using std's messy inheritance
  532. using UTF32WriterFunction = std::function<void(DsrChar character)>;
  533. // Filter out unwanted characters for improved portability
  534. static void feedCharacter(const UTF32WriterFunction &receiver, DsrChar character) {
  535. if (character != U'\0' && character != U'\r') {
  536. receiver(character);
  537. }
  538. }
  539. // Appends the content of buffer as a BOM-free Latin-1 file into target
  540. // fileLength is ignored when nullTerminated is true
  541. template <bool nullTerminated>
  542. static void feedStringFromFileBuffer_Latin1(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength = 0) {
  543. for (intptr_t i = 0; i < fileLength || nullTerminated; i++) {
  544. DsrChar character = (DsrChar)(buffer[i]);
  545. if (nullTerminated && character == 0) { return; }
  546. feedCharacter(receiver, character);
  547. }
  548. }
  549. // Appends the content of buffer as a BOM-free UTF-8 file into target
  550. // fileLength is ignored when nullTerminated is true
  551. template <bool nullTerminated>
  552. static void feedStringFromFileBuffer_UTF8(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength = 0) {
  553. for (intptr_t i = 0; i < fileLength || nullTerminated; i++) {
  554. uint8_t byteA = buffer[i];
  555. if (byteA < (uint32_t)0b10000000) {
  556. // Single byte (1xxxxxxx)
  557. if (nullTerminated && byteA == 0) { return; }
  558. feedCharacter(receiver, (DsrChar)byteA);
  559. } else {
  560. uint32_t character = 0;
  561. int extraBytes = 0;
  562. if (byteA >= (uint32_t)0b11000000) { // At least two leading ones
  563. if (byteA < (uint32_t)0b11100000) { // Less than three leading ones
  564. character = byteA & (uint32_t)0b00011111;
  565. extraBytes = 1;
  566. } else if (byteA < (uint32_t)0b11110000) { // Less than four leading ones
  567. character = byteA & (uint32_t)0b00001111;
  568. extraBytes = 2;
  569. } else if (byteA < (uint32_t)0b11111000) { // Less than five leading ones
  570. character = byteA & (uint32_t)0b00000111;
  571. extraBytes = 3;
  572. } else {
  573. // Invalid UTF-8 format
  574. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  575. }
  576. } else {
  577. // Invalid UTF-8 format
  578. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  579. }
  580. while (extraBytes > 0) {
  581. i += 1; uint32_t nextByte = buffer[i];
  582. character = (character << 6) | (nextByte & 0b00111111);
  583. extraBytes--;
  584. }
  585. feedCharacter(receiver, (DsrChar)character);
  586. }
  587. }
  588. }
  589. template <bool LittleEndian>
  590. uint16_t read16bits(const uint8_t* buffer, intptr_t startOffset) {
  591. uint16_t byteA = buffer[startOffset];
  592. uint16_t byteB = buffer[startOffset + 1];
  593. if (LittleEndian) {
  594. return (byteB << 8) | byteA;
  595. } else {
  596. return (byteA << 8) | byteB;
  597. }
  598. }
  599. // Appends the content of buffer as a BOM-free UTF-16 file into target as UTF-32
  600. // fileLength is ignored when nullTerminated is true
  601. template <bool LittleEndian, bool nullTerminated>
  602. static void feedStringFromFileBuffer_UTF16(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength = 0) {
  603. for (intptr_t i = 0; i < fileLength || nullTerminated; i += 2) {
  604. // Read the first 16-bit word
  605. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  606. // Check if another word is needed
  607. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  608. // we can just check if it's within the range reserved for 32-bit encoding
  609. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  610. // Not in the reserved range, just a single 16-bit character
  611. if (nullTerminated && wordA == 0) { return; }
  612. feedCharacter(receiver, (DsrChar)wordA);
  613. } else {
  614. // The given range was reserved and therefore using 32 bits
  615. i += 2;
  616. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  617. uint32_t higher10Bits = wordA & (uint32_t)0b1111111111;
  618. uint32_t lower10Bits = wordB & (uint32_t)0b1111111111;
  619. DsrChar finalChar = (DsrChar)(((higher10Bits << 10) | lower10Bits) + (uint32_t)0x10000);
  620. feedCharacter(receiver, finalChar);
  621. }
  622. }
  623. }
  624. // Sends the decoded UTF-32 characters from the encoded buffer into target.
  625. // The text encoding should be specified using a BOM at the start of buffer, otherwise Latin-1 is assumed.
  626. static void feedStringFromFileBuffer(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength) {
  627. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  628. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  629. feedStringFromFileBuffer_UTF8<false>(receiver, buffer + 3, fileLength - 3);
  630. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  631. feedStringFromFileBuffer_UTF16<false, false>(receiver, buffer + 2, fileLength - 2);
  632. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  633. feedStringFromFileBuffer_UTF16<true, false>(receiver, buffer + 2, fileLength - 2);
  634. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  635. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  636. throwError(U"UTF-32 BE format is not yet supported!\n");
  637. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  638. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  639. throwError(U"UTF-32 LE format is not yet supported!\n");
  640. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  641. //feedStringFromFileBuffer_UTF1(receiver, buffer + 3, fileLength - 3);
  642. throwError(U"UTF-1 format is not yet supported!\n");
  643. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  644. //feedStringFromFileBuffer_SCSU(receiver, buffer + 3, fileLength - 3);
  645. throwError(U"SCSU format is not yet supported!\n");
  646. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  647. //feedStringFromFileBuffer_BOCU-1(receiver, buffer + 3, fileLength - 3);
  648. throwError(U"BOCU-1 format is not yet supported!\n");
  649. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  650. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  651. throwError(U"UTF-7 format is not yet supported!\n");
  652. } else {
  653. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  654. feedStringFromFileBuffer_Latin1<false>(receiver, buffer, fileLength);
  655. }
  656. }
  657. // Sends the decoded UTF-32 characters from the encoded null terminated buffer into target.
  658. // buffer may not contain any BOM, and must be null terminated in the specified encoding.
  659. static void feedStringFromRawData(const UTF32WriterFunction &receiver, const uint8_t* buffer, CharacterEncoding encoding) {
  660. if (encoding == CharacterEncoding::Raw_Latin1) {
  661. feedStringFromFileBuffer_Latin1<true>(receiver, buffer);
  662. } else if (encoding == CharacterEncoding::BOM_UTF8) {
  663. feedStringFromFileBuffer_UTF8<true>(receiver, buffer);
  664. } else if (encoding == CharacterEncoding::BOM_UTF16BE) {
  665. feedStringFromFileBuffer_UTF16<false, true>(receiver, buffer);
  666. } else if (encoding == CharacterEncoding::BOM_UTF16LE) {
  667. feedStringFromFileBuffer_UTF16<true, true>(receiver, buffer);
  668. } else {
  669. throwError(U"Unhandled encoding in feedStringFromRawData!\n");
  670. }
  671. }
  672. String dsr::string_dangerous_decodeFromData(const void* data, CharacterEncoding encoding) {
  673. String result;
  674. // Measure the size of the result by scanning the content in advance
  675. intptr_t characterCount = 0;
  676. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  677. characterCount++;
  678. };
  679. feedStringFromRawData(measurer, (const uint8_t*)data, encoding);
  680. // Pre-allocate the correct amount of memory based on the simulation
  681. string_reserve(result, characterCount);
  682. // Stream output to the result string
  683. UTF32WriterFunction receiver = [&result](DsrChar character) {
  684. string_appendChar(result, character);
  685. };
  686. feedStringFromRawData(receiver, (const uint8_t*)data, encoding);
  687. return result;
  688. }
  689. String dsr::string_loadFromMemory(Buffer fileContent) {
  690. String result;
  691. // Measure the size of the result by scanning the content in advance
  692. intptr_t characterCount = 0;
  693. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  694. characterCount++;
  695. };
  696. feedStringFromFileBuffer(measurer, fileContent.getUnsafe(), fileContent.getUsedSize());
  697. // Pre-allocate the correct amount of memory based on the simulation
  698. string_reserve(result, characterCount);
  699. // Stream output to the result string
  700. UTF32WriterFunction receiver = [&result](DsrChar character) {
  701. string_appendChar(result, character);
  702. };
  703. feedStringFromFileBuffer(receiver, fileContent.getUnsafe(), fileContent.getUsedSize());
  704. return result;
  705. }
  706. // Loads a text file of unknown format
  707. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines
  708. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  709. Buffer encoded = file_loadBuffer(filename, mustExist);
  710. if (!buffer_exists(encoded)) {
  711. return String();
  712. } else {
  713. return string_loadFromMemory(encoded);
  714. }
  715. }
  716. template <CharacterEncoding characterEncoding>
  717. static void encodeCharacter(const ByteWriterFunction &receiver, DsrChar character) {
  718. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  719. // Replace any illegal characters with questionmarks
  720. if (character > 255) { character = U'?'; }
  721. receiver(character);
  722. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  723. // Replace any illegal characters with questionmarks
  724. if (character > 0x10FFFF) { character = U'?'; }
  725. if (character < (1 << 7)) {
  726. // 0xxxxxxx
  727. receiver(character);
  728. } else if (character < (1 << 11)) {
  729. // 110xxxxx 10xxxxxx
  730. receiver((uint32_t)0b11000000 | ((character & ((uint32_t)0b11111 << 6)) >> 6));
  731. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  732. } else if (character < (1 << 16)) {
  733. // 1110xxxx 10xxxxxx 10xxxxxx
  734. receiver((uint32_t)0b11100000 | ((character & ((uint32_t)0b1111 << 12)) >> 12));
  735. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  736. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  737. } else if (character < (1 << 21)) {
  738. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  739. receiver((uint32_t)0b11110000 | ((character & ((uint32_t)0b111 << 18)) >> 18));
  740. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 12)) >> 12));
  741. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  742. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  743. }
  744. } else { // Assuming UTF-16
  745. if (character > 0x10FFFF) { character = U'?'; }
  746. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  747. // xxxxxxxx xxxxxxxx (Limited range)
  748. uint32_t higher8Bits = (character & (uint32_t)0b1111111100000000) >> 8;
  749. uint32_t lower8Bits = character & (uint32_t)0b0000000011111111;
  750. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  751. receiver(higher8Bits);
  752. receiver(lower8Bits);
  753. } else { // Assuming UTF-16 LE
  754. receiver(lower8Bits);
  755. receiver(higher8Bits);
  756. }
  757. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  758. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  759. uint32_t code = character - (uint32_t)0x10000;
  760. uint32_t byteA = ((code & (uint32_t)0b11000000000000000000) >> 18) | (uint32_t)0b11011000;
  761. uint32_t byteB = (code & (uint32_t)0b00111111110000000000) >> 10;
  762. uint32_t byteC = ((code & (uint32_t)0b00000000001100000000) >> 8) | (uint32_t)0b11011100;
  763. uint32_t byteD = code & (uint32_t)0b00000000000011111111;
  764. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  765. receiver(byteA);
  766. receiver(byteB);
  767. receiver(byteC);
  768. receiver(byteD);
  769. } else { // Assuming UTF-16 LE
  770. receiver(byteB);
  771. receiver(byteA);
  772. receiver(byteD);
  773. receiver(byteC);
  774. }
  775. }
  776. }
  777. }
  778. // Template for encoding a whole string
  779. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  780. static void encodeText(const ByteWriterFunction &receiver, String content, bool writeBOM, bool writeNullTerminator) {
  781. if (writeBOM) {
  782. // Write byte order marks
  783. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  784. receiver(0xEF);
  785. receiver(0xBB);
  786. receiver(0xBF);
  787. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  788. receiver(0xFE);
  789. receiver(0xFF);
  790. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  791. receiver(0xFF);
  792. receiver(0xFE);
  793. }
  794. }
  795. // Write encoded content
  796. for (intptr_t i = 0; i < string_length(content); i++) {
  797. DsrChar character = content[i];
  798. if (character == U'\n') {
  799. if (lineEncoding == LineEncoding::CrLf) {
  800. encodeCharacter<characterEncoding>(receiver, U'\r');
  801. encodeCharacter<characterEncoding>(receiver, U'\n');
  802. } else { // Assuming that lineEncoding == LineEncoding::Lf
  803. encodeCharacter<characterEncoding>(receiver, U'\n');
  804. }
  805. } else {
  806. encodeCharacter<characterEncoding>(receiver, character);
  807. }
  808. }
  809. if (writeNullTerminator) {
  810. // Terminate internal strings with \0 to prevent getting garbage data after unpadded buffers
  811. if (characterEncoding == CharacterEncoding::BOM_UTF16BE || characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  812. receiver(0);
  813. receiver(0);
  814. } else {
  815. receiver(0);
  816. }
  817. }
  818. }
  819. // Macro for converting run-time arguments into template arguments for encodeText
  820. #define ENCODE_TEXT(RECEIVER, CONTENT, CHAR_ENCODING, LINE_ENCODING, WRITE_BOM, WRITE_NULL_TERMINATOR) \
  821. if (CHAR_ENCODING == CharacterEncoding::Raw_Latin1) { \
  822. if (LINE_ENCODING == LineEncoding::CrLf) { \
  823. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::CrLf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  824. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  825. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::Lf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  826. } \
  827. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF8) { \
  828. if (LINE_ENCODING == LineEncoding::CrLf) { \
  829. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  830. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  831. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  832. } \
  833. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16BE) { \
  834. if (LINE_ENCODING == LineEncoding::CrLf) { \
  835. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  836. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  837. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  838. } \
  839. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16LE) { \
  840. if (LINE_ENCODING == LineEncoding::CrLf) { \
  841. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  842. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  843. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  844. } \
  845. }
  846. // Encoding to a buffer before saving all at once as a binary file.
  847. // This tells the operating system how big the file is in advance and prevent the worst case of stalling for minutes!
  848. bool dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  849. Buffer buffer = string_saveToMemory(content, characterEncoding, lineEncoding);
  850. if (buffer_exists(buffer)) {
  851. return file_saveBuffer(filename, buffer);
  852. } else {
  853. return false;
  854. }
  855. }
  856. Buffer dsr::string_saveToMemory(const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding, bool writeByteOrderMark, bool writeNullTerminator) {
  857. intptr_t byteCount = 0;
  858. ByteWriterFunction counter = [&byteCount](uint8_t value) {
  859. byteCount++;
  860. };
  861. ENCODE_TEXT(counter, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  862. Buffer result = buffer_create(byteCount).setName("Buffer holding an encoded string");
  863. SafePointer<uint8_t> byteWriter = buffer_getSafeData<uint8_t>(result, "Buffer for string encoding");
  864. ByteWriterFunction receiver = [&byteWriter](uint8_t value) {
  865. *byteWriter = value;
  866. byteWriter += 1;
  867. };
  868. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  869. return result;
  870. }
  871. static uintptr_t getStartOffset(const ReadableString &source) {
  872. // Get the allocation
  873. const uint8_t* origin = (uint8_t*)(source.characters.getUnsafe());
  874. const uint8_t* start = (uint8_t*)(source.view.getUnchecked());
  875. assert(start <= origin);
  876. // Get the offset from the parent
  877. return (start - origin) / sizeof(DsrChar);
  878. }
  879. #ifdef SAFE_POINTER_CHECKS
  880. static void serializeCharacterBuffer(PrintCharacter target, void const * const allocation, uintptr_t maxLength) {
  881. uintptr_t characterCount = heap_getUsedSize(allocation) / sizeof(DsrChar);
  882. target(U'\"');
  883. for (uintptr_t c = 0; c < characterCount; c++) {
  884. if (c == maxLength) {
  885. target(U'\"');
  886. target(U'.');
  887. target(U'.');
  888. target(U'.');
  889. return;
  890. }
  891. target(((DsrChar *)allocation)[c]);
  892. }
  893. target(U'\"');
  894. }
  895. #endif
  896. static Handle<DsrChar> allocateCharacters(intptr_t minimumLength) {
  897. // Allocate memory.
  898. Handle<DsrChar> result = handle_createArray<DsrChar>(AllocationInitialization::Uninitialized, minimumLength).setName("String characters");
  899. #ifdef SAFE_POINTER_CHECKS
  900. setAllocationSerialization(result.getUnsafe(), &serializeCharacterBuffer);
  901. #endif
  902. // Check how much space we got.
  903. uintptr_t availableSpace = heap_getAllocationSize(result.getUnsafe());
  904. // Expand to use all available memory in the allocation.
  905. uintptr_t newSize = heap_setUsedSize(result.getUnsafe(), availableSpace);
  906. // Clear the memory to zeroes, just to be safe against non-deterministic bugs.
  907. safeMemorySet(result.getSafe("Cleared String pointer"), 0, newSize);
  908. return result;
  909. }
  910. // Replaces the buffer with a new buffer holding at least minimumLength characters
  911. // Guarantees that the new buffer is not shared by other strings, so that it may be written to freely
  912. static void reallocateBuffer(String &target, intptr_t minimumLength, bool preserve) {
  913. // Holding oldData alive while copying to the new buffer
  914. Handle<DsrChar> oldBuffer = target.characters; // Kept for reference counting only, do not remove.
  915. Impl_CharacterView oldData = target.view;
  916. target.characters = allocateCharacters(minimumLength);
  917. target.view = Impl_CharacterView(target.characters.getUnsafe(), oldData.length);
  918. if (preserve && oldData.length > 0) {
  919. safeMemoryCopy(target.view.getSafe("New characters being copied from an old buffer"), oldData.getSafe("Old characters being copied to a new buffer"), oldData.length * sizeof(DsrChar));
  920. }
  921. }
  922. // Call before writing to the buffer.
  923. // This hides that Strings share buffers when assigning by value or taking partial strings.
  924. static void cloneIfNeeded(String &target) {
  925. // If there is no buffer or the buffer is shared, it needs to allocate its own buffer.
  926. if (target.characters.isNull() || target.characters.getUseCount() > 1) {
  927. reallocateBuffer(target, target.view.length, true);
  928. }
  929. }
  930. void dsr::string_clear(String& target) {
  931. // We we start writing from the beginning, then we must have our own allocation to avoid overwriting the characters in other strings.
  932. cloneIfNeeded(target);
  933. target.view.length = 0;
  934. }
  935. // The number of DsrChar characters that can be contained in the allocation before reaching the buffer's end
  936. // This doesn't imply that it's always okay to write to the remaining space, because the buffer may be shared
  937. static intptr_t getCapacity(const ReadableString &source) {
  938. if (source.characters.isNotNull()) {
  939. uintptr_t bufferElements = source.characters.getElementCount();
  940. // Subtract offset from the buffer size to get the remaining space
  941. return bufferElements - getStartOffset(source);
  942. } else {
  943. return 0;
  944. }
  945. }
  946. static void expand(String &target, intptr_t newLength, bool affectUsedLength) {
  947. cloneIfNeeded(target);
  948. if (newLength > target.view.length) {
  949. if (newLength > getCapacity(target)) {
  950. reallocateBuffer(target, newLength, true);
  951. }
  952. if (affectUsedLength) {
  953. target.view.length = newLength;
  954. }
  955. }
  956. }
  957. void dsr::string_reserve(String& target, intptr_t minimumLength) {
  958. expand(target, minimumLength, false);
  959. }
  960. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  961. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  962. // Proof that appending to one string doesn't affect another:
  963. // If it has to reallocate
  964. // * Then it will have its own buffer without conflicts
  965. // If it doesn't have to reallocate
  966. // If it shares the buffer
  967. // If source is empty
  968. // * Then no risk of overwriting neighbor strings if we don't write
  969. // If source isn't empty
  970. // * Then the buffer will be cloned when the first character is written
  971. // If it doesn't share the buffer
  972. // * Then no risk of writing
  973. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  974. intptr_t oldLength = (TARGET).view.length; \
  975. expand((TARGET), oldLength + (intptr_t)(LENGTH), true); \
  976. for (intptr_t i = 0; i < (intptr_t)(LENGTH); i++) { \
  977. (TARGET).view.writeCharacter(oldLength + i, ((SOURCE)[i]) & MASK); \
  978. } \
  979. }
  980. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  981. static void atomic_append_ascii(String &target, const char* source) { APPEND(target, source, strlen(source), 0xFF); }
  982. // TODO: Use memcpy when appending input of the same format
  983. static void atomic_append_readable(String &target, const ReadableString& source) { APPEND(target, source, source.view.length, 0xFFFFFFFF); }
  984. static void atomic_append_utf32(String &target, const DsrChar* source) { APPEND(target, source, strlen_utf32(source), 0xFFFFFFFF); }
  985. void dsr::string_appendChar(String& target, DsrChar value) { APPEND(target, &value, 1, 0xFFFFFFFF); }
  986. String& dsr::impl_toStreamIndented_ascii(String& target, const char *value, const ReadableString& indentation) {
  987. atomic_append_readable(target, indentation);
  988. atomic_append_ascii(target, value);
  989. return target;
  990. }
  991. String& dsr::impl_toStreamIndented_utf32(String& target, const char32_t *value, const ReadableString& indentation) {
  992. atomic_append_readable(target, indentation);
  993. atomic_append_utf32(target, value);
  994. return target;
  995. }
  996. String& dsr::impl_toStreamIndented_readable(String& target, const ReadableString& value, const ReadableString& indentation) {
  997. atomic_append_readable(target, indentation);
  998. atomic_append_readable(target, value);
  999. return target;
  1000. }
  1001. String& dsr::impl_toStreamIndented_double(String& target, const double &value, const ReadableString& indentation) {
  1002. atomic_append_readable(target, indentation);
  1003. string_fromDouble(target, (double)value);
  1004. return target;
  1005. }
  1006. String& dsr::impl_toStreamIndented_int64(String& target, const int64_t &value, const ReadableString& indentation) {
  1007. atomic_append_readable(target, indentation);
  1008. string_fromSigned(target, value);
  1009. return target;
  1010. }
  1011. String& dsr::impl_toStreamIndented_uint64(String& target, const uint64_t &value, const ReadableString& indentation) {
  1012. atomic_append_readable(target, indentation);
  1013. string_fromUnsigned(target, value);
  1014. return target;
  1015. }
  1016. // The print mutex makes sure that messages from multiple threads don't get mixed up.
  1017. static std::mutex printMutex;
  1018. static std::ostream& toStream(std::ostream& out, const ReadableString &source) {
  1019. for (intptr_t i = 0; i < source.view.length; i++) {
  1020. out.put(toAscii(source.view[i]));
  1021. }
  1022. return out;
  1023. }
  1024. static const std::function<void(const ReadableString &message, MessageType type)> defaultMessageAction = [](const ReadableString &message, MessageType type) {
  1025. if (type == MessageType::Error) {
  1026. #ifdef DSR_HARD_EXIT_ON_ERROR
  1027. // Print the error.
  1028. toStream(std::cerr, message);
  1029. // Free all heap allocations.
  1030. heap_hardExitCleaning();
  1031. // Terminate with a non-zero value to indicate failure.
  1032. std::exit(1);
  1033. #else
  1034. Buffer ascii = string_saveToMemory(message, CharacterEncoding::Raw_Latin1, LineEncoding::CrLf, false, true);
  1035. throw std::runtime_error((char*)ascii.getUnsafe());
  1036. #endif
  1037. } else {
  1038. printMutex.lock();
  1039. toStream(std::cout, message);
  1040. printMutex.unlock();
  1041. }
  1042. };
  1043. static std::function<void(const ReadableString &message, MessageType type)> globalMessageAction = defaultMessageAction;
  1044. void dsr::string_sendMessage(const ReadableString &message, MessageType type) {
  1045. globalMessageAction(message, type);
  1046. }
  1047. void dsr::string_sendMessage_default(const ReadableString &message, MessageType type) {
  1048. defaultMessageAction(message, type);
  1049. }
  1050. void dsr::string_assignMessageHandler(std::function<void(const ReadableString &message, MessageType type)> newHandler) {
  1051. globalMessageAction = newHandler;
  1052. }
  1053. void dsr::string_unassignMessageHandler() {
  1054. globalMessageAction = defaultMessageAction;
  1055. }
  1056. void dsr::string_split_callback(std::function<void(ReadableString separatedText)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  1057. intptr_t sectionStart = 0;
  1058. for (intptr_t i = 0; i < source.view.length; i++) {
  1059. DsrChar c = source[i];
  1060. if (c == separator) {
  1061. ReadableString element = string_exclusiveRange(source, sectionStart, i);
  1062. if (removeWhiteSpace) {
  1063. action(string_removeOuterWhiteSpace(element));
  1064. } else {
  1065. action(element);
  1066. }
  1067. sectionStart = i + 1;
  1068. }
  1069. }
  1070. if (source.view.length > sectionStart) {
  1071. if (removeWhiteSpace) {
  1072. action(string_removeOuterWhiteSpace(string_exclusiveRange(source, sectionStart, source.view.length)));
  1073. } else {
  1074. action(string_exclusiveRange(source, sectionStart, source.view.length));
  1075. }
  1076. }
  1077. }
  1078. static String createSubString(const Handle<DsrChar> &characters, const Impl_CharacterView &view) {
  1079. String result;
  1080. result.characters = characters;
  1081. result.view = view;
  1082. return result;
  1083. }
  1084. List<String> dsr::string_split(const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  1085. List<String> result;
  1086. if (source.view.length > 0) {
  1087. // Re-use the existing buffer
  1088. String commonBuffer = createSubString(source.characters, source.view);
  1089. // Source is allocated as String
  1090. string_split_callback([&result, removeWhiteSpace](String element) {
  1091. if (removeWhiteSpace) {
  1092. result.push(string_removeOuterWhiteSpace(element));
  1093. } else {
  1094. result.push(element);
  1095. }
  1096. }, commonBuffer, separator, removeWhiteSpace);
  1097. }
  1098. return result;
  1099. }
  1100. intptr_t dsr::string_splitCount(const ReadableString& source, DsrChar separator) {
  1101. intptr_t result = 0;
  1102. string_split_callback([&result](ReadableString element) {
  1103. result++;
  1104. }, source, separator);
  1105. return result;
  1106. }
  1107. int64_t dsr::string_toInteger(const ReadableString& source) {
  1108. int64_t result;
  1109. bool negated;
  1110. result = 0;
  1111. negated = false;
  1112. for (intptr_t i = 0; i < source.view.length; i++) {
  1113. DsrChar c = source[i];
  1114. if (c == '-' || c == '~') {
  1115. negated = !negated;
  1116. } else if (c >= '0' && c <= '9') {
  1117. result = (result * 10) + (int)(c - '0');
  1118. } else if (c == ',' || c == '.') {
  1119. // Truncate any decimals by ignoring them
  1120. break;
  1121. }
  1122. }
  1123. if (negated) {
  1124. return -result;
  1125. } else {
  1126. return result;
  1127. }
  1128. }
  1129. double dsr::string_toDouble(const ReadableString& source) {
  1130. double result;
  1131. bool negated;
  1132. bool reachedDecimal;
  1133. int64_t digitDivider;
  1134. result = 0.0;
  1135. negated = false;
  1136. reachedDecimal = false;
  1137. digitDivider = 1;
  1138. for (intptr_t i = 0; i < source.view.length; i++) {
  1139. DsrChar c = source[i];
  1140. if (c == '-' || c == '~') {
  1141. negated = !negated;
  1142. } else if (c >= '0' && c <= '9') {
  1143. if (reachedDecimal) {
  1144. digitDivider = digitDivider * 10;
  1145. result = result + ((double)(c - '0') / (double)digitDivider);
  1146. } else {
  1147. result = (result * 10) + (double)(c - '0');
  1148. }
  1149. } else if (c == ',' || c == '.') {
  1150. reachedDecimal = true;
  1151. } else if (c == 'e' || c == 'E') {
  1152. // Apply the exponent after 'e'.
  1153. result *= std::pow(10.0, string_toInteger(string_after(source, i)));
  1154. // Skip remaining characters.
  1155. i = source.view.length;
  1156. }
  1157. }
  1158. if (negated) {
  1159. return -result;
  1160. } else {
  1161. return result;
  1162. }
  1163. }
  1164. intptr_t dsr::string_length(const ReadableString& source) {
  1165. return source.view.length;
  1166. }
  1167. intptr_t dsr::string_findFirst(const ReadableString& source, DsrChar toFind, intptr_t startIndex) {
  1168. for (intptr_t i = startIndex; i < source.view.length; i++) {
  1169. if (source[i] == toFind) {
  1170. return i;
  1171. }
  1172. }
  1173. return -1;
  1174. }
  1175. intptr_t dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  1176. for (intptr_t i = source.view.length - 1; i >= 0; i--) {
  1177. if (source[i] == toFind) {
  1178. return i;
  1179. }
  1180. }
  1181. return -1;
  1182. }
  1183. ReadableString dsr::string_exclusiveRange(const ReadableString& source, intptr_t inclusiveStart, intptr_t exclusiveEnd) {
  1184. // Return empty string for each complete miss
  1185. if (inclusiveStart >= source.view.length || exclusiveEnd <= 0) { return ReadableString(); }
  1186. // Automatically clamping to valid range
  1187. if (inclusiveStart < 0) { inclusiveStart = 0; }
  1188. if (exclusiveEnd > source.view.length) { exclusiveEnd = source.view.length; }
  1189. // Return the overlapping interval
  1190. return createSubString(source.characters, Impl_CharacterView(source.view.getUnchecked() + inclusiveStart, exclusiveEnd - inclusiveStart));
  1191. }
  1192. ReadableString dsr::string_inclusiveRange(const ReadableString& source, intptr_t inclusiveStart, intptr_t inclusiveEnd) {
  1193. return string_exclusiveRange(source, inclusiveStart, inclusiveEnd + 1);
  1194. }
  1195. ReadableString dsr::string_before(const ReadableString& source, intptr_t exclusiveEnd) {
  1196. return string_exclusiveRange(source, 0, exclusiveEnd);
  1197. }
  1198. ReadableString dsr::string_until(const ReadableString& source, intptr_t inclusiveEnd) {
  1199. return string_inclusiveRange(source, 0, inclusiveEnd);
  1200. }
  1201. ReadableString dsr::string_from(const ReadableString& source, intptr_t inclusiveStart) {
  1202. return string_exclusiveRange(source, inclusiveStart, source.view.length);
  1203. }
  1204. ReadableString dsr::string_after(const ReadableString& source, intptr_t exclusiveStart) {
  1205. return string_from(source, exclusiveStart + 1);
  1206. }
  1207. bool dsr::character_isDigit(DsrChar c) {
  1208. return c >= U'0' && c <= U'9';
  1209. }
  1210. bool dsr::character_isIntegerCharacter(DsrChar c) {
  1211. return c == U'-' || character_isDigit(c);
  1212. }
  1213. bool dsr::character_isValueCharacter(DsrChar c) {
  1214. return c == U'.' || character_isIntegerCharacter(c);
  1215. }
  1216. bool dsr::character_isWhiteSpace(DsrChar c) {
  1217. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  1218. }
  1219. // Macros for implementing regular expressions with a greedy approach consuming the first match
  1220. // Optional accepts 0 or 1 occurence
  1221. // Forced accepts 1 occurence
  1222. // Star accepts 0..N occurence
  1223. // Plus accepts 1..N occurence
  1224. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  1225. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  1226. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  1227. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  1228. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1229. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  1230. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1231. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  1232. // The greedy approach works here, because there's no ambiguity
  1233. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  1234. intptr_t readIndex = 0;
  1235. if (allowWhiteSpace) {
  1236. PATTERN_STAR(WhiteSpace);
  1237. }
  1238. CHARACTER_OPTIONAL(U'-');
  1239. // At least one digit required
  1240. PATTERN_PLUS(IntegerCharacter);
  1241. if (allowWhiteSpace) {
  1242. PATTERN_STAR(WhiteSpace);
  1243. }
  1244. return readIndex == source.view.length;
  1245. }
  1246. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1247. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1248. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1249. if (string_findFirst(source, U'.') == -1) {
  1250. // No decimal detected
  1251. return string_isInteger(source, allowWhiteSpace);
  1252. } else {
  1253. intptr_t readIndex = 0;
  1254. if (allowWhiteSpace) {
  1255. PATTERN_STAR(WhiteSpace);
  1256. }
  1257. // Double <- UnsignedDouble | '-' UnsignedDouble
  1258. CHARACTER_OPTIONAL(U'-');
  1259. // UnsignedDouble <- Digit* '.' Digit+
  1260. // Any number of integer digits
  1261. PATTERN_STAR(IntegerCharacter);
  1262. // Only dot for decimal
  1263. CHARACTER_FORCED(U'.')
  1264. // At least one decimal digit
  1265. PATTERN_PLUS(IntegerCharacter);
  1266. if (allowWhiteSpace) {
  1267. PATTERN_STAR(WhiteSpace);
  1268. }
  1269. return readIndex == source.view.length;
  1270. }
  1271. }
  1272. uintptr_t dsr::string_getBufferUseCount(const ReadableString& text) {
  1273. return text.characters.getUseCount();
  1274. }