2
0

stringAPI.cpp 53 KB

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