text.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2019 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. #include "text.h"
  24. #include <fstream>
  25. #include <streambuf>
  26. #include <cstring>
  27. #include <stdexcept>
  28. using namespace dsr;
  29. static int strlen_utf32(const char32_t *content) {
  30. int length = 0;
  31. while (content[length] != 0) {
  32. length++;
  33. }
  34. return length;
  35. }
  36. static char toAscii(DsrChar c) {
  37. if (c > 127) {
  38. return '?';
  39. } else {
  40. return c;
  41. }
  42. }
  43. String& Printable::toStream(String& target) const {
  44. return this->toStreamIndented(target, U"");
  45. }
  46. String Printable::toStringIndented(const ReadableString& indentation) const {
  47. String result;
  48. this->toStreamIndented(result, indentation);
  49. return result;
  50. }
  51. String Printable::toString() const {
  52. return this->toStringIndented(U"");
  53. }
  54. std::ostream& Printable::toStreamIndented(std::ostream& out, const ReadableString& indentation) const {
  55. String result;
  56. this->toStreamIndented(result, indentation);
  57. for (int i = 0; i < result.length(); i++) {
  58. out.put(toAscii(result.read(i)));
  59. }
  60. return out;
  61. }
  62. std::ostream& Printable::toStream(std::ostream& out) const {
  63. return this->toStreamIndented(out, U"");
  64. }
  65. std::string Printable::toStdString() const {
  66. std::ostringstream result;
  67. this->toStream(result);
  68. return result.str();
  69. }
  70. Printable::~Printable() {}
  71. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  72. if (a.length() != b.length()) {
  73. return false;
  74. } else {
  75. for (int i = 0; i < a.length(); i++) {
  76. if (a.read(i) != b.read(i)) {
  77. return false;
  78. }
  79. }
  80. return true;
  81. }
  82. }
  83. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  84. if (a.length() != b.length()) {
  85. return false;
  86. } else {
  87. for (int i = 0; i < a.length(); i++) {
  88. if (towupper(a.read(i)) != towupper(b.read(i))) {
  89. return false;
  90. }
  91. }
  92. return true;
  93. }
  94. }
  95. std::ostream& ReadableString::toStream(std::ostream& out) const {
  96. for (int i = 0; i < this->length(); i++) {
  97. out.put(toAscii(this->read(i)));
  98. }
  99. return out;
  100. }
  101. std::string ReadableString::toStdString() const {
  102. std::ostringstream result;
  103. this->toStream(result);
  104. return result.str();
  105. }
  106. String dsr::string_upperCase(const ReadableString &text) {
  107. String result;
  108. result.reserve(text.length());
  109. for (int i = 0; i < text.length(); i++) {
  110. result.appendChar(towupper(text[i]));
  111. }
  112. return result;
  113. }
  114. String dsr::string_lowerCase(const ReadableString &text) {
  115. String result;
  116. result.reserve(text.length());
  117. for (int i = 0; i < text.length(); i++) {
  118. result.appendChar(towlower(text[i]));
  119. }
  120. return result;
  121. }
  122. String dsr::string_removeAllWhiteSpace(const ReadableString &text) {
  123. String result;
  124. result.reserve(text.length());
  125. for (int i = 0; i < text.length(); i++) {
  126. DsrChar c = text[i];
  127. if (!character_isWhiteSpace(c)) {
  128. result.appendChar(c);
  129. }
  130. }
  131. return result;
  132. }
  133. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  134. int first = -1;
  135. int last = -1;
  136. for (int i = 0; i < text.length(); i++) {
  137. DsrChar c = text[i];
  138. if (!character_isWhiteSpace(c)) {
  139. first = i;
  140. break;
  141. }
  142. }
  143. for (int i = text.length() - 1; i >= 0; i--) {
  144. DsrChar c = text[i];
  145. if (!character_isWhiteSpace(c)) {
  146. last = i;
  147. break;
  148. }
  149. }
  150. if (first == -1) {
  151. // Only white space
  152. return ReadableString();
  153. } else {
  154. // Subset
  155. return string_inclusiveRange(text, first, last);
  156. }
  157. }
  158. String dsr::string_mangleQuote(const ReadableString &rawText) {
  159. String result;
  160. result.reserve(rawText.length() + 2);
  161. result.appendChar(U'\"'); // Begin quote
  162. for (int i = 0; i < rawText.length(); i++) {
  163. DsrChar c = rawText[i];
  164. if (c == U'\"') { // Double quote
  165. result.append(U"\\\"");
  166. } else if (c == U'\\') { // Backslash
  167. result.append(U"\\\\");
  168. } else if (c == U'\a') { // Audible bell
  169. result.append(U"\\a");
  170. } else if (c == U'\b') { // Backspace
  171. result.append(U"\\b");
  172. } else if (c == U'\f') { // Form feed
  173. result.append(U"\\f");
  174. } else if (c == U'\n') { // Line feed
  175. result.append(U"\\n");
  176. } else if (c == U'\r') { // Carriage return
  177. result.append(U"\\r");
  178. } else if (c == U'\t') { // Horizontal tab
  179. result.append(U"\\t");
  180. } else if (c == U'\v') { // Vertical tab
  181. result.append(U"\\v");
  182. } else if (c == U'\0') { // Null terminator
  183. result.append(U"\\0");
  184. } else {
  185. result.appendChar(c);
  186. }
  187. }
  188. result.appendChar(U'\"'); // End quote
  189. return result;
  190. }
  191. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  192. int firstQuote = string_findFirst(mangledText, '\"');
  193. int lastQuote = string_findLast(mangledText, '\"');
  194. String result;
  195. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  196. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, "\n");
  197. } else {
  198. for (int i = firstQuote + 1; i < lastQuote; i++) {
  199. DsrChar c = mangledText[i];
  200. if (c == U'\\') { // Escape character
  201. DsrChar c2 = mangledText[i + 1];
  202. if (c2 == U'\"') { // Double quote
  203. result.appendChar(U'\"');
  204. } else if (c2 == U'\\') { // Back slash
  205. result.appendChar(U'\\');
  206. } else if (c2 == U'a') { // Audible bell
  207. result.appendChar(U'\a');
  208. } else if (c2 == U'b') { // Backspace
  209. result.appendChar(U'\b');
  210. } else if (c2 == U'f') { // Form feed
  211. result.appendChar(U'\f');
  212. } else if (c2 == U'n') { // Line feed
  213. result.appendChar(U'\n');
  214. } else if (c2 == U'r') { // Carriage return
  215. result.appendChar(U'\r');
  216. } else if (c2 == U't') { // Horizontal tab
  217. result.appendChar(U'\t');
  218. } else if (c2 == U'v') { // Vertical tab
  219. result.appendChar(U'\v');
  220. } else if (c2 == U'0') { // Null terminator
  221. result.appendChar(U'\0');
  222. }
  223. i++; // Consume both characters
  224. } else {
  225. // Detect bad input
  226. if (c == U'\"') { // Double quote
  227. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, "\n");
  228. } else if (c == U'\\') { // Back slash
  229. throwError(U"Unmangled back slash detected in string_unmangleQuote!\n", mangledText, "\n");
  230. } else if (c == U'\a') { // Audible bell
  231. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  232. } else if (c == U'\b') { // Backspace
  233. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  234. } else if (c == U'\f') { // Form feed
  235. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  236. } else if (c == U'\n') { // Line feed
  237. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  238. } else if (c == U'\r') { // Carriage return
  239. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  240. } else if (c == U'\0') { // Null terminator
  241. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  242. } else {
  243. result.appendChar(c);
  244. }
  245. }
  246. }
  247. }
  248. return result;
  249. }
  250. static void uintToString_arabic(String& target, uint64_t value) {
  251. static const int bufferSize = 20;
  252. DsrChar digits[bufferSize];
  253. int usedSize = 0;
  254. if (value == 0) {
  255. target.appendChar(U'0');
  256. } else {
  257. while (usedSize < bufferSize) {
  258. DsrChar digit = U'0' + (value % 10u);
  259. digits[usedSize] = digit;
  260. usedSize++;
  261. value /= 10u;
  262. if (value == 0) {
  263. break;
  264. }
  265. }
  266. while (usedSize > 0) {
  267. usedSize--;
  268. target.appendChar(digits[usedSize]);
  269. }
  270. }
  271. }
  272. static void intToString_arabic(String& target, int64_t value) {
  273. if (value >= 0) {
  274. uintToString_arabic(target, (uint64_t)value);
  275. } else {
  276. target.appendChar(U'-');
  277. uintToString_arabic(target, (uint64_t)(-value));
  278. }
  279. }
  280. // TODO: Implement own version to ensure that nothing strange is happening from buggy std implementations
  281. static void doubleToString_arabic(String& target, double value) {
  282. std::ostringstream buffer;
  283. buffer << std::fixed << value; // Generate using a fixed number of decimals
  284. std::string result = buffer.str();
  285. // Remove trailing zero decimal digits
  286. int decimalCount = 0;
  287. int lastValueIndex = -1;
  288. for (int c = 0; c < (int)result.length(); c++) {
  289. if (result[c] == '.') {
  290. decimalCount++;
  291. } else if (result[c] == ',') {
  292. result[c] = '.'; // Convert nationalized french decimal serialization into international decimals
  293. decimalCount++;
  294. } else if (decimalCount > 0 && result[c] >= '1' && result[c] <= '9') {
  295. lastValueIndex = c;
  296. } else if (decimalCount == 0 && result[c] >= '0' && result[c] <= '9') {
  297. lastValueIndex = c;
  298. }
  299. }
  300. for (int c = 0; c <= lastValueIndex; c++) {
  301. target.appendChar(result[c]);
  302. }
  303. }
  304. #define TO_RAW_ASCII(TARGET, SOURCE) \
  305. char TARGET[SOURCE.length() + 1]; \
  306. for (int i = 0; i < SOURCE.length(); i++) { \
  307. TARGET[i] = toAscii(SOURCE[i]); \
  308. } \
  309. TARGET[SOURCE.length()] = '\0';
  310. // TODO: Give as a lambda with target captured, so that pre-allocation can measure the
  311. // needed space exactly using a lambda that increases a character counter instead.
  312. // Interpreting a character's value and appends it to the string.
  313. static void feedCharacterFromFile(String &target, DsrChar character) {
  314. if (character != U'\r') {
  315. target.appendChar(character);
  316. }
  317. }
  318. // Appends the content of buffer as a BOM-free Latin-1 file into target
  319. static void AppendStringFromFileBuffer_Latin1(String &target, const uint8_t* buffer, int64_t fileLength) {
  320. for (int64_t i = 0; i < fileLength; i++) {
  321. feedCharacterFromFile(target, (DsrChar)(buffer[i]));
  322. }
  323. }
  324. // Appends the content of buffer as a BOM-free UTF-8 file into target
  325. static void AppendStringFromFileBuffer_UTF8(String &target, const uint8_t* buffer, int64_t fileLength) {
  326. // We know that the result will be at least one character per given byte for UTF-8
  327. target.reserve(string_length(target) + fileLength);
  328. for (int64_t i = 0; i < fileLength; i++) {
  329. uint8_t byteA = buffer[i];
  330. if (byteA < 0b10000000) {
  331. // Single byte (1xxxxxxx)
  332. feedCharacterFromFile(target, (DsrChar)byteA);
  333. } else {
  334. uint32_t character = 0;
  335. int extraBytes = 0;
  336. if (byteA >= 0b11000000) { // At least two leading ones
  337. if (byteA < 0b11100000) { // Less than three leading ones
  338. character = byteA & 0b00011111;
  339. extraBytes = 1;
  340. } else if (byteA < 0b11110000) { // Less than four leading ones
  341. character = byteA & 0b00011111;
  342. extraBytes = 2;
  343. } else if (byteA < 0b11111000) { // Less than five leading ones
  344. character = byteA & 0b00011111;
  345. extraBytes = 3;
  346. } else {
  347. // Invalid UTF-8 format
  348. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  349. }
  350. } else {
  351. // Invalid UTF-8 format
  352. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  353. }
  354. while (extraBytes > 0) {
  355. i += 1; uint32_t nextByte = buffer[i];
  356. character = (character << 6) | (nextByte & 0b00111111);
  357. extraBytes--;
  358. }
  359. feedCharacterFromFile(target, (DsrChar)character);
  360. }
  361. }
  362. }
  363. // Appends the content of buffer as a text file of unknown format into target
  364. static void AppendStringFromFileBuffer(String &target, const uint8_t* buffer, int64_t fileLength) {
  365. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  366. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) {
  367. AppendStringFromFileBuffer_UTF8(target, buffer + 3, fileLength - 3);
  368. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) {
  369. //AppendStringFromFileBuffer_UTF1(target, buffer + 3, fileLength - 3);
  370. throwError(U"UTF-1 format is not yet supported!\n");
  371. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) {
  372. //AppendStringFromFileBuffer_SCSU(target, buffer + 3, fileLength - 3);
  373. throwError(U"SCSU format is not yet supported!\n");
  374. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) {
  375. //AppendStringFromFileBuffer_BOCU-1(target, buffer + 3, fileLength - 3);
  376. throwError(U"BOCU-1 format is not yet supported!\n");
  377. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) {
  378. //AppendStringFromFileBuffer_UTF16BE(target, buffer + 2, fileLength - 2);
  379. throwError(U"UTF-16 BE format is not yet supported!\n");
  380. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) {
  381. //AppendStringFromFileBuffer_UTF16LE(target, buffer + 2, fileLength - 2);
  382. throwError(U"UTF-16 LE format is not yet supported!\n");
  383. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) {
  384. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  385. throwError(U"UTF-32 BE format is not yet supported!\n");
  386. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) {
  387. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  388. throwError(U"UTF-32 LE format is not yet supported!\n");
  389. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) {
  390. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  391. throwError(U"UTF-7 format is not yet supported!\n");
  392. } else {
  393. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  394. AppendStringFromFileBuffer_Latin1(target, buffer, fileLength);
  395. }
  396. }
  397. String dsr::string_loadFromMemory(const Buffer &fileContent) {
  398. String result;
  399. AppendStringFromFileBuffer(result, fileContent.getUnsafeData(), fileContent.size);
  400. return result;
  401. }
  402. // Loads a text file of unknown format
  403. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines.
  404. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  405. // TODO: Load files using Unicode filenames when available
  406. TO_RAW_ASCII(asciiFilename, filename);
  407. std::ifstream fileStream(asciiFilename, std::ios_base::in | std::ios_base::binary);
  408. if (fileStream.is_open()) {
  409. String result;
  410. // Get the file's length and allocate an array for the raw encoding
  411. fileStream.seekg (0, fileStream.end);
  412. int64_t fileLength = fileStream.tellg();
  413. fileStream.seekg (0, fileStream.beg);
  414. uint8_t* buffer = (uint8_t*)malloc(fileLength);
  415. fileStream.read((char*)buffer, fileLength);
  416. AppendStringFromFileBuffer(result, buffer, fileLength);
  417. free(buffer);
  418. return result;
  419. } else {
  420. if (mustExist) {
  421. throwError(U"The text file ", filename, U" could not be opened for reading.\n");
  422. }
  423. // If the file cound not be found and opened, a null string is returned
  424. return String();
  425. }
  426. }
  427. static inline void byteToStream(std::ostream &target, int value) {
  428. uint8_t byte = value;
  429. target.write((char*)&byte, 1);
  430. }
  431. template <CharacterEncoding characterEncoding>
  432. static void encodeCharacterToStream(std::ostream &target, DsrChar character) {
  433. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  434. // Replace any illegal characters with questionmarks
  435. if (character > 255) { character = U'?'; }
  436. byteToStream(target, character);
  437. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  438. if (character < (1 << 7)) {
  439. // 0xxxxxxx
  440. byteToStream(target, character);
  441. } else if (character < (1 << 11)) {
  442. // 110xxxxx 10xxxxxx
  443. byteToStream(target, 0b11000000 | ((character & (0b11111 << 6)) >> 6));
  444. byteToStream(target, 0b10000000 | (character & 0b111111));
  445. } else if (character < (1 << 16)) {
  446. // 1110xxxx 10xxxxxx 10xxxxxx
  447. byteToStream(target, 0b11100000 | ((character & (0b1111 << 12)) >> 12));
  448. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  449. byteToStream(target, 0b10000000 | (character & 0b111111));
  450. } else if (character < (1 << 21)) {
  451. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  452. byteToStream(target, 0b11110000 | ((character & (0b111 << 18)) >> 18));
  453. byteToStream(target, 0b10000000 | ((character & (0b111111 << 12)) >> 12));
  454. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  455. byteToStream(target, 0b10000000 | (character & 0b111111));
  456. }
  457. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  458. throwError(U"Saving text files in UTF-16 BE is not yet implemented.\n");
  459. } else { // Assuming that characterEncoding == CharacterEncoding::BOM_UTF16LE
  460. throwError(U"Saving text files in UTF-16 LE is not yet implemented.\n");
  461. }
  462. }
  463. // Template for writing a whole string to a file
  464. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  465. static void writeCharacterToStream(std::ostream &target, String content) {
  466. // Write byte order marks
  467. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  468. byteToStream(target, 0xEF);
  469. byteToStream(target, 0xBB);
  470. byteToStream(target, 0xBF);
  471. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  472. byteToStream(target, 0xFE);
  473. byteToStream(target, 0xFF);
  474. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  475. byteToStream(target, 0xFF);
  476. byteToStream(target, 0xFE);
  477. }
  478. // Write encoded content
  479. for (int i = 0; i < string_length(content); i++) {
  480. DsrChar character = content[i];
  481. if (character == U'\n') {
  482. if (lineEncoding == LineEncoding::CrLf) {
  483. encodeCharacterToStream<characterEncoding>(target, U'\r');
  484. encodeCharacterToStream<characterEncoding>(target, U'\n');
  485. } else if (lineEncoding == LineEncoding::LfCr) {
  486. encodeCharacterToStream<characterEncoding>(target, U'\n');
  487. encodeCharacterToStream<characterEncoding>(target, U'\r');
  488. } else { // Assuming that lineEncoding == LineEncoding::Lf
  489. encodeCharacterToStream<characterEncoding>(target, U'\n');
  490. }
  491. } else {
  492. encodeCharacterToStream<characterEncoding>(target, character);
  493. }
  494. }
  495. }
  496. // Macros for dynamcally selecting templates
  497. #define WRITE_TEXT_STRING(CHAR_ENCODING, LINE_ENCODING) \
  498. writeCharacterToStream<CHAR_ENCODING, LINE_ENCODING>(fileStream, content);
  499. #define WRITE_TEXT_LINE_ENCODINGS(CHAR_ENCODING) \
  500. if (lineEncoding == LineEncoding::CrLf) { \
  501. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::CrLf); \
  502. } else if (lineEncoding == LineEncoding::Lf) { \
  503. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::Lf); \
  504. } else if (lineEncoding == LineEncoding::LfCr) { \
  505. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::LfCr); \
  506. }
  507. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  508. // TODO: Load files using Unicode filenames
  509. TO_RAW_ASCII(asciiFilename, filename);
  510. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  511. if (fileStream.is_open()) {
  512. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  513. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::Raw_Latin1);
  514. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  515. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF8);
  516. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  517. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16BE);
  518. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  519. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16LE);
  520. }
  521. fileStream.close();
  522. } else {
  523. throwError("Failed to save ", filename, "\n");
  524. }
  525. }
  526. const char32_t* dsr::file_separator() {
  527. #ifdef _WIN32
  528. return U"\\";
  529. #else
  530. return U"/";
  531. #endif
  532. }
  533. int ReadableString::length() const {
  534. return this->sectionLength;
  535. }
  536. bool ReadableString::checkBound(int start, int length, bool warning) const {
  537. if (start < 0 || start + length > this->length()) {
  538. if (warning) {
  539. String message;
  540. string_append(message, U"\n");
  541. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  542. string_append(message, U"/\n");
  543. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  544. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  545. string_append(message, U"\\_______________________________________________________________________\n");
  546. throwError(message);
  547. }
  548. return false;
  549. } else {
  550. return true;
  551. }
  552. }
  553. DsrChar ReadableString::read(int index) const {
  554. if (index < 0 || index >= this->sectionLength) {
  555. return '\0';
  556. } else {
  557. return this->readSection[index];
  558. }
  559. }
  560. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  561. ReadableString::ReadableString() {}
  562. ReadableString::~ReadableString() {}
  563. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  564. : readSection(content), sectionLength(sectionLength) {}
  565. ReadableString::ReadableString(const DsrChar *content)
  566. : readSection(content), sectionLength(strlen_utf32(content)) {}
  567. String::String() {}
  568. String::String(const char* source) { this->append(source); }
  569. String::String(const char32_t* source) { this->append(source); }
  570. String::String(const std::string& source) { this->append(source); }
  571. String::String(const ReadableString& source) { this->append(source); }
  572. String::String(const String& source) { this->append(source); }
  573. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  574. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  575. int String::capacity() {
  576. if (this->buffer.get() == nullptr) {
  577. return 0;
  578. } else {
  579. // Get the parent allocation
  580. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  581. // Get the offset from the parent
  582. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  583. // Subtract offset from the buffer size to get the remaining space
  584. return (this->buffer->size - offset) / sizeof(DsrChar);
  585. }
  586. }
  587. ReadableString ReadableString::getRange(int start, int length) const {
  588. if (length < 1) {
  589. return ReadableString();
  590. } else if (this->checkBound(start, length)) {
  591. return ReadableString(&(this->readSection[start]), length);
  592. } else {
  593. return ReadableString();
  594. }
  595. }
  596. ReadableString String::getRange(int start, int length) const {
  597. if (length < 1) {
  598. return ReadableString();
  599. } else if (this->checkBound(start, length)) {
  600. return String(this->buffer, &(this->writeSection[start]), length);
  601. } else {
  602. return ReadableString();
  603. }
  604. }
  605. static int32_t getNewBufferSize(int32_t minimumSize) {
  606. if (minimumSize <= 128) {
  607. return 128;
  608. } else if (minimumSize <= 512) {
  609. return 512;
  610. } else if (minimumSize <= 2048) {
  611. return 2048;
  612. } else if (minimumSize <= 8192) {
  613. return 8192;
  614. } else if (minimumSize <= 32768) {
  615. return 32768;
  616. } else if (minimumSize <= 131072) {
  617. return 131072;
  618. } else if (minimumSize <= 524288) {
  619. return 524288;
  620. } else if (minimumSize <= 2097152) {
  621. return 2097152;
  622. } else if (minimumSize <= 8388608) {
  623. return 8388608;
  624. } else if (minimumSize <= 33554432) {
  625. return 33554432;
  626. } else if (minimumSize <= 134217728) {
  627. return 134217728;
  628. } else if (minimumSize <= 536870912) {
  629. return 536870912;
  630. } else {
  631. return 2147483647;
  632. }
  633. }
  634. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  635. // Holding oldData alive while copying to the new buffer
  636. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  637. const char32_t* oldData = this->readSection;
  638. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  639. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  640. if (preserve && oldData) {
  641. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  642. }
  643. }
  644. // Call before writing to the buffer
  645. // This hides that Strings share buffers when assigning by value or taking partial strings
  646. void String::cloneIfShared() {
  647. if (this->buffer.use_count() > 1) {
  648. this->reallocateBuffer(this->sectionLength, true);
  649. }
  650. }
  651. void String::expand(int32_t newLength, bool affectUsedLength) {
  652. if (newLength > this->sectionLength) {
  653. if (newLength > this->capacity()) {
  654. this->reallocateBuffer(newLength, true);
  655. }
  656. }
  657. if (affectUsedLength) {
  658. this->sectionLength = newLength;
  659. }
  660. }
  661. void String::reserve(int32_t minimumLength) {
  662. this->expand(minimumLength, false);
  663. }
  664. void String::write(int index, DsrChar value) {
  665. this->cloneIfShared();
  666. if (index < 0 || index >= this->sectionLength) {
  667. // TODO: Give a warning
  668. } else {
  669. this->writeSection[index] = value;
  670. }
  671. }
  672. void String::clear() {
  673. this->sectionLength = 0;
  674. }
  675. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  676. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  677. // Proof that appending to one string doesn't affect another:
  678. // If it has to reallocate
  679. // * Then it will have its own buffer without conflicts
  680. // If it doesn't have to reallocate
  681. // If it shares the buffer
  682. // If source is empty
  683. // * Then no risk of overwriting neighbor strings if we don't write
  684. // If source isn't empty
  685. // * Then the buffer will be cloned when the first character is written
  686. // If it doesn't share the buffer
  687. // * Then no risk of writing
  688. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  689. int64_t oldLength = (TARGET)->length(); \
  690. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  691. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  692. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  693. } \
  694. }
  695. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  696. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  697. // TODO: Use memcpy when appending input of the same format
  698. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  699. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  700. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  701. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  702. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  703. return source.toStreamIndented(target, indentation);
  704. }
  705. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  706. target.append(indentation);
  707. target.append(value);
  708. return target;
  709. }
  710. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  711. target.append(indentation);
  712. target.append(value);
  713. return target;
  714. }
  715. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  716. target.append(indentation);
  717. target.append(value);
  718. return target;
  719. }
  720. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  721. target.append(indentation);
  722. target.append(value);
  723. return target;
  724. }
  725. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  726. target.append(indentation);
  727. doubleToString_arabic(target, (double)value);
  728. return target;
  729. }
  730. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  731. target.append(indentation);
  732. doubleToString_arabic(target, value);
  733. return target;
  734. }
  735. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  736. target.append(indentation);
  737. intToString_arabic(target, value);
  738. return target;
  739. }
  740. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  741. target.append(indentation);
  742. uintToString_arabic(target, value);
  743. return target;
  744. }
  745. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  746. target.append(indentation);
  747. intToString_arabic(target, (int64_t)value);
  748. return target;
  749. }
  750. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  751. target.append(indentation);
  752. uintToString_arabic(target, (uint64_t)value);
  753. return target;
  754. }
  755. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  756. target.append(indentation);
  757. intToString_arabic(target, (int64_t)value);
  758. return target;
  759. }
  760. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  761. target.append(indentation);
  762. uintToString_arabic(target, (uint64_t)value);
  763. return target;
  764. }
  765. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  766. target.append(indentation);
  767. intToString_arabic(target, (int64_t)value);
  768. return target;
  769. }
  770. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  771. target.append(indentation);
  772. uintToString_arabic(target, (uint64_t)value);
  773. return target;
  774. }
  775. void dsr::throwErrorMessage(const String& message) {
  776. throw std::runtime_error(message.toStdString());
  777. }
  778. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  779. if (!appendResult) {
  780. target.clear();
  781. }
  782. int sectionStart = 0;
  783. for (int i = 0; i < source.length(); i++) {
  784. DsrChar c = source[i];
  785. if (c == separator) {
  786. target.push(string_exclusiveRange(source, sectionStart, i));
  787. sectionStart = i + 1;
  788. }
  789. }
  790. if (source.length() > sectionStart) {
  791. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  792. }
  793. }
  794. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  795. List<ReadableString> result;
  796. string_split_inPlace(result, source, separator);
  797. return result;
  798. }
  799. int64_t dsr::string_toInteger(const ReadableString& source) {
  800. int64_t result;
  801. bool negated;
  802. result = 0;
  803. negated = false;
  804. for (int i = 0; i < source.length(); i++) {
  805. DsrChar c = source[i];
  806. if (c == '-' || c == '~') {
  807. negated = !negated;
  808. } else if (c >= '0' && c <= '9') {
  809. result = (result * 10) + (int)(c - '0');
  810. } else if (c == ',' || c == '.') {
  811. // Truncate any decimals by ignoring them
  812. break;
  813. }
  814. }
  815. if (negated) {
  816. return -result;
  817. } else {
  818. return result;
  819. }
  820. }
  821. double dsr::string_toDouble(const ReadableString& source) {
  822. double result;
  823. bool negated;
  824. bool reachedDecimal;
  825. int digitDivider;
  826. result = 0.0;
  827. negated = false;
  828. reachedDecimal = false;
  829. digitDivider = 1;
  830. for (int i = 0; i < source.length(); i++) {
  831. DsrChar c = source[i];
  832. if (c == '-' || c == '~') {
  833. negated = !negated;
  834. } else if (c >= '0' && c <= '9') {
  835. if (reachedDecimal) {
  836. digitDivider = digitDivider * 10;
  837. result = result + ((double)(c - '0') / (double)digitDivider);
  838. } else {
  839. result = (result * 10) + (double)(c - '0');
  840. }
  841. } else if (c == ',' || c == '.') {
  842. reachedDecimal = true;
  843. }
  844. }
  845. if (negated) {
  846. return -result;
  847. } else {
  848. return result;
  849. }
  850. }
  851. int dsr::string_length(const ReadableString& source) {
  852. return source.length();
  853. }
  854. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  855. for (int i = startIndex; i < source.length(); i++) {
  856. if (source[i] == toFind) {
  857. return i;
  858. }
  859. }
  860. return -1;
  861. }
  862. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  863. for (int i = source.length() - 1; i >= 0; i--) {
  864. if (source[i] == toFind) {
  865. return i;
  866. }
  867. }
  868. return -1;
  869. }
  870. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  871. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  872. }
  873. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  874. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  875. }
  876. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  877. return string_exclusiveRange(source, 0, exclusiveEnd);
  878. }
  879. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  880. return string_inclusiveRange(source, 0, inclusiveEnd);
  881. }
  882. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  883. return string_exclusiveRange(source, inclusiveStart, source.length());
  884. }
  885. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  886. return string_from(source, exclusiveStart + 1);
  887. }
  888. bool dsr::character_isDigit(DsrChar c) {
  889. return c >= U'0' && c <= U'9';
  890. }
  891. bool dsr::character_isIntegerCharacter(DsrChar c) {
  892. return c == U'-' || character_isDigit(c);
  893. }
  894. bool dsr::character_isValueCharacter(DsrChar c) {
  895. return c == U'.' || character_isIntegerCharacter(c);
  896. }
  897. bool dsr::character_isWhiteSpace(DsrChar c) {
  898. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  899. }
  900. // Macros for implementing regular expressions with a greedy approach consuming the first match
  901. // Optional accepts 0 or 1 occurence
  902. // Forced accepts 1 occurence
  903. // Star accepts 0..N occurence
  904. // Plus accepts 1..N occurence
  905. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  906. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  907. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  908. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  909. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  910. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  911. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  912. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  913. // The greedy approach works here, because there's no ambiguity
  914. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  915. int readIndex = 0;
  916. if (allowWhiteSpace) {
  917. PATTERN_STAR(WhiteSpace);
  918. }
  919. CHARACTER_OPTIONAL(U'-');
  920. // At least one digit required
  921. PATTERN_PLUS(IntegerCharacter);
  922. if (allowWhiteSpace) {
  923. PATTERN_STAR(WhiteSpace);
  924. }
  925. return true;
  926. }
  927. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  928. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  929. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  930. if (string_findFirst(source, U'.') == -1) {
  931. // No decimal detected
  932. return string_isInteger(source, allowWhiteSpace);
  933. } else {
  934. int readIndex = 0;
  935. if (allowWhiteSpace) {
  936. PATTERN_STAR(WhiteSpace);
  937. }
  938. // Double <- UnsignedDouble | '-' UnsignedDouble
  939. CHARACTER_OPTIONAL(U'-');
  940. // UnsignedDouble <- Digit* '.' Digit+
  941. // Any number of integer digits
  942. PATTERN_STAR(IntegerCharacter);
  943. // Only dot for decimal
  944. CHARACTER_FORCED(U'.')
  945. // At least one decimal digit
  946. PATTERN_PLUS(IntegerCharacter);
  947. if (allowWhiteSpace) {
  948. PATTERN_STAR(WhiteSpace);
  949. }
  950. return true;
  951. }
  952. }