text.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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) + 0x10000));
  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 code = character - 0x10000;
  508. uint32_t higher10Bits = (code & 0b11111111110000000000) >> 10;
  509. uint32_t lower10Bits = code & 0b00000000001111111111;
  510. uint32_t byteA = (0b110110 << 2) | ((higher10Bits & (0b11 << 8)) >> 8);
  511. uint32_t byteB = higher10Bits & 0b11111111;
  512. uint32_t byteC = (0b110111 << 2) | ((lower10Bits & (0b11 << 8)) >> 8);
  513. uint32_t byteD = lower10Bits & 0b11111111;
  514. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  515. byteToStream(target, byteA);
  516. byteToStream(target, byteB);
  517. byteToStream(target, byteC);
  518. byteToStream(target, byteD);
  519. } else { // Assuming UTF-16 LE
  520. byteToStream(target, byteB);
  521. byteToStream(target, byteA);
  522. byteToStream(target, byteD);
  523. byteToStream(target, byteC);
  524. }
  525. }
  526. }
  527. }
  528. // Template for writing a whole string to a file
  529. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  530. static void writeCharacterToStream(std::ostream &target, String content) {
  531. // Write byte order marks
  532. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  533. byteToStream(target, 0xEF);
  534. byteToStream(target, 0xBB);
  535. byteToStream(target, 0xBF);
  536. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  537. byteToStream(target, 0xFE);
  538. byteToStream(target, 0xFF);
  539. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  540. byteToStream(target, 0xFF);
  541. byteToStream(target, 0xFE);
  542. }
  543. // Write encoded content
  544. for (int i = 0; i < string_length(content); i++) {
  545. DsrChar character = content[i];
  546. if (character == U'\n') {
  547. if (lineEncoding == LineEncoding::CrLf) {
  548. encodeCharacterToStream<characterEncoding>(target, U'\r');
  549. encodeCharacterToStream<characterEncoding>(target, U'\n');
  550. } else { // Assuming that lineEncoding == LineEncoding::Lf
  551. encodeCharacterToStream<characterEncoding>(target, U'\n');
  552. }
  553. } else {
  554. encodeCharacterToStream<characterEncoding>(target, character);
  555. }
  556. }
  557. }
  558. // Macros for dynamcally selecting templates
  559. #define WRITE_TEXT_STRING(CHAR_ENCODING, LINE_ENCODING) \
  560. writeCharacterToStream<CHAR_ENCODING, LINE_ENCODING>(fileStream, content);
  561. #define WRITE_TEXT_LINE_ENCODINGS(CHAR_ENCODING) \
  562. if (lineEncoding == LineEncoding::CrLf) { \
  563. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::CrLf); \
  564. } else if (lineEncoding == LineEncoding::Lf) { \
  565. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::Lf); \
  566. }
  567. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  568. // TODO: Load files using Unicode filenames
  569. TO_RAW_ASCII(asciiFilename, filename);
  570. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  571. if (fileStream.is_open()) {
  572. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  573. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::Raw_Latin1);
  574. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  575. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF8);
  576. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  577. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16BE);
  578. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  579. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16LE);
  580. }
  581. fileStream.close();
  582. } else {
  583. throwError("Failed to save ", filename, "\n");
  584. }
  585. }
  586. const char32_t* dsr::file_separator() {
  587. #ifdef _WIN32
  588. return U"\\";
  589. #else
  590. return U"/";
  591. #endif
  592. }
  593. int ReadableString::length() const {
  594. return this->sectionLength;
  595. }
  596. bool ReadableString::checkBound(int start, int length, bool warning) const {
  597. if (start < 0 || start + length > this->length()) {
  598. if (warning) {
  599. String message;
  600. string_append(message, U"\n");
  601. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  602. string_append(message, U"/\n");
  603. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  604. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  605. string_append(message, U"\\_______________________________________________________________________\n");
  606. throwError(message);
  607. }
  608. return false;
  609. } else {
  610. return true;
  611. }
  612. }
  613. DsrChar ReadableString::read(int index) const {
  614. if (index < 0 || index >= this->sectionLength) {
  615. return '\0';
  616. } else {
  617. return this->readSection[index];
  618. }
  619. }
  620. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  621. ReadableString::ReadableString() {}
  622. ReadableString::~ReadableString() {}
  623. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  624. : readSection(content), sectionLength(sectionLength) {}
  625. ReadableString::ReadableString(const DsrChar *content)
  626. : readSection(content), sectionLength(strlen_utf32(content)) {}
  627. String::String() {}
  628. String::String(const char* source) { this->append(source); }
  629. String::String(const char32_t* source) { this->append(source); }
  630. String::String(const std::string& source) { this->append(source); }
  631. String::String(const ReadableString& source) { this->append(source); }
  632. String::String(const String& source) { this->append(source); }
  633. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  634. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  635. int String::capacity() {
  636. if (this->buffer.get() == nullptr) {
  637. return 0;
  638. } else {
  639. // Get the parent allocation
  640. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  641. // Get the offset from the parent
  642. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  643. // Subtract offset from the buffer size to get the remaining space
  644. return (this->buffer->size - offset) / sizeof(DsrChar);
  645. }
  646. }
  647. ReadableString ReadableString::getRange(int start, int length) const {
  648. if (length < 1) {
  649. return ReadableString();
  650. } else if (this->checkBound(start, length)) {
  651. return ReadableString(&(this->readSection[start]), length);
  652. } else {
  653. return ReadableString();
  654. }
  655. }
  656. ReadableString String::getRange(int start, int length) const {
  657. if (length < 1) {
  658. return ReadableString();
  659. } else if (this->checkBound(start, length)) {
  660. return String(this->buffer, &(this->writeSection[start]), length);
  661. } else {
  662. return ReadableString();
  663. }
  664. }
  665. static int32_t getNewBufferSize(int32_t minimumSize) {
  666. if (minimumSize <= 128) {
  667. return 128;
  668. } else if (minimumSize <= 512) {
  669. return 512;
  670. } else if (minimumSize <= 2048) {
  671. return 2048;
  672. } else if (minimumSize <= 8192) {
  673. return 8192;
  674. } else if (minimumSize <= 32768) {
  675. return 32768;
  676. } else if (minimumSize <= 131072) {
  677. return 131072;
  678. } else if (minimumSize <= 524288) {
  679. return 524288;
  680. } else if (minimumSize <= 2097152) {
  681. return 2097152;
  682. } else if (minimumSize <= 8388608) {
  683. return 8388608;
  684. } else if (minimumSize <= 33554432) {
  685. return 33554432;
  686. } else if (minimumSize <= 134217728) {
  687. return 134217728;
  688. } else if (minimumSize <= 536870912) {
  689. return 536870912;
  690. } else {
  691. return 2147483647;
  692. }
  693. }
  694. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  695. // Holding oldData alive while copying to the new buffer
  696. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  697. const char32_t* oldData = this->readSection;
  698. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  699. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  700. if (preserve && oldData) {
  701. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  702. }
  703. }
  704. // Call before writing to the buffer
  705. // This hides that Strings share buffers when assigning by value or taking partial strings
  706. void String::cloneIfShared() {
  707. if (this->buffer.use_count() > 1) {
  708. this->reallocateBuffer(this->sectionLength, true);
  709. }
  710. }
  711. void String::expand(int32_t newLength, bool affectUsedLength) {
  712. if (newLength > this->sectionLength) {
  713. if (newLength > this->capacity()) {
  714. this->reallocateBuffer(newLength, true);
  715. }
  716. }
  717. if (affectUsedLength) {
  718. this->sectionLength = newLength;
  719. }
  720. }
  721. void String::reserve(int32_t minimumLength) {
  722. this->expand(minimumLength, false);
  723. }
  724. void String::write(int index, DsrChar value) {
  725. this->cloneIfShared();
  726. if (index < 0 || index >= this->sectionLength) {
  727. // TODO: Give a warning
  728. } else {
  729. this->writeSection[index] = value;
  730. }
  731. }
  732. void String::clear() {
  733. this->sectionLength = 0;
  734. }
  735. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  736. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  737. // Proof that appending to one string doesn't affect another:
  738. // If it has to reallocate
  739. // * Then it will have its own buffer without conflicts
  740. // If it doesn't have to reallocate
  741. // If it shares the buffer
  742. // If source is empty
  743. // * Then no risk of overwriting neighbor strings if we don't write
  744. // If source isn't empty
  745. // * Then the buffer will be cloned when the first character is written
  746. // If it doesn't share the buffer
  747. // * Then no risk of writing
  748. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  749. int64_t oldLength = (TARGET)->length(); \
  750. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  751. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  752. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  753. } \
  754. }
  755. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  756. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  757. // TODO: Use memcpy when appending input of the same format
  758. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  759. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  760. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  761. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  762. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  763. return source.toStreamIndented(target, indentation);
  764. }
  765. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  766. target.append(indentation);
  767. target.append(value);
  768. return target;
  769. }
  770. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  771. target.append(indentation);
  772. target.append(value);
  773. return target;
  774. }
  775. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  776. target.append(indentation);
  777. target.append(value);
  778. return target;
  779. }
  780. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  781. target.append(indentation);
  782. target.append(value);
  783. return target;
  784. }
  785. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  786. target.append(indentation);
  787. doubleToString_arabic(target, (double)value);
  788. return target;
  789. }
  790. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  791. target.append(indentation);
  792. doubleToString_arabic(target, value);
  793. return target;
  794. }
  795. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  796. target.append(indentation);
  797. intToString_arabic(target, value);
  798. return target;
  799. }
  800. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  801. target.append(indentation);
  802. uintToString_arabic(target, value);
  803. return target;
  804. }
  805. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  806. target.append(indentation);
  807. intToString_arabic(target, (int64_t)value);
  808. return target;
  809. }
  810. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  811. target.append(indentation);
  812. uintToString_arabic(target, (uint64_t)value);
  813. return target;
  814. }
  815. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  816. target.append(indentation);
  817. intToString_arabic(target, (int64_t)value);
  818. return target;
  819. }
  820. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  821. target.append(indentation);
  822. uintToString_arabic(target, (uint64_t)value);
  823. return target;
  824. }
  825. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  826. target.append(indentation);
  827. intToString_arabic(target, (int64_t)value);
  828. return target;
  829. }
  830. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  831. target.append(indentation);
  832. uintToString_arabic(target, (uint64_t)value);
  833. return target;
  834. }
  835. void dsr::throwErrorMessage(const String& message) {
  836. throw std::runtime_error(message.toStdString());
  837. }
  838. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  839. if (!appendResult) {
  840. target.clear();
  841. }
  842. int sectionStart = 0;
  843. for (int i = 0; i < source.length(); i++) {
  844. DsrChar c = source[i];
  845. if (c == separator) {
  846. target.push(string_exclusiveRange(source, sectionStart, i));
  847. sectionStart = i + 1;
  848. }
  849. }
  850. if (source.length() > sectionStart) {
  851. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  852. }
  853. }
  854. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  855. List<ReadableString> result;
  856. string_split_inPlace(result, source, separator);
  857. return result;
  858. }
  859. int64_t dsr::string_toInteger(const ReadableString& source) {
  860. int64_t result;
  861. bool negated;
  862. result = 0;
  863. negated = false;
  864. for (int i = 0; i < source.length(); i++) {
  865. DsrChar c = source[i];
  866. if (c == '-' || c == '~') {
  867. negated = !negated;
  868. } else if (c >= '0' && c <= '9') {
  869. result = (result * 10) + (int)(c - '0');
  870. } else if (c == ',' || c == '.') {
  871. // Truncate any decimals by ignoring them
  872. break;
  873. }
  874. }
  875. if (negated) {
  876. return -result;
  877. } else {
  878. return result;
  879. }
  880. }
  881. double dsr::string_toDouble(const ReadableString& source) {
  882. double result;
  883. bool negated;
  884. bool reachedDecimal;
  885. int digitDivider;
  886. result = 0.0;
  887. negated = false;
  888. reachedDecimal = false;
  889. digitDivider = 1;
  890. for (int i = 0; i < source.length(); i++) {
  891. DsrChar c = source[i];
  892. if (c == '-' || c == '~') {
  893. negated = !negated;
  894. } else if (c >= '0' && c <= '9') {
  895. if (reachedDecimal) {
  896. digitDivider = digitDivider * 10;
  897. result = result + ((double)(c - '0') / (double)digitDivider);
  898. } else {
  899. result = (result * 10) + (double)(c - '0');
  900. }
  901. } else if (c == ',' || c == '.') {
  902. reachedDecimal = true;
  903. }
  904. }
  905. if (negated) {
  906. return -result;
  907. } else {
  908. return result;
  909. }
  910. }
  911. int dsr::string_length(const ReadableString& source) {
  912. return source.length();
  913. }
  914. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  915. for (int i = startIndex; i < source.length(); i++) {
  916. if (source[i] == toFind) {
  917. return i;
  918. }
  919. }
  920. return -1;
  921. }
  922. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  923. for (int i = source.length() - 1; i >= 0; i--) {
  924. if (source[i] == toFind) {
  925. return i;
  926. }
  927. }
  928. return -1;
  929. }
  930. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  931. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  932. }
  933. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  934. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  935. }
  936. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  937. return string_exclusiveRange(source, 0, exclusiveEnd);
  938. }
  939. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  940. return string_inclusiveRange(source, 0, inclusiveEnd);
  941. }
  942. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  943. return string_exclusiveRange(source, inclusiveStart, source.length());
  944. }
  945. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  946. return string_from(source, exclusiveStart + 1);
  947. }
  948. bool dsr::character_isDigit(DsrChar c) {
  949. return c >= U'0' && c <= U'9';
  950. }
  951. bool dsr::character_isIntegerCharacter(DsrChar c) {
  952. return c == U'-' || character_isDigit(c);
  953. }
  954. bool dsr::character_isValueCharacter(DsrChar c) {
  955. return c == U'.' || character_isIntegerCharacter(c);
  956. }
  957. bool dsr::character_isWhiteSpace(DsrChar c) {
  958. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  959. }
  960. // Macros for implementing regular expressions with a greedy approach consuming the first match
  961. // Optional accepts 0 or 1 occurence
  962. // Forced accepts 1 occurence
  963. // Star accepts 0..N occurence
  964. // Plus accepts 1..N occurence
  965. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  966. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  967. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  968. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  969. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  970. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  971. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  972. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  973. // The greedy approach works here, because there's no ambiguity
  974. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  975. int readIndex = 0;
  976. if (allowWhiteSpace) {
  977. PATTERN_STAR(WhiteSpace);
  978. }
  979. CHARACTER_OPTIONAL(U'-');
  980. // At least one digit required
  981. PATTERN_PLUS(IntegerCharacter);
  982. if (allowWhiteSpace) {
  983. PATTERN_STAR(WhiteSpace);
  984. }
  985. return true;
  986. }
  987. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  988. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  989. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  990. if (string_findFirst(source, U'.') == -1) {
  991. // No decimal detected
  992. return string_isInteger(source, allowWhiteSpace);
  993. } else {
  994. int readIndex = 0;
  995. if (allowWhiteSpace) {
  996. PATTERN_STAR(WhiteSpace);
  997. }
  998. // Double <- UnsignedDouble | '-' UnsignedDouble
  999. CHARACTER_OPTIONAL(U'-');
  1000. // UnsignedDouble <- Digit* '.' Digit+
  1001. // Any number of integer digits
  1002. PATTERN_STAR(IntegerCharacter);
  1003. // Only dot for decimal
  1004. CHARACTER_FORCED(U'.')
  1005. // At least one decimal digit
  1006. PATTERN_PLUS(IntegerCharacter);
  1007. if (allowWhiteSpace) {
  1008. PATTERN_STAR(WhiteSpace);
  1009. }
  1010. return true;
  1011. }
  1012. }