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.

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