Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

620 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #ifndef WATER_CHARACTERFUNCTIONS_H_INCLUDED
  21. #define WATER_CHARACTERFUNCTIONS_H_INCLUDED
  22. #include "../memory/Memory.h"
  23. #include <algorithm>
  24. namespace water {
  25. /** A platform-independent 32-bit unicode character type. */
  26. typedef uint32 water_uchar;
  27. //==============================================================================
  28. /**
  29. A collection of functions for manipulating characters and character strings.
  30. Most of these methods are designed for internal use by the String and CharPointer
  31. classes, but some of them may be useful to call directly.
  32. @see String, CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  33. */
  34. class CharacterFunctions
  35. {
  36. public:
  37. //==============================================================================
  38. /** Converts a character to upper-case. */
  39. static water_uchar toUpperCase (water_uchar character) noexcept;
  40. /** Converts a character to lower-case. */
  41. static water_uchar toLowerCase (water_uchar character) noexcept;
  42. /** Checks whether a unicode character is upper-case. */
  43. static bool isUpperCase (water_uchar character) noexcept;
  44. /** Checks whether a unicode character is lower-case. */
  45. static bool isLowerCase (water_uchar character) noexcept;
  46. /** Checks whether a character is whitespace. */
  47. static bool isWhitespace (char character) noexcept;
  48. /** Checks whether a character is whitespace. */
  49. static bool isWhitespace (water_uchar character) noexcept;
  50. /** Checks whether a character is a digit. */
  51. static bool isDigit (char character) noexcept;
  52. /** Checks whether a character is a digit. */
  53. static bool isDigit (water_uchar character) noexcept;
  54. /** Checks whether a character is alphabetic. */
  55. static bool isLetter (char character) noexcept;
  56. /** Checks whether a character is alphabetic. */
  57. static bool isLetter (water_uchar character) noexcept;
  58. /** Checks whether a character is alphabetic or numeric. */
  59. static bool isLetterOrDigit (char character) noexcept;
  60. /** Checks whether a character is alphabetic or numeric. */
  61. static bool isLetterOrDigit (water_uchar character) noexcept;
  62. /** Checks whether a character is a printable character, i.e. alphabetic, numeric,
  63. a punctuation character or a space.
  64. */
  65. static bool isPrintable (char character) noexcept;
  66. /** Checks whether a character is a printable character, i.e. alphabetic, numeric,
  67. a punctuation character or a space.
  68. */
  69. static bool isPrintable (water_uchar character) noexcept;
  70. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  71. static int getHexDigitValue (water_uchar digit) noexcept;
  72. /** Converts a byte of Windows 1252 codepage to unicode. */
  73. static water_uchar getUnicodeCharFromWindows1252Codepage (uint8 windows1252Char) noexcept;
  74. //==============================================================================
  75. /** Parses a character string to read a floating-point number.
  76. Note that this will advance the pointer that is passed in, leaving it at
  77. the end of the number.
  78. */
  79. template <typename CharPointerType>
  80. static double readDoubleValue (CharPointerType& text) noexcept
  81. {
  82. double result[3] = { 0 }, accumulator[2] = { 0 };
  83. int exponentAdjustment[2] = { 0 }, exponentAccumulator[2] = { -1, -1 };
  84. int exponent = 0, decPointIndex = 0, digit = 0;
  85. int lastDigit = 0, numSignificantDigits = 0;
  86. bool isNegative = false, digitsFound = false;
  87. const int maxSignificantDigits = 15 + 2;
  88. text = text.findEndOfWhitespace();
  89. water_uchar c = *text;
  90. switch (c)
  91. {
  92. case '-': isNegative = true; // fall-through..
  93. case '+': c = *++text;
  94. }
  95. switch (c)
  96. {
  97. case 'n':
  98. case 'N':
  99. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  100. return std::numeric_limits<double>::quiet_NaN();
  101. break;
  102. case 'i':
  103. case 'I':
  104. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  105. return std::numeric_limits<double>::infinity();
  106. break;
  107. }
  108. for (;;)
  109. {
  110. if (text.isDigit())
  111. {
  112. lastDigit = digit;
  113. digit = (int) text.getAndAdvance() - '0';
  114. digitsFound = true;
  115. if (decPointIndex != 0)
  116. exponentAdjustment[1]++;
  117. if (numSignificantDigits == 0 && digit == 0)
  118. continue;
  119. if (++numSignificantDigits > maxSignificantDigits)
  120. {
  121. if (digit > 5)
  122. ++accumulator [decPointIndex];
  123. else if (digit == 5 && (lastDigit & 1) != 0)
  124. ++accumulator [decPointIndex];
  125. if (decPointIndex > 0)
  126. exponentAdjustment[1]--;
  127. else
  128. exponentAdjustment[0]++;
  129. while (text.isDigit())
  130. {
  131. ++text;
  132. if (decPointIndex == 0)
  133. exponentAdjustment[0]++;
  134. }
  135. }
  136. else
  137. {
  138. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  139. if (accumulator [decPointIndex] > maxAccumulatorValue)
  140. {
  141. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  142. + accumulator [decPointIndex];
  143. accumulator [decPointIndex] = 0;
  144. exponentAccumulator [decPointIndex] = 0;
  145. }
  146. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  147. exponentAccumulator [decPointIndex]++;
  148. }
  149. }
  150. else if (decPointIndex == 0 && *text == '.')
  151. {
  152. ++text;
  153. decPointIndex = 1;
  154. if (numSignificantDigits > maxSignificantDigits)
  155. {
  156. while (text.isDigit())
  157. ++text;
  158. break;
  159. }
  160. }
  161. else
  162. {
  163. break;
  164. }
  165. }
  166. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  167. if (decPointIndex != 0)
  168. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  169. c = *text;
  170. if ((c == 'e' || c == 'E') && digitsFound)
  171. {
  172. bool negativeExponent = false;
  173. switch (*++text)
  174. {
  175. case '-': negativeExponent = true; // fall-through..
  176. case '+': ++text;
  177. }
  178. while (text.isDigit())
  179. exponent = (exponent * 10) + ((int) text.getAndAdvance() - '0');
  180. if (negativeExponent)
  181. exponent = -exponent;
  182. }
  183. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  184. if (decPointIndex != 0)
  185. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  186. return isNegative ? -r : r;
  187. }
  188. /** Parses a character string, to read a floating-point value. */
  189. template <typename CharPointerType>
  190. static double getDoubleValue (CharPointerType text) noexcept
  191. {
  192. return readDoubleValue (text);
  193. }
  194. //==============================================================================
  195. /** Parses a character string, to read an integer value. */
  196. template <typename IntType, typename CharPointerType>
  197. static IntType getIntValue (const CharPointerType text) noexcept
  198. {
  199. IntType v = 0;
  200. CharPointerType s (text.findEndOfWhitespace());
  201. const bool isNeg = *s == '-';
  202. if (isNeg)
  203. ++s;
  204. for (;;)
  205. {
  206. const water_uchar c = s.getAndAdvance();
  207. if (c >= '0' && c <= '9')
  208. v = v * 10 + (IntType) (c - '0');
  209. else
  210. break;
  211. }
  212. return isNeg ? -v : v;
  213. }
  214. template <typename ResultType>
  215. struct HexParser
  216. {
  217. template <typename CharPointerType>
  218. static ResultType parse (CharPointerType t) noexcept
  219. {
  220. ResultType result = 0;
  221. while (! t.isEmpty())
  222. {
  223. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  224. if (hexValue >= 0)
  225. result = (result << 4) | hexValue;
  226. }
  227. return result;
  228. }
  229. };
  230. //==============================================================================
  231. /** Counts the number of characters in a given string, stopping if the count exceeds
  232. a specified limit. */
  233. template <typename CharPointerType>
  234. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) noexcept
  235. {
  236. size_t len = 0;
  237. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  238. ++len;
  239. return len;
  240. }
  241. /** Counts the number of characters in a given string, stopping if the count exceeds
  242. a specified end-pointer. */
  243. template <typename CharPointerType>
  244. static size_t lengthUpTo (CharPointerType start, const CharPointerType end) noexcept
  245. {
  246. size_t len = 0;
  247. while (start < end && start.getAndAdvance() != 0)
  248. ++len;
  249. return len;
  250. }
  251. /** Copies null-terminated characters from one string to another. */
  252. template <typename DestCharPointerType, typename SrcCharPointerType>
  253. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) noexcept
  254. {
  255. while (water_uchar c = src.getAndAdvance())
  256. dest.write (c);
  257. dest.writeNull();
  258. }
  259. /** Copies characters from one string to another, up to a null terminator
  260. or a given byte size limit. */
  261. template <typename DestCharPointerType, typename SrcCharPointerType>
  262. static size_t copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, size_t maxBytesToWrite) noexcept
  263. {
  264. typename DestCharPointerType::CharType const* const startAddress = dest.getAddress();
  265. ssize_t maxBytes = (ssize_t) maxBytesToWrite;
  266. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  267. for (;;)
  268. {
  269. const water_uchar c = src.getAndAdvance();
  270. const size_t bytesNeeded = DestCharPointerType::getBytesRequiredFor (c);
  271. maxBytes -= bytesNeeded;
  272. if (c == 0 || maxBytes < 0)
  273. break;
  274. dest.write (c);
  275. }
  276. dest.writeNull();
  277. return (size_t) getAddressDifference (dest.getAddress(), startAddress)
  278. + sizeof (typename DestCharPointerType::CharType);
  279. }
  280. /** Copies characters from one string to another, up to a null terminator
  281. or a given maximum number of characters. */
  282. template <typename DestCharPointerType, typename SrcCharPointerType>
  283. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) noexcept
  284. {
  285. while (--maxChars > 0)
  286. {
  287. const water_uchar c = src.getAndAdvance();
  288. if (c == 0)
  289. break;
  290. dest.write (c);
  291. }
  292. dest.writeNull();
  293. }
  294. /** Compares two characters. */
  295. static inline int compare (water_uchar char1, water_uchar char2) noexcept
  296. {
  297. if (int diff = static_cast<int> (char1) - static_cast<int> (char2))
  298. return diff < 0 ? -1 : 1;
  299. return 0;
  300. }
  301. /** Compares two null-terminated character strings. */
  302. template <typename CharPointerType1, typename CharPointerType2>
  303. static int compare (CharPointerType1 s1, CharPointerType2 s2) noexcept
  304. {
  305. for (;;)
  306. {
  307. const water_uchar c1 = s1.getAndAdvance();
  308. if (int diff = compare (c1, s2.getAndAdvance()))
  309. return diff;
  310. if (c1 == 0)
  311. break;
  312. }
  313. return 0;
  314. }
  315. /** Compares two null-terminated character strings, up to a given number of characters. */
  316. template <typename CharPointerType1, typename CharPointerType2>
  317. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  318. {
  319. while (--maxChars >= 0)
  320. {
  321. const water_uchar c1 = s1.getAndAdvance();
  322. if (int diff = compare (c1, s2.getAndAdvance()))
  323. return diff;
  324. if (c1 == 0)
  325. break;
  326. }
  327. return 0;
  328. }
  329. /** Compares two characters, using a case-independant match. */
  330. static inline int compareIgnoreCase (water_uchar char1, water_uchar char2) noexcept
  331. {
  332. return char1 != char2 ? compare (toUpperCase (char1), toUpperCase (char2)) : 0;
  333. }
  334. /** Compares two null-terminated character strings, using a case-independant match. */
  335. template <typename CharPointerType1, typename CharPointerType2>
  336. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) noexcept
  337. {
  338. for (;;)
  339. {
  340. const water_uchar c1 = s1.getAndAdvance();
  341. if (int diff = compareIgnoreCase (c1, s2.getAndAdvance()))
  342. return diff;
  343. if (c1 == 0)
  344. break;
  345. }
  346. return 0;
  347. }
  348. /** Compares two null-terminated character strings, using a case-independent match. */
  349. template <typename CharPointerType1, typename CharPointerType2>
  350. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  351. {
  352. while (--maxChars >= 0)
  353. {
  354. const water_uchar c1 = s1.getAndAdvance();
  355. if (int diff = compareIgnoreCase (c1, s2.getAndAdvance()))
  356. return diff;
  357. if (c1 == 0)
  358. break;
  359. }
  360. return 0;
  361. }
  362. /** Finds the character index of a given substring in another string.
  363. Returns -1 if the substring is not found.
  364. */
  365. template <typename CharPointerType1, typename CharPointerType2>
  366. static int indexOf (CharPointerType1 textToSearch, const CharPointerType2 substringToLookFor) noexcept
  367. {
  368. int index = 0;
  369. const int substringLength = (int) substringToLookFor.length();
  370. for (;;)
  371. {
  372. if (textToSearch.compareUpTo (substringToLookFor, substringLength) == 0)
  373. return index;
  374. if (textToSearch.getAndAdvance() == 0)
  375. return -1;
  376. ++index;
  377. }
  378. }
  379. /** Returns a pointer to the first occurrence of a substring in a string.
  380. If the substring is not found, this will return a pointer to the string's
  381. null terminator.
  382. */
  383. template <typename CharPointerType1, typename CharPointerType2>
  384. static CharPointerType1 find (CharPointerType1 textToSearch, const CharPointerType2 substringToLookFor) noexcept
  385. {
  386. const int substringLength = (int) substringToLookFor.length();
  387. while (textToSearch.compareUpTo (substringToLookFor, substringLength) != 0
  388. && ! textToSearch.isEmpty())
  389. ++textToSearch;
  390. return textToSearch;
  391. }
  392. /** Returns a pointer to the first occurrence of a substring in a string.
  393. If the substring is not found, this will return a pointer to the string's
  394. null terminator.
  395. */
  396. template <typename CharPointerType>
  397. static CharPointerType find (CharPointerType textToSearch, const water_uchar charToLookFor) noexcept
  398. {
  399. for (;; ++textToSearch)
  400. {
  401. const water_uchar c = *textToSearch;
  402. if (c == charToLookFor || c == 0)
  403. break;
  404. }
  405. return textToSearch;
  406. }
  407. /** Finds the character index of a given substring in another string, using
  408. a case-independent match.
  409. Returns -1 if the substring is not found.
  410. */
  411. template <typename CharPointerType1, typename CharPointerType2>
  412. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2 needle) noexcept
  413. {
  414. int index = 0;
  415. const int needleLength = (int) needle.length();
  416. for (;;)
  417. {
  418. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  419. return index;
  420. if (haystack.getAndAdvance() == 0)
  421. return -1;
  422. ++index;
  423. }
  424. }
  425. /** Finds the character index of a given character in another string.
  426. Returns -1 if the character is not found.
  427. */
  428. template <typename Type>
  429. static int indexOfChar (Type text, const water_uchar charToFind) noexcept
  430. {
  431. int i = 0;
  432. while (! text.isEmpty())
  433. {
  434. if (text.getAndAdvance() == charToFind)
  435. return i;
  436. ++i;
  437. }
  438. return -1;
  439. }
  440. /** Finds the character index of a given character in another string, using
  441. a case-independent match.
  442. Returns -1 if the character is not found.
  443. */
  444. template <typename Type>
  445. static int indexOfCharIgnoreCase (Type text, water_uchar charToFind) noexcept
  446. {
  447. charToFind = CharacterFunctions::toLowerCase (charToFind);
  448. int i = 0;
  449. while (! text.isEmpty())
  450. {
  451. if (text.toLowerCase() == charToFind)
  452. return i;
  453. ++text;
  454. ++i;
  455. }
  456. return -1;
  457. }
  458. /** Returns a pointer to the first non-whitespace character in a string.
  459. If the string contains only whitespace, this will return a pointer
  460. to its null terminator.
  461. */
  462. template <typename Type>
  463. static Type findEndOfWhitespace (Type text) noexcept
  464. {
  465. while (text.isWhitespace())
  466. ++text;
  467. return text;
  468. }
  469. /** Returns a pointer to the first character in the string which is found in
  470. the breakCharacters string.
  471. */
  472. template <typename Type, typename BreakType>
  473. static Type findEndOfToken (Type text, const BreakType breakCharacters, const Type quoteCharacters)
  474. {
  475. water_uchar currentQuoteChar = 0;
  476. while (! text.isEmpty())
  477. {
  478. const water_uchar c = text.getAndAdvance();
  479. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  480. {
  481. --text;
  482. break;
  483. }
  484. if (quoteCharacters.indexOf (c) >= 0)
  485. {
  486. if (currentQuoteChar == 0)
  487. currentQuoteChar = c;
  488. else if (currentQuoteChar == c)
  489. currentQuoteChar = 0;
  490. }
  491. }
  492. return text;
  493. }
  494. private:
  495. static double mulexp10 (const double value, int exponent) noexcept;
  496. };
  497. }
  498. #endif // WATER_CHARACTERFUNCTIONS_H_INCLUDED