ascii.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/strings/ascii.h"
  15. #include <climits>
  16. #include <cstdint>
  17. #include <cstring>
  18. #include <string>
  19. #include <type_traits>
  20. #include "absl/base/config.h"
  21. #include "absl/base/nullability.h"
  22. namespace absl {
  23. ABSL_NAMESPACE_BEGIN
  24. namespace ascii_internal {
  25. // # Table generated by this Python code (bit 0x02 is currently unused):
  26. // TODO(mbar) Move Python code for generation of table to BUILD and link here.
  27. // NOTE: The kAsciiPropertyBits table used within this code was generated by
  28. // Python code of the following form. (Bit 0x02 is currently unused and
  29. // available.)
  30. //
  31. // def Hex2(n):
  32. // return '0x' + hex(n/16)[2:] + hex(n%16)[2:]
  33. // def IsPunct(ch):
  34. // return (ord(ch) >= 32 and ord(ch) < 127 and
  35. // not ch.isspace() and not ch.isalnum())
  36. // def IsBlank(ch):
  37. // return ch in ' \t'
  38. // def IsCntrl(ch):
  39. // return ord(ch) < 32 or ord(ch) == 127
  40. // def IsXDigit(ch):
  41. // return ch.isdigit() or ch.lower() in 'abcdef'
  42. // for i in range(128):
  43. // ch = chr(i)
  44. // mask = ((ch.isalpha() and 0x01 or 0) |
  45. // (ch.isalnum() and 0x04 or 0) |
  46. // (ch.isspace() and 0x08 or 0) |
  47. // (IsPunct(ch) and 0x10 or 0) |
  48. // (IsBlank(ch) and 0x20 or 0) |
  49. // (IsCntrl(ch) and 0x40 or 0) |
  50. // (IsXDigit(ch) and 0x80 or 0))
  51. // print Hex2(mask) + ',',
  52. // if i % 16 == 7:
  53. // print ' //', Hex2(i & 0x78)
  54. // elif i % 16 == 15:
  55. // print
  56. // clang-format off
  57. // Array of bitfields holding character information. Each bit value corresponds
  58. // to a particular character feature. For readability, and because the value
  59. // of these bits is tightly coupled to this implementation, the individual bits
  60. // are not named. Note that bitfields for all characters above ASCII 127 are
  61. // zero-initialized.
  62. ABSL_DLL const unsigned char kPropertyBits[256] = {
  63. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // 0x00
  64. 0x40, 0x68, 0x48, 0x48, 0x48, 0x48, 0x40, 0x40,
  65. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // 0x10
  66. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
  67. 0x28, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, // 0x20
  68. 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
  69. 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, // 0x30
  70. 0x84, 0x84, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
  71. 0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05, // 0x40
  72. 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
  73. 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, // 0x50
  74. 0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x10,
  75. 0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05, // 0x60
  76. 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
  77. 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, // 0x70
  78. 0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x40,
  79. };
  80. // Array of characters for the ascii_tolower() function. For values 'A'
  81. // through 'Z', return the lower-case character; otherwise, return the
  82. // identity of the passed character.
  83. ABSL_DLL const char kToLower[256] = {
  84. '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  85. '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
  86. '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
  87. '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
  88. '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
  89. '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
  90. '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
  91. '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
  92. '\x40', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  93. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  94. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
  95. 'x', 'y', 'z', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
  96. '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
  97. '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
  98. '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
  99. '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f',
  100. '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87',
  101. '\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f',
  102. '\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97',
  103. '\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f',
  104. '\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7',
  105. '\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf',
  106. '\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5', '\xb6', '\xb7',
  107. '\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf',
  108. '\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7',
  109. '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf',
  110. '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7',
  111. '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf',
  112. '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7',
  113. '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef',
  114. '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7',
  115. '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff',
  116. };
  117. // Array of characters for the ascii_toupper() function. For values 'a'
  118. // through 'z', return the upper-case character; otherwise, return the
  119. // identity of the passed character.
  120. ABSL_DLL const char kToUpper[256] = {
  121. '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  122. '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
  123. '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
  124. '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
  125. '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
  126. '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
  127. '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
  128. '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
  129. '\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47',
  130. '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f',
  131. '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57',
  132. '\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
  133. '\x60', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
  134. 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  135. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  136. 'X', 'Y', 'Z', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f',
  137. '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87',
  138. '\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f',
  139. '\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97',
  140. '\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f',
  141. '\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7',
  142. '\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf',
  143. '\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5', '\xb6', '\xb7',
  144. '\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf',
  145. '\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7',
  146. '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf',
  147. '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7',
  148. '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf',
  149. '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7',
  150. '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef',
  151. '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7',
  152. '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff',
  153. };
  154. // clang-format on
  155. template <class T>
  156. static constexpr T BroadcastByte(unsigned char value) {
  157. static_assert(std::is_integral<T>::value && sizeof(T) <= sizeof(uint64_t) &&
  158. std::is_unsigned<T>::value,
  159. "only unsigned integers up to 64-bit allowed");
  160. T result = value;
  161. constexpr size_t result_bit_width = sizeof(result) * CHAR_BIT;
  162. result |= result << ((CHAR_BIT << 0) & (result_bit_width - 1));
  163. result |= result << ((CHAR_BIT << 1) & (result_bit_width - 1));
  164. result |= result << ((CHAR_BIT << 2) & (result_bit_width - 1));
  165. return result;
  166. }
  167. // Returns whether `c` is in the a-z/A-Z range (w.r.t. `ToUpper`).
  168. // Implemented by:
  169. // 1. Pushing the a-z/A-Z range to [SCHAR_MIN, SCHAR_MIN + 26).
  170. // 2. Comparing to SCHAR_MIN + 26.
  171. template <bool ToUpper>
  172. constexpr bool AsciiInAZRange(unsigned char c) {
  173. constexpr unsigned char sub = (ToUpper ? 'a' : 'A') - SCHAR_MIN;
  174. constexpr signed char threshold = SCHAR_MIN + 26; // 26 = alphabet size.
  175. // Using unsigned arithmetic as overflows/underflows are well defined.
  176. unsigned char u = c - sub;
  177. // Using signed cmp, as SIMD unsigned cmp isn't available in many platforms.
  178. return static_cast<signed char>(u) < threshold;
  179. }
  180. template <bool ToUpper>
  181. static constexpr char* PartialAsciiStrCaseFold(absl::Nonnull<char*> p,
  182. absl::Nonnull<char*> end) {
  183. using vec_t = size_t;
  184. const size_t n = static_cast<size_t>(end - p);
  185. // SWAR algorithm: http://0x80.pl/notesen/2016-01-06-swar-swap-case.html
  186. constexpr char ch_a = ToUpper ? 'a' : 'A', ch_z = ToUpper ? 'z' : 'Z';
  187. char* const swar_end = p + (n / sizeof(vec_t)) * sizeof(vec_t);
  188. while (p < swar_end) {
  189. vec_t v = vec_t();
  190. // memcpy the vector, but constexpr
  191. for (size_t i = 0; i < sizeof(vec_t); ++i) {
  192. v |= static_cast<vec_t>(static_cast<unsigned char>(p[i]))
  193. << (i * CHAR_BIT);
  194. }
  195. constexpr unsigned int msb = 1u << (CHAR_BIT - 1);
  196. const vec_t v_msb = v & BroadcastByte<vec_t>(msb);
  197. const vec_t v_nonascii_mask = (v_msb << 1) - (v_msb >> (CHAR_BIT - 1));
  198. const vec_t v_nonascii = v & v_nonascii_mask;
  199. const vec_t v_ascii = v & ~v_nonascii_mask;
  200. const vec_t a = v_ascii + BroadcastByte<vec_t>(msb - ch_a - 0),
  201. z = v_ascii + BroadcastByte<vec_t>(msb - ch_z - 1);
  202. v = v_nonascii | (v_ascii ^ ((a ^ z) & BroadcastByte<vec_t>(msb)) >> 2);
  203. // memcpy the vector, but constexpr
  204. for (size_t i = 0; i < sizeof(vec_t); ++i) {
  205. p[i] = static_cast<char>(v >> (i * CHAR_BIT));
  206. }
  207. p += sizeof(v);
  208. }
  209. return p;
  210. }
  211. template <bool ToUpper>
  212. static constexpr void AsciiStrCaseFold(absl::Nonnull<char*> p,
  213. absl::Nonnull<char*> end) {
  214. // The upper- and lowercase versions of ASCII characters differ by only 1 bit.
  215. // When we need to flip the case, we can xor with this bit to achieve the
  216. // desired result. Note that the choice of 'a' and 'A' here is arbitrary. We
  217. // could have chosen 'z' and 'Z', or any other pair of characters as they all
  218. // have the same single bit difference.
  219. constexpr unsigned char kAsciiCaseBitFlip = 'a' ^ 'A';
  220. using vec_t = size_t;
  221. // TODO(b/316380338): When FDO becomes able to vectorize these,
  222. // revert this manual optimization and just leave the naive loop.
  223. if (static_cast<size_t>(end - p) >= sizeof(vec_t)) {
  224. p = ascii_internal::PartialAsciiStrCaseFold<ToUpper>(p, end);
  225. }
  226. while (p < end) {
  227. unsigned char v = static_cast<unsigned char>(*p);
  228. v ^= AsciiInAZRange<ToUpper>(v) ? kAsciiCaseBitFlip : 0;
  229. *p = static_cast<char>(v);
  230. ++p;
  231. }
  232. }
  233. static constexpr size_t ValidateAsciiCasefold() {
  234. constexpr size_t num_chars = 1 + CHAR_MAX - CHAR_MIN;
  235. size_t incorrect_index = 0;
  236. char lowered[num_chars] = {};
  237. char uppered[num_chars] = {};
  238. for (unsigned int i = 0; i < num_chars; ++i) {
  239. uppered[i] = lowered[i] = static_cast<char>(i);
  240. }
  241. AsciiStrCaseFold<false>(&lowered[0], &lowered[num_chars]);
  242. AsciiStrCaseFold<true>(&uppered[0], &uppered[num_chars]);
  243. for (size_t i = 0; i < num_chars; ++i) {
  244. const char ch = static_cast<char>(i),
  245. ch_upper = ('a' <= ch && ch <= 'z' ? 'A' + (ch - 'a') : ch),
  246. ch_lower = ('A' <= ch && ch <= 'Z' ? 'a' + (ch - 'A') : ch);
  247. if (uppered[i] != ch_upper || lowered[i] != ch_lower) {
  248. incorrect_index = i > 0 ? i : num_chars;
  249. break;
  250. }
  251. }
  252. return incorrect_index;
  253. }
  254. static_assert(ValidateAsciiCasefold() == 0, "error in case conversion");
  255. } // namespace ascii_internal
  256. void AsciiStrToLower(absl::Nonnull<std::string*> s) {
  257. char* p = &(*s)[0]; // Guaranteed to be valid for empty strings
  258. return ascii_internal::AsciiStrCaseFold<false>(p, p + s->size());
  259. }
  260. void AsciiStrToUpper(absl::Nonnull<std::string*> s) {
  261. char* p = &(*s)[0]; // Guaranteed to be valid for empty strings
  262. return ascii_internal::AsciiStrCaseFold<true>(p, p + s->size());
  263. }
  264. void RemoveExtraAsciiWhitespace(absl::Nonnull<std::string*> str) {
  265. auto stripped = StripAsciiWhitespace(*str);
  266. if (stripped.empty()) {
  267. str->clear();
  268. return;
  269. }
  270. auto input_it = stripped.begin();
  271. auto input_end = stripped.end();
  272. auto output_it = &(*str)[0];
  273. bool is_ws = false;
  274. for (; input_it < input_end; ++input_it) {
  275. if (is_ws) {
  276. // Consecutive whitespace? Keep only the last.
  277. is_ws = absl::ascii_isspace(static_cast<unsigned char>(*input_it));
  278. if (is_ws) --output_it;
  279. } else {
  280. is_ws = absl::ascii_isspace(static_cast<unsigned char>(*input_it));
  281. }
  282. *output_it = *input_it;
  283. ++output_it;
  284. }
  285. str->erase(static_cast<size_t>(output_it - &(*str)[0]));
  286. }
  287. ABSL_NAMESPACE_END
  288. } // namespace absl