stringAPI.cpp 52 KB

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