text.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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 most 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. template <bool LittleEndian>
  364. uint16_t read16bits(const uint8_t* buffer, int startOffset) {
  365. uint16_t byteA = buffer[startOffset];
  366. uint16_t byteB = buffer[startOffset + 1];
  367. if (LittleEndian) {
  368. return (byteB << 8) | byteA;
  369. } else {
  370. return (byteA << 8) | byteB;
  371. }
  372. }
  373. // Appends the content of buffer as a BOM-free UTF-16 file into target
  374. template <bool LittleEndian>
  375. static void AppendStringFromFileBuffer_UTF16(String &target, const uint8_t* buffer, int64_t fileLength) {
  376. // We know that the result will be at most one character per two given bytes for UTF-16
  377. target.reserve(string_length(target) + (fileLength / 2));
  378. for (int64_t i = 0; i < fileLength; i += 2) {
  379. // Read the first 16-bit word
  380. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  381. // Check if another word is needed
  382. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  383. // we can just check if it's within the range reserved for 32-bit encoding
  384. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  385. // Not in the reserved range, just a single 16-bit character
  386. feedCharacterFromFile(target, (DsrChar)wordA);
  387. } else {
  388. // The given range was reserved and therefore using 32 bits
  389. i += 2;
  390. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  391. uint32_t higher10Bits = wordA & 0b1111111111;
  392. uint32_t lower10Bits = wordB & 0b1111111111;
  393. feedCharacterFromFile(target, (DsrChar)((higher10Bits << 10) | lower10Bits));
  394. }
  395. }
  396. }
  397. // Appends the content of buffer as a text file of unknown format into target
  398. static void AppendStringFromFileBuffer(String &target, const uint8_t* buffer, int64_t fileLength) {
  399. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  400. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  401. AppendStringFromFileBuffer_UTF8(target, buffer + 3, fileLength - 3);
  402. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  403. AppendStringFromFileBuffer_UTF16<false>(target, buffer + 2, fileLength - 2);
  404. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  405. AppendStringFromFileBuffer_UTF16<true>(target, buffer + 2, fileLength - 2);
  406. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  407. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  408. throwError(U"UTF-32 BE format is not yet supported!\n");
  409. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  410. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  411. throwError(U"UTF-32 LE format is not yet supported!\n");
  412. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  413. //AppendStringFromFileBuffer_UTF1(target, buffer + 3, fileLength - 3);
  414. throwError(U"UTF-1 format is not yet supported!\n");
  415. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  416. //AppendStringFromFileBuffer_SCSU(target, buffer + 3, fileLength - 3);
  417. throwError(U"SCSU format is not yet supported!\n");
  418. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  419. //AppendStringFromFileBuffer_BOCU-1(target, buffer + 3, fileLength - 3);
  420. throwError(U"BOCU-1 format is not yet supported!\n");
  421. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  422. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  423. throwError(U"UTF-7 format is not yet supported!\n");
  424. } else {
  425. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  426. AppendStringFromFileBuffer_Latin1(target, buffer, fileLength);
  427. }
  428. }
  429. String dsr::string_loadFromMemory(const Buffer &fileContent) {
  430. String result;
  431. AppendStringFromFileBuffer(result, fileContent.getUnsafeData(), fileContent.size);
  432. return result;
  433. }
  434. // Loads a text file of unknown format
  435. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines.
  436. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  437. // TODO: Load files using Unicode filenames when available
  438. TO_RAW_ASCII(asciiFilename, filename);
  439. std::ifstream fileStream(asciiFilename, std::ios_base::in | std::ios_base::binary);
  440. if (fileStream.is_open()) {
  441. String result;
  442. // Get the file's length and allocate an array for the raw encoding
  443. fileStream.seekg (0, fileStream.end);
  444. int64_t fileLength = fileStream.tellg();
  445. fileStream.seekg (0, fileStream.beg);
  446. uint8_t* buffer = (uint8_t*)malloc(fileLength);
  447. fileStream.read((char*)buffer, fileLength);
  448. AppendStringFromFileBuffer(result, buffer, fileLength);
  449. free(buffer);
  450. return result;
  451. } else {
  452. if (mustExist) {
  453. throwError(U"The text file ", filename, U" could not be opened for reading.\n");
  454. }
  455. // If the file cound not be found and opened, a null string is returned
  456. return String();
  457. }
  458. }
  459. static inline void byteToStream(std::ostream &target, int value) {
  460. uint8_t byte = value;
  461. target.write((char*)&byte, 1);
  462. }
  463. #define AT_MOST_BITS(BIT_COUNT) if (character >= 1 << BIT_COUNT) { character = U'?'; }
  464. template <CharacterEncoding characterEncoding>
  465. static void encodeCharacterToStream(std::ostream &target, DsrChar character) {
  466. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  467. // Replace any illegal characters with questionmarks
  468. AT_MOST_BITS(8);
  469. byteToStream(target, character);
  470. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  471. // Replace any illegal characters with questionmarks
  472. AT_MOST_BITS(21);
  473. if (character < (1 << 7)) {
  474. // 0xxxxxxx
  475. byteToStream(target, character);
  476. } else if (character < (1 << 11)) {
  477. // 110xxxxx 10xxxxxx
  478. byteToStream(target, 0b11000000 | ((character & (0b11111 << 6)) >> 6));
  479. byteToStream(target, 0b10000000 | (character & 0b111111));
  480. } else if (character < (1 << 16)) {
  481. // 1110xxxx 10xxxxxx 10xxxxxx
  482. byteToStream(target, 0b11100000 | ((character & (0b1111 << 12)) >> 12));
  483. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  484. byteToStream(target, 0b10000000 | (character & 0b111111));
  485. } else if (character < (1 << 21)) {
  486. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  487. byteToStream(target, 0b11110000 | ((character & (0b111 << 18)) >> 18));
  488. byteToStream(target, 0b10000000 | ((character & (0b111111 << 12)) >> 12));
  489. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  490. byteToStream(target, 0b10000000 | (character & 0b111111));
  491. }
  492. } else { // Assuming UTF-16
  493. AT_MOST_BITS(20);
  494. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  495. // xxxxxxxx xxxxxxxx (Limited range)
  496. uint32_t higher8Bits = (character & 0b1111111100000000) >> 8;
  497. uint32_t lower8Bits = character & 0b0000000011111111;
  498. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  499. byteToStream(target, higher8Bits);
  500. byteToStream(target, lower8Bits);
  501. } else { // Assuming UTF-16 LE
  502. byteToStream(target, lower8Bits);
  503. byteToStream(target, higher8Bits);
  504. }
  505. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  506. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  507. uint32_t higher10Bits = (character & 0b11111111110000000000) >> 10;
  508. uint32_t lower10Bits = character & 0b00000000001111111111;
  509. uint32_t byteA = (0b110110 << 2) | ((higher10Bits & (0b11 << 8)) >> 8);
  510. uint32_t byteB = higher10Bits & 0b11111111;
  511. uint32_t byteC = (0b110111 << 2) | ((lower10Bits & (0b11 << 8)) >> 8);
  512. uint32_t byteD = lower10Bits & 0b11111111;
  513. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  514. byteToStream(target, byteA);
  515. byteToStream(target, byteB);
  516. byteToStream(target, byteC);
  517. byteToStream(target, byteD);
  518. } else { // Assuming UTF-16 LE
  519. byteToStream(target, byteB);
  520. byteToStream(target, byteA);
  521. byteToStream(target, byteD);
  522. byteToStream(target, byteC);
  523. }
  524. }
  525. }
  526. }
  527. // Template for writing a whole string to a file
  528. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  529. static void writeCharacterToStream(std::ostream &target, String content) {
  530. // Write byte order marks
  531. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  532. byteToStream(target, 0xEF);
  533. byteToStream(target, 0xBB);
  534. byteToStream(target, 0xBF);
  535. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  536. byteToStream(target, 0xFE);
  537. byteToStream(target, 0xFF);
  538. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  539. byteToStream(target, 0xFF);
  540. byteToStream(target, 0xFE);
  541. }
  542. // Write encoded content
  543. for (int i = 0; i < string_length(content); i++) {
  544. DsrChar character = content[i];
  545. if (character == U'\n') {
  546. if (lineEncoding == LineEncoding::CrLf) {
  547. encodeCharacterToStream<characterEncoding>(target, U'\r');
  548. encodeCharacterToStream<characterEncoding>(target, U'\n');
  549. } else { // Assuming that lineEncoding == LineEncoding::Lf
  550. encodeCharacterToStream<characterEncoding>(target, U'\n');
  551. }
  552. } else {
  553. encodeCharacterToStream<characterEncoding>(target, character);
  554. }
  555. }
  556. }
  557. // Macros for dynamcally selecting templates
  558. #define WRITE_TEXT_STRING(CHAR_ENCODING, LINE_ENCODING) \
  559. writeCharacterToStream<CHAR_ENCODING, LINE_ENCODING>(fileStream, content);
  560. #define WRITE_TEXT_LINE_ENCODINGS(CHAR_ENCODING) \
  561. if (lineEncoding == LineEncoding::CrLf) { \
  562. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::CrLf); \
  563. } else if (lineEncoding == LineEncoding::Lf) { \
  564. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::Lf); \
  565. }
  566. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  567. // TODO: Load files using Unicode filenames
  568. TO_RAW_ASCII(asciiFilename, filename);
  569. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  570. if (fileStream.is_open()) {
  571. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  572. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::Raw_Latin1);
  573. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  574. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF8);
  575. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  576. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16BE);
  577. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  578. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16LE);
  579. }
  580. fileStream.close();
  581. } else {
  582. throwError("Failed to save ", filename, "\n");
  583. }
  584. }
  585. const char32_t* dsr::file_separator() {
  586. #ifdef _WIN32
  587. return U"\\";
  588. #else
  589. return U"/";
  590. #endif
  591. }
  592. int ReadableString::length() const {
  593. return this->sectionLength;
  594. }
  595. bool ReadableString::checkBound(int start, int length, bool warning) const {
  596. if (start < 0 || start + length > this->length()) {
  597. if (warning) {
  598. String message;
  599. string_append(message, U"\n");
  600. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  601. string_append(message, U"/\n");
  602. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  603. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  604. string_append(message, U"\\_______________________________________________________________________\n");
  605. throwError(message);
  606. }
  607. return false;
  608. } else {
  609. return true;
  610. }
  611. }
  612. DsrChar ReadableString::read(int index) const {
  613. if (index < 0 || index >= this->sectionLength) {
  614. return '\0';
  615. } else {
  616. return this->readSection[index];
  617. }
  618. }
  619. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  620. ReadableString::ReadableString() {}
  621. ReadableString::~ReadableString() {}
  622. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  623. : readSection(content), sectionLength(sectionLength) {}
  624. ReadableString::ReadableString(const DsrChar *content)
  625. : readSection(content), sectionLength(strlen_utf32(content)) {}
  626. String::String() {}
  627. String::String(const char* source) { this->append(source); }
  628. String::String(const char32_t* source) { this->append(source); }
  629. String::String(const std::string& source) { this->append(source); }
  630. String::String(const ReadableString& source) { this->append(source); }
  631. String::String(const String& source) { this->append(source); }
  632. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  633. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  634. int String::capacity() {
  635. if (this->buffer.get() == nullptr) {
  636. return 0;
  637. } else {
  638. // Get the parent allocation
  639. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  640. // Get the offset from the parent
  641. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  642. // Subtract offset from the buffer size to get the remaining space
  643. return (this->buffer->size - offset) / sizeof(DsrChar);
  644. }
  645. }
  646. ReadableString ReadableString::getRange(int start, int length) const {
  647. if (length < 1) {
  648. return ReadableString();
  649. } else if (this->checkBound(start, length)) {
  650. return ReadableString(&(this->readSection[start]), length);
  651. } else {
  652. return ReadableString();
  653. }
  654. }
  655. ReadableString String::getRange(int start, int length) const {
  656. if (length < 1) {
  657. return ReadableString();
  658. } else if (this->checkBound(start, length)) {
  659. return String(this->buffer, &(this->writeSection[start]), length);
  660. } else {
  661. return ReadableString();
  662. }
  663. }
  664. static int32_t getNewBufferSize(int32_t minimumSize) {
  665. if (minimumSize <= 128) {
  666. return 128;
  667. } else if (minimumSize <= 512) {
  668. return 512;
  669. } else if (minimumSize <= 2048) {
  670. return 2048;
  671. } else if (minimumSize <= 8192) {
  672. return 8192;
  673. } else if (minimumSize <= 32768) {
  674. return 32768;
  675. } else if (minimumSize <= 131072) {
  676. return 131072;
  677. } else if (minimumSize <= 524288) {
  678. return 524288;
  679. } else if (minimumSize <= 2097152) {
  680. return 2097152;
  681. } else if (minimumSize <= 8388608) {
  682. return 8388608;
  683. } else if (minimumSize <= 33554432) {
  684. return 33554432;
  685. } else if (minimumSize <= 134217728) {
  686. return 134217728;
  687. } else if (minimumSize <= 536870912) {
  688. return 536870912;
  689. } else {
  690. return 2147483647;
  691. }
  692. }
  693. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  694. // Holding oldData alive while copying to the new buffer
  695. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  696. const char32_t* oldData = this->readSection;
  697. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  698. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  699. if (preserve && oldData) {
  700. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  701. }
  702. }
  703. // Call before writing to the buffer
  704. // This hides that Strings share buffers when assigning by value or taking partial strings
  705. void String::cloneIfShared() {
  706. if (this->buffer.use_count() > 1) {
  707. this->reallocateBuffer(this->sectionLength, true);
  708. }
  709. }
  710. void String::expand(int32_t newLength, bool affectUsedLength) {
  711. if (newLength > this->sectionLength) {
  712. if (newLength > this->capacity()) {
  713. this->reallocateBuffer(newLength, true);
  714. }
  715. }
  716. if (affectUsedLength) {
  717. this->sectionLength = newLength;
  718. }
  719. }
  720. void String::reserve(int32_t minimumLength) {
  721. this->expand(minimumLength, false);
  722. }
  723. void String::write(int index, DsrChar value) {
  724. this->cloneIfShared();
  725. if (index < 0 || index >= this->sectionLength) {
  726. // TODO: Give a warning
  727. } else {
  728. this->writeSection[index] = value;
  729. }
  730. }
  731. void String::clear() {
  732. this->sectionLength = 0;
  733. }
  734. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  735. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  736. // Proof that appending to one string doesn't affect another:
  737. // If it has to reallocate
  738. // * Then it will have its own buffer without conflicts
  739. // If it doesn't have to reallocate
  740. // If it shares the buffer
  741. // If source is empty
  742. // * Then no risk of overwriting neighbor strings if we don't write
  743. // If source isn't empty
  744. // * Then the buffer will be cloned when the first character is written
  745. // If it doesn't share the buffer
  746. // * Then no risk of writing
  747. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  748. int64_t oldLength = (TARGET)->length(); \
  749. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  750. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  751. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  752. } \
  753. }
  754. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  755. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  756. // TODO: Use memcpy when appending input of the same format
  757. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  758. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  759. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  760. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  761. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  762. return source.toStreamIndented(target, indentation);
  763. }
  764. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  765. target.append(indentation);
  766. target.append(value);
  767. return target;
  768. }
  769. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  770. target.append(indentation);
  771. target.append(value);
  772. return target;
  773. }
  774. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  775. target.append(indentation);
  776. target.append(value);
  777. return target;
  778. }
  779. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  780. target.append(indentation);
  781. target.append(value);
  782. return target;
  783. }
  784. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  785. target.append(indentation);
  786. doubleToString_arabic(target, (double)value);
  787. return target;
  788. }
  789. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  790. target.append(indentation);
  791. doubleToString_arabic(target, value);
  792. return target;
  793. }
  794. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  795. target.append(indentation);
  796. intToString_arabic(target, value);
  797. return target;
  798. }
  799. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  800. target.append(indentation);
  801. uintToString_arabic(target, value);
  802. return target;
  803. }
  804. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  805. target.append(indentation);
  806. intToString_arabic(target, (int64_t)value);
  807. return target;
  808. }
  809. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  810. target.append(indentation);
  811. uintToString_arabic(target, (uint64_t)value);
  812. return target;
  813. }
  814. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  815. target.append(indentation);
  816. intToString_arabic(target, (int64_t)value);
  817. return target;
  818. }
  819. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  820. target.append(indentation);
  821. uintToString_arabic(target, (uint64_t)value);
  822. return target;
  823. }
  824. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  825. target.append(indentation);
  826. intToString_arabic(target, (int64_t)value);
  827. return target;
  828. }
  829. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  830. target.append(indentation);
  831. uintToString_arabic(target, (uint64_t)value);
  832. return target;
  833. }
  834. void dsr::throwErrorMessage(const String& message) {
  835. throw std::runtime_error(message.toStdString());
  836. }
  837. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  838. if (!appendResult) {
  839. target.clear();
  840. }
  841. int sectionStart = 0;
  842. for (int i = 0; i < source.length(); i++) {
  843. DsrChar c = source[i];
  844. if (c == separator) {
  845. target.push(string_exclusiveRange(source, sectionStart, i));
  846. sectionStart = i + 1;
  847. }
  848. }
  849. if (source.length() > sectionStart) {
  850. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  851. }
  852. }
  853. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  854. List<ReadableString> result;
  855. string_split_inPlace(result, source, separator);
  856. return result;
  857. }
  858. int64_t dsr::string_toInteger(const ReadableString& source) {
  859. int64_t result;
  860. bool negated;
  861. result = 0;
  862. negated = false;
  863. for (int i = 0; i < source.length(); i++) {
  864. DsrChar c = source[i];
  865. if (c == '-' || c == '~') {
  866. negated = !negated;
  867. } else if (c >= '0' && c <= '9') {
  868. result = (result * 10) + (int)(c - '0');
  869. } else if (c == ',' || c == '.') {
  870. // Truncate any decimals by ignoring them
  871. break;
  872. }
  873. }
  874. if (negated) {
  875. return -result;
  876. } else {
  877. return result;
  878. }
  879. }
  880. double dsr::string_toDouble(const ReadableString& source) {
  881. double result;
  882. bool negated;
  883. bool reachedDecimal;
  884. int digitDivider;
  885. result = 0.0;
  886. negated = false;
  887. reachedDecimal = false;
  888. digitDivider = 1;
  889. for (int i = 0; i < source.length(); i++) {
  890. DsrChar c = source[i];
  891. if (c == '-' || c == '~') {
  892. negated = !negated;
  893. } else if (c >= '0' && c <= '9') {
  894. if (reachedDecimal) {
  895. digitDivider = digitDivider * 10;
  896. result = result + ((double)(c - '0') / (double)digitDivider);
  897. } else {
  898. result = (result * 10) + (double)(c - '0');
  899. }
  900. } else if (c == ',' || c == '.') {
  901. reachedDecimal = true;
  902. }
  903. }
  904. if (negated) {
  905. return -result;
  906. } else {
  907. return result;
  908. }
  909. }
  910. int dsr::string_length(const ReadableString& source) {
  911. return source.length();
  912. }
  913. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  914. for (int i = startIndex; i < source.length(); i++) {
  915. if (source[i] == toFind) {
  916. return i;
  917. }
  918. }
  919. return -1;
  920. }
  921. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  922. for (int i = source.length() - 1; i >= 0; i--) {
  923. if (source[i] == toFind) {
  924. return i;
  925. }
  926. }
  927. return -1;
  928. }
  929. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  930. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  931. }
  932. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  933. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  934. }
  935. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  936. return string_exclusiveRange(source, 0, exclusiveEnd);
  937. }
  938. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  939. return string_inclusiveRange(source, 0, inclusiveEnd);
  940. }
  941. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  942. return string_exclusiveRange(source, inclusiveStart, source.length());
  943. }
  944. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  945. return string_from(source, exclusiveStart + 1);
  946. }
  947. bool dsr::character_isDigit(DsrChar c) {
  948. return c >= U'0' && c <= U'9';
  949. }
  950. bool dsr::character_isIntegerCharacter(DsrChar c) {
  951. return c == U'-' || character_isDigit(c);
  952. }
  953. bool dsr::character_isValueCharacter(DsrChar c) {
  954. return c == U'.' || character_isIntegerCharacter(c);
  955. }
  956. bool dsr::character_isWhiteSpace(DsrChar c) {
  957. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  958. }
  959. // Macros for implementing regular expressions with a greedy approach consuming the first match
  960. // Optional accepts 0 or 1 occurence
  961. // Forced accepts 1 occurence
  962. // Star accepts 0..N occurence
  963. // Plus accepts 1..N occurence
  964. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  965. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  966. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  967. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  968. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  969. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  970. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  971. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  972. // The greedy approach works here, because there's no ambiguity
  973. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  974. int readIndex = 0;
  975. if (allowWhiteSpace) {
  976. PATTERN_STAR(WhiteSpace);
  977. }
  978. CHARACTER_OPTIONAL(U'-');
  979. // At least one digit required
  980. PATTERN_PLUS(IntegerCharacter);
  981. if (allowWhiteSpace) {
  982. PATTERN_STAR(WhiteSpace);
  983. }
  984. return true;
  985. }
  986. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  987. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  988. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  989. if (string_findFirst(source, U'.') == -1) {
  990. // No decimal detected
  991. return string_isInteger(source, allowWhiteSpace);
  992. } else {
  993. int readIndex = 0;
  994. if (allowWhiteSpace) {
  995. PATTERN_STAR(WhiteSpace);
  996. }
  997. // Double <- UnsignedDouble | '-' UnsignedDouble
  998. CHARACTER_OPTIONAL(U'-');
  999. // UnsignedDouble <- Digit* '.' Digit+
  1000. // Any number of integer digits
  1001. PATTERN_STAR(IntegerCharacter);
  1002. // Only dot for decimal
  1003. CHARACTER_FORCED(U'.')
  1004. // At least one decimal digit
  1005. PATTERN_PLUS(IntegerCharacter);
  1006. if (allowWhiteSpace) {
  1007. PATTERN_STAR(WhiteSpace);
  1008. }
  1009. return true;
  1010. }
  1011. }