wide.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. #pragma once
  2. #include "recode_result.h"
  3. #include "unidata.h"
  4. #include "utf8.h"
  5. #include "wide_specific.h"
  6. #include <util/generic/algorithm.h>
  7. #include <util/generic/string.h>
  8. #include <util/generic/yexception.h>
  9. #include <util/memory/tempbuf.h>
  10. #include <util/system/compiler.h>
  11. #include <util/system/cpu_id.h>
  12. #include <util/system/yassert.h>
  13. #include <cstring>
  14. #ifdef _sse2_
  15. #include <emmintrin.h>
  16. #endif
  17. template <class T>
  18. class TTempArray;
  19. using TCharTemp = TTempArray<wchar16>;
  20. namespace NDetail {
  21. inline TString InStringMsg(const char* s, size_t len) {
  22. return (len <= 50) ? " in string " + TString(s, len).Quote() : TString();
  23. }
  24. template <bool isPointer>
  25. struct TSelector;
  26. template <>
  27. struct TSelector<false> {
  28. template <class T>
  29. static inline void WriteSymbol(wchar16 s, T& dest) noexcept {
  30. dest.push_back(s);
  31. }
  32. };
  33. template <>
  34. struct TSelector<true> {
  35. template <class T>
  36. static inline void WriteSymbol(wchar16 s, T& dest) noexcept {
  37. *(dest++) = s;
  38. }
  39. };
  40. inline wchar32 ReadSurrogatePair(const wchar16* chars) noexcept {
  41. const wchar32 SURROGATE_OFFSET = static_cast<wchar32>(0x10000 - (0xD800 << 10) - 0xDC00);
  42. wchar32 lead = chars[0];
  43. wchar32 tail = chars[1];
  44. Y_ASSERT(IsW16SurrogateLead(lead));
  45. Y_ASSERT(IsW16SurrogateTail(tail));
  46. return (static_cast<wchar32>(lead) << 10) + tail + SURROGATE_OFFSET;
  47. }
  48. template <class T>
  49. inline void WriteSurrogatePair(wchar32 s, T& dest) noexcept;
  50. }
  51. inline wchar16* SkipSymbol(wchar16* begin, const wchar16* end) noexcept {
  52. return begin + W16SymbolSize(begin, end);
  53. }
  54. inline const wchar16* SkipSymbol(const wchar16* begin, const wchar16* end) noexcept {
  55. return begin + W16SymbolSize(begin, end);
  56. }
  57. inline wchar32* SkipSymbol(wchar32* begin, const wchar32* end) noexcept {
  58. Y_ASSERT(begin < end);
  59. return begin + 1;
  60. }
  61. inline const wchar32* SkipSymbol(const wchar32* begin, const wchar32* end) noexcept {
  62. Y_ASSERT(begin < end);
  63. return begin + 1;
  64. }
  65. inline wchar32 ReadSymbol(const wchar16* begin, const wchar16* end) noexcept {
  66. Y_ASSERT(begin < end);
  67. if (IsW16SurrogateLead(*begin)) {
  68. if (begin + 1 < end && IsW16SurrogateTail(*(begin + 1)))
  69. return ::NDetail::ReadSurrogatePair(begin);
  70. return BROKEN_RUNE;
  71. } else if (IsW16SurrogateTail(*begin)) {
  72. return BROKEN_RUNE;
  73. }
  74. return *begin;
  75. }
  76. inline wchar32 ReadSymbol(const wchar32* begin, const wchar32* end) noexcept {
  77. Y_ASSERT(begin < end);
  78. return *begin;
  79. }
  80. //! presuming input data is either big enought of null terminated
  81. inline wchar32 ReadSymbolAndAdvance(const char16_t*& begin) noexcept {
  82. Y_ASSERT(*begin);
  83. if (IsW16SurrogateLead(begin[0])) {
  84. if (IsW16SurrogateTail(begin[1])) {
  85. Y_ASSERT(begin[1] != 0);
  86. const wchar32 c = ::NDetail::ReadSurrogatePair(begin);
  87. begin += 2;
  88. return c;
  89. }
  90. ++begin;
  91. return BROKEN_RUNE;
  92. } else if (IsW16SurrogateTail(begin[0])) {
  93. ++begin;
  94. return BROKEN_RUNE;
  95. }
  96. return *(begin++);
  97. }
  98. //! presuming input data is either big enought of null terminated
  99. inline wchar32 ReadSymbolAndAdvance(const char32_t*& begin) noexcept {
  100. Y_ASSERT(*begin);
  101. return *(begin++);
  102. }
  103. inline wchar32 ReadSymbolAndAdvance(const wchar_t*& begin) noexcept {
  104. // According to
  105. // https://en.cppreference.com/w/cpp/language/types
  106. // wchar_t holds UTF-16 on Windows and UTF-32 on Linux / macOS
  107. //
  108. // Apply reinterpret cast and dispatch to a proper type
  109. #ifdef _win_
  110. using TDistinctChar = char16_t;
  111. #else
  112. using TDistinctChar = char32_t;
  113. #endif
  114. const TDistinctChar*& distinctBegin = reinterpret_cast<const TDistinctChar*&>(begin);
  115. wchar32 result = ReadSymbolAndAdvance(distinctBegin);
  116. begin = reinterpret_cast<const wchar_t*&>(distinctBegin);
  117. return result;
  118. }
  119. inline wchar32 ReadSymbolAndAdvance(const char16_t*& begin, const char16_t* end) noexcept {
  120. Y_ASSERT(begin < end);
  121. if (IsW16SurrogateLead(begin[0])) {
  122. if (begin + 1 != end && IsW16SurrogateTail(begin[1])) {
  123. const wchar32 c = ::NDetail::ReadSurrogatePair(begin);
  124. begin += 2;
  125. return c;
  126. }
  127. ++begin;
  128. return BROKEN_RUNE;
  129. } else if (IsW16SurrogateTail(begin[0])) {
  130. ++begin;
  131. return BROKEN_RUNE;
  132. }
  133. return *(begin++);
  134. }
  135. inline wchar32 ReadSymbolAndAdvance(const wchar32*& begin, const wchar32* end) noexcept {
  136. Y_ASSERT(begin < end);
  137. return *(begin++);
  138. }
  139. inline wchar32 ReadSymbolAndAdvance(const wchar_t*& begin, const wchar_t* end) noexcept {
  140. // According to
  141. // https://en.cppreference.com/w/cpp/language/types
  142. // wchar_t holds UTF-16 on Windows and UTF-32 on Linux / macOS
  143. //
  144. // Apply reinterpret cast and dispatch to a proper type
  145. #ifdef _win_
  146. using TDistinctChar = char16_t;
  147. #else
  148. using TDistinctChar = char32_t;
  149. #endif
  150. const TDistinctChar* distinctBegin = reinterpret_cast<const TDistinctChar*>(begin);
  151. const TDistinctChar* distinctEnd = reinterpret_cast<const TDistinctChar*>(end);
  152. wchar32 result = ::ReadSymbolAndAdvance(distinctBegin, distinctEnd);
  153. begin = reinterpret_cast<const wchar_t*>(distinctBegin);
  154. return result;
  155. }
  156. template <class T>
  157. inline size_t WriteSymbol(wchar16 s, T& dest) noexcept {
  158. ::NDetail::TSelector<std::is_pointer<T>::value>::WriteSymbol(s, dest);
  159. return 1;
  160. }
  161. template <class T>
  162. inline size_t WriteSymbol(wchar32 s, T& dest) noexcept {
  163. if (s > 0xFFFF) {
  164. if (s >= ::NUnicode::UnicodeInstancesLimit()) {
  165. return WriteSymbol(static_cast<wchar16>(BROKEN_RUNE), dest);
  166. }
  167. ::NDetail::WriteSurrogatePair(s, dest);
  168. return 2;
  169. }
  170. return WriteSymbol(static_cast<wchar16>(s), dest);
  171. }
  172. inline bool WriteSymbol(wchar32 s, wchar16*& dest, const wchar16* destEnd) noexcept {
  173. Y_ASSERT(dest < destEnd);
  174. if (s > 0xFFFF) {
  175. if (s >= NUnicode::UnicodeInstancesLimit()) {
  176. *(dest++) = static_cast<wchar16>(BROKEN_RUNE);
  177. return true;
  178. }
  179. if (dest + 2 > destEnd)
  180. return false;
  181. ::NDetail::WriteSurrogatePair(s, dest);
  182. } else {
  183. *(dest++) = static_cast<wchar16>(s);
  184. }
  185. return true;
  186. }
  187. inline size_t WriteSymbol(wchar32 s, wchar32*& dest) noexcept {
  188. *(dest++) = s;
  189. return 1;
  190. }
  191. inline bool WriteSymbol(wchar32 s, wchar32*& dest, const wchar32* destEnd) noexcept {
  192. Y_ASSERT(dest < destEnd);
  193. *(dest++) = s;
  194. return true;
  195. }
  196. template <class T>
  197. inline void ::NDetail::WriteSurrogatePair(wchar32 s, T& dest) noexcept {
  198. const wchar32 LEAD_OFFSET = 0xD800 - (0x10000 >> 10);
  199. Y_ASSERT(s > 0xFFFF && s < ::NUnicode::UnicodeInstancesLimit());
  200. wchar16 lead = LEAD_OFFSET + (static_cast<wchar16>(s >> 10));
  201. wchar16 tail = 0xDC00 + static_cast<wchar16>(s & 0x3FF);
  202. Y_ASSERT(IsW16SurrogateLead(lead));
  203. Y_ASSERT(IsW16SurrogateTail(tail));
  204. WriteSymbol(lead, dest);
  205. WriteSymbol(tail, dest);
  206. }
  207. class TCharIterator {
  208. private:
  209. const wchar16* Begin;
  210. const wchar16* End;
  211. public:
  212. inline explicit TCharIterator(const wchar16* end)
  213. : Begin(end)
  214. , End(end)
  215. {
  216. }
  217. inline TCharIterator(const wchar16* begin, const wchar16* end)
  218. : Begin(begin)
  219. , End(end)
  220. {
  221. }
  222. inline TCharIterator& operator++() {
  223. Begin = SkipSymbol(Begin, End);
  224. return *this;
  225. }
  226. inline bool operator==(const wchar16* other) const {
  227. return Begin == other;
  228. }
  229. inline bool operator!=(const wchar16* other) const {
  230. return !(*this == other);
  231. }
  232. inline bool operator==(const TCharIterator& other) const {
  233. return *this == other.Begin;
  234. }
  235. inline bool operator!=(const TCharIterator& other) const {
  236. return *this != other.Begin;
  237. }
  238. inline wchar32 operator*() const {
  239. return ReadSymbol(Begin, End);
  240. }
  241. inline const wchar16* Get() const {
  242. return Begin;
  243. }
  244. };
  245. namespace NDetail {
  246. template <bool robust, typename TCharType>
  247. inline void UTF8ToWideImplScalar(const unsigned char*& cur, const unsigned char* last, TCharType*& dest) noexcept {
  248. wchar32 rune = BROKEN_RUNE;
  249. while (cur != last) {
  250. if (ReadUTF8CharAndAdvance(rune, cur, last) != RECODE_OK) {
  251. if (robust) {
  252. rune = BROKEN_RUNE;
  253. ++cur;
  254. } else {
  255. break;
  256. }
  257. }
  258. Y_ASSERT(cur <= last);
  259. WriteSymbol(rune, dest);
  260. }
  261. }
  262. template <typename TCharType>
  263. inline void UTF16ToUTF32ImplScalar(const wchar16* cur, const wchar16* last, TCharType*& dest) noexcept {
  264. wchar32 rune = BROKEN_RUNE;
  265. while (cur != last) {
  266. rune = ReadSymbolAndAdvance(cur, last);
  267. Y_ASSERT(cur <= last);
  268. WriteSymbol(rune, dest);
  269. }
  270. }
  271. template <class TCharType>
  272. inline void UTF8ToWideImplSSE41(const unsigned char*& /*cur*/, const unsigned char* /*last*/, TCharType*& /*dest*/) noexcept {
  273. }
  274. void UTF8ToWideImplSSE41(const unsigned char*& cur, const unsigned char* last, wchar16*& dest) noexcept;
  275. void UTF8ToWideImplSSE41(const unsigned char*& cur, const unsigned char* last, wchar32*& dest) noexcept;
  276. }
  277. //! @return len if robust and position where encoding stopped if not
  278. template <bool robust, typename TCharType>
  279. inline size_t UTF8ToWideImpl(const char* text, size_t len, TCharType* dest, size_t& written) noexcept {
  280. const unsigned char* cur = reinterpret_cast<const unsigned char*>(text);
  281. const unsigned char* last = cur + len;
  282. TCharType* p = dest;
  283. #ifdef _sse_ //can't check for sse4, as we build most of arcadia without sse4 support even on platforms that support it
  284. if (cur + 16 <= last && NX86::CachedHaveSSE41()) {
  285. ::NDetail::UTF8ToWideImplSSE41(cur, last, p);
  286. }
  287. #endif
  288. ::NDetail::UTF8ToWideImplScalar<robust>(cur, last, p);
  289. written = p - dest;
  290. return cur - reinterpret_cast<const unsigned char*>(text);
  291. }
  292. template <typename TCharType>
  293. inline size_t UTF8ToWideImpl(const char* text, size_t len, TCharType* dest, size_t& written) {
  294. return UTF8ToWideImpl<false>(text, len, dest, written);
  295. }
  296. template <bool robust>
  297. inline TUtf16String UTF8ToWide(const char* text, size_t len) {
  298. TUtf16String w = TUtf16String::Uninitialized(len);
  299. size_t written;
  300. size_t pos = UTF8ToWideImpl<robust>(text, len, w.begin(), written);
  301. if (pos != len)
  302. ythrow yexception() << "failed to decode UTF-8 string at pos " << pos << ::NDetail::InStringMsg(text, len);
  303. Y_ASSERT(w.size() >= written);
  304. w.remove(written);
  305. return w;
  306. }
  307. template <bool robust, typename TCharType>
  308. inline bool UTF8ToWide(const char* text, size_t len, TCharType* dest, size_t& written) noexcept {
  309. return UTF8ToWideImpl<robust>(text, len, dest, written) == len;
  310. }
  311. //! converts text from UTF8 to unicode, stops immediately it UTF8 byte sequence is wrong
  312. //! @attention destination buffer must be long enough to fit all characters of the text,
  313. //! conversion stops if a broken symbol is met
  314. //! @return @c true if all the text converted successfully, @c false - a broken symbol was found
  315. template <typename TCharType>
  316. inline bool UTF8ToWide(const char* text, size_t len, TCharType* dest, size_t& written) noexcept {
  317. return UTF8ToWide<false>(text, len, dest, written);
  318. }
  319. template <bool robust>
  320. inline TWtringBuf UTF8ToWide(const TStringBuf src, TUtf16String& dst) {
  321. dst.ReserveAndResize(src.size());
  322. size_t written = 0;
  323. UTF8ToWideImpl<robust>(src.data(), src.size(), dst.begin(), written);
  324. dst.resize(written);
  325. return dst;
  326. }
  327. //! if not robust will stop at first error position
  328. template <bool robust>
  329. inline TUtf32StringBuf UTF8ToUTF32(const TStringBuf src, TUtf32String& dst) {
  330. dst.ReserveAndResize(src.size());
  331. size_t written = 0;
  332. UTF8ToWideImpl<robust>(src.data(), src.size(), dst.begin(), written);
  333. dst.resize(written);
  334. return dst;
  335. }
  336. inline TWtringBuf UTF8ToWide(const TStringBuf src, TUtf16String& dst) {
  337. return UTF8ToWide<false>(src, dst);
  338. }
  339. inline TUtf16String UTF8ToWide(const char* text, size_t len) {
  340. return UTF8ToWide<false>(text, len);
  341. }
  342. template <bool robust>
  343. inline TUtf16String UTF8ToWide(const TStringBuf s) {
  344. return UTF8ToWide<robust>(s.data(), s.size());
  345. }
  346. template <bool robust>
  347. inline TUtf32String UTF8ToUTF32(const TStringBuf s) {
  348. TUtf32String r;
  349. UTF8ToUTF32<robust>(s, r);
  350. return r;
  351. }
  352. inline TUtf16String UTF8ToWide(const TStringBuf s) {
  353. return UTF8ToWide<false>(s.data(), s.size());
  354. }
  355. //! converts text from unicode to UTF8
  356. //! @attention destination buffer must be long enough to fit all characters of the text,
  357. //! @c WriteUTF8Char converts @c wchar32 into maximum 4 bytes of UTF8 so
  358. //! destination buffer must have length equal to <tt> len * 4 </tt>
  359. template <typename TCharType>
  360. inline void WideToUTF8(const TCharType* text, size_t len, char* dest, size_t& written) {
  361. const TCharType* const last = text + len;
  362. unsigned char* p = reinterpret_cast<unsigned char*>(dest);
  363. size_t runeLen;
  364. for (const TCharType* cur = text; cur != last;) {
  365. WriteUTF8Char(ReadSymbolAndAdvance(cur, last), runeLen, p);
  366. Y_ASSERT(runeLen <= 4);
  367. p += runeLen;
  368. }
  369. written = p - reinterpret_cast<unsigned char*>(dest);
  370. }
  371. constexpr size_t WideToUTF8BufferSize(const size_t inputStringSize) noexcept {
  372. return inputStringSize * 4; // * 4 because the conversion functions can convert unicode character into maximum 4 bytes of UTF8
  373. }
  374. inline TStringBuf WideToUTF8(const TWtringBuf src, TString& dst) {
  375. dst.ReserveAndResize(WideToUTF8BufferSize(src.size()));
  376. size_t written = 0;
  377. WideToUTF8(src.data(), src.size(), dst.begin(), written);
  378. Y_ASSERT(dst.size() >= written);
  379. dst.remove(written);
  380. return dst;
  381. }
  382. inline TString WideToUTF8(const wchar16* text, size_t len) {
  383. TString s = TString::Uninitialized(WideToUTF8BufferSize(len));
  384. size_t written = 0;
  385. WideToUTF8(text, len, s.begin(), written);
  386. Y_ASSERT(s.size() >= written);
  387. s.remove(written);
  388. return s;
  389. }
  390. inline TString WideToUTF8(const wchar32* text, size_t len) {
  391. TString s = TString::Uninitialized(WideToUTF8BufferSize(len));
  392. size_t written = 0;
  393. WideToUTF8(text, len, s.begin(), written);
  394. Y_ASSERT(s.size() >= written);
  395. s.remove(written);
  396. return s;
  397. }
  398. inline TString WideToUTF8(const TWtringBuf w) {
  399. return WideToUTF8(w.data(), w.size());
  400. }
  401. inline TString WideToUTF8(const TUtf32StringBuf w) {
  402. return WideToUTF8(w.data(), w.size());
  403. }
  404. inline TUtf16String UTF32ToWide(const wchar32* begin, size_t len) {
  405. TUtf16String res;
  406. res.reserve(len);
  407. const wchar32* end = begin + len;
  408. for (const wchar32* i = begin; i != end; ++i) {
  409. WriteSymbol(*i, res);
  410. }
  411. return res;
  412. }
  413. // adopted from https://chromium.googlesource.com/chromium/src/+/master/base/strings/string_util.cc
  414. // Assuming that a pointer is the size of a "machine word", then
  415. // uintptr_t is an integer type that is also a machine word.
  416. namespace NDetail {
  417. using TMachineWord = uintptr_t;
  418. const uintptr_t kMachineWordAlignmentMask = sizeof(TMachineWord) - 1;
  419. inline bool IsAlignedToMachineWord(const void* pointer) {
  420. return !(reinterpret_cast<TMachineWord>(pointer) & kMachineWordAlignmentMask);
  421. }
  422. template <typename T>
  423. inline T* AlignToMachineWord(T* pointer) {
  424. return reinterpret_cast<T*>(reinterpret_cast<TMachineWord>(pointer) & ~kMachineWordAlignmentMask);
  425. }
  426. template <size_t size, typename CharacterType>
  427. struct NonASCIIMask;
  428. template <>
  429. struct
  430. NonASCIIMask<4, wchar16> {
  431. static constexpr ui32 Value() {
  432. return 0xFF80FF80U;
  433. }
  434. };
  435. template <>
  436. struct
  437. NonASCIIMask<4, char> {
  438. static constexpr ui32 Value() {
  439. return 0x80808080U;
  440. }
  441. };
  442. template <>
  443. struct
  444. NonASCIIMask<8, wchar16> {
  445. static constexpr ui64 Value() {
  446. return 0xFF80FF80FF80FF80ULL;
  447. }
  448. };
  449. template <>
  450. struct
  451. NonASCIIMask<8, char> {
  452. static constexpr ui64 Value() {
  453. return 0x8080808080808080ULL;
  454. }
  455. };
  456. template <typename TChar>
  457. inline bool DoIsStringASCIISlow(const TChar* first, const TChar* last) {
  458. using TUnsignedChar = std::make_unsigned_t<TChar>;
  459. Y_ASSERT(first <= last);
  460. for (; first != last; ++first) {
  461. if (static_cast<TUnsignedChar>(*first) > 0x7F) {
  462. return false;
  463. }
  464. }
  465. return true;
  466. }
  467. template <typename TChar>
  468. inline bool DoIsStringASCII(const TChar* first, const TChar* last) {
  469. if (last - first < 10) {
  470. return DoIsStringASCIISlow(first, last);
  471. }
  472. TMachineWord allCharBits = 0;
  473. TMachineWord nonAsciiBitMask = NonASCIIMask<sizeof(TMachineWord), TChar>::Value();
  474. // Prologue: align the input.
  475. while (!IsAlignedToMachineWord(first) && first != last) {
  476. allCharBits |= *first;
  477. ++first;
  478. }
  479. // Compare the values of CPU word size.
  480. const TChar* word_end = AlignToMachineWord(last);
  481. const size_t loopIncrement = sizeof(TMachineWord) / sizeof(TChar);
  482. while (first < word_end) {
  483. allCharBits |= *(reinterpret_cast<const TMachineWord*>(first));
  484. first += loopIncrement;
  485. // fast exit
  486. if (allCharBits & nonAsciiBitMask) {
  487. return false;
  488. }
  489. }
  490. // Process the remaining bytes.
  491. while (first != last) {
  492. allCharBits |= *first;
  493. ++first;
  494. }
  495. return !(allCharBits & nonAsciiBitMask);
  496. }
  497. #ifdef _sse2_
  498. inline bool DoIsStringASCIISSE(const unsigned char* first, const unsigned char* last) {
  499. //scalar version for short strings
  500. if (first + 8 > last) {
  501. return ::NDetail::DoIsStringASCIISlow(first, last);
  502. }
  503. alignas(16) unsigned char buf[16];
  504. while (first + 16 <= last) {
  505. memcpy(buf, first, 16);
  506. __m128i chunk = _mm_load_si128(reinterpret_cast<__m128i*>(buf));
  507. int asciiMask = _mm_movemask_epi8(chunk);
  508. if (asciiMask) {
  509. return false;
  510. }
  511. first += 16;
  512. }
  513. if (first + 8 <= last) {
  514. memcpy(buf, first, 8);
  515. __m128i chunk = _mm_loadl_epi64(reinterpret_cast<__m128i*>(buf));
  516. int asciiMask = _mm_movemask_epi8(chunk);
  517. if (asciiMask) {
  518. return false;
  519. }
  520. first += 8;
  521. }
  522. return ::NDetail::DoIsStringASCIISlow(first, last);
  523. }
  524. #endif //_sse2_
  525. }
  526. //! returns @c true if character sequence has no symbols with value greater than 0x7F
  527. template <typename TChar>
  528. inline bool IsStringASCII(const TChar* first, const TChar* last) {
  529. return ::NDetail::DoIsStringASCII(first, last);
  530. }
  531. #ifdef _sse2_
  532. template <>
  533. inline bool IsStringASCII<unsigned char>(const unsigned char* first, const unsigned char* last) {
  534. return ::NDetail::DoIsStringASCIISSE(first, last);
  535. }
  536. template <>
  537. inline bool IsStringASCII<char>(const char* first, const char* last) {
  538. return ::NDetail::DoIsStringASCIISSE(reinterpret_cast<const unsigned char*>(first), reinterpret_cast<const unsigned char*>(last));
  539. }
  540. #endif
  541. //! copies elements from one character sequence to another using memcpy
  542. //! for compatibility only
  543. template <typename TChar>
  544. inline void Copy(const TChar* first, size_t len, TChar* result) {
  545. memcpy(result, first, len * sizeof(TChar));
  546. }
  547. template <typename TChar1, typename TChar2>
  548. inline void Copy(const TChar1* first, size_t len, TChar2* result) {
  549. Copy(first, first + len, result);
  550. }
  551. //! copies symbols from one character sequence to another without any conversion
  552. //! @note this function can be used instead of the template constructor of @c std::basic_string:
  553. //! template <typename InputIterator>
  554. //! basic_string(InputIterator begin, InputIterator end, const Allocator& a = Allocator());
  555. //! and the family of template member functions: append, assign, insert, replace.
  556. template <typename TStringType, typename TChar>
  557. inline TStringType CopyTo(const TChar* first, const TChar* last) {
  558. Y_ASSERT(first <= last);
  559. TStringType str = TStringType::Uninitialized(last - first);
  560. Copy(first, last, str.begin());
  561. return str;
  562. }
  563. template <typename TStringType, typename TChar>
  564. inline TStringType CopyTo(const TChar* s, size_t n) {
  565. TStringType str = TStringType::Uninitialized(n);
  566. Copy(s, n, str.begin());
  567. return str;
  568. }
  569. inline TString WideToASCII(const TWtringBuf w) {
  570. Y_ASSERT(IsStringASCII(w.begin(), w.end()));
  571. return CopyTo<TString>(w.begin(), w.end());
  572. }
  573. inline TUtf16String ASCIIToWide(const TStringBuf s) {
  574. Y_ASSERT(IsStringASCII(s.begin(), s.end()));
  575. return CopyTo<TUtf16String>(s.begin(), s.end());
  576. }
  577. inline TUtf32String ASCIIToUTF32(const TStringBuf s) {
  578. Y_ASSERT(IsStringASCII(s.begin(), s.end()));
  579. return CopyTo<TUtf32String>(s.begin(), s.end());
  580. }
  581. //! returns @c true if string contains whitespace characters only
  582. inline bool IsSpace(const wchar16* s, size_t n) {
  583. if (n == 0)
  584. return false;
  585. Y_ASSERT(s);
  586. const wchar16* const e = s + n;
  587. for (const wchar16* p = s; p != e; ++p) {
  588. if (!IsWhitespace(*p))
  589. return false;
  590. }
  591. return true;
  592. }
  593. //! returns @c true if string contains whitespace characters only
  594. inline bool IsSpace(const TWtringBuf s) {
  595. return IsSpace(s.data(), s.length());
  596. }
  597. //! replaces multiple sequential whitespace characters with a single space character
  598. void Collapse(TUtf16String& w);
  599. //! @return new length
  600. size_t Collapse(wchar16* s, size_t n);
  601. //! Removes leading whitespace characters
  602. TWtringBuf StripLeft(const TWtringBuf text) noexcept Y_WARN_UNUSED_RESULT;
  603. void StripLeft(TUtf16String& text);
  604. //! Removes trailing whitespace characters
  605. TWtringBuf StripRight(const TWtringBuf text) noexcept Y_WARN_UNUSED_RESULT;
  606. void StripRight(TUtf16String& text);
  607. //! Removes leading and trailing whitespace characters
  608. TWtringBuf Strip(const TWtringBuf text) noexcept Y_WARN_UNUSED_RESULT;
  609. void Strip(TUtf16String& text);
  610. /* Check if given word is lowercase/uppercase. Will return false if string contains any
  611. * non-alphabetical symbols. It is expected that `text` is a correct UTF-16 string.
  612. *
  613. * For example `IsLowerWord("hello")` will return `true`, when `IsLowerWord("hello there")` will
  614. * return false because of the space in the middle of the string. Empty string is also considered
  615. * lowercase.
  616. */
  617. bool IsLowerWord(const TWtringBuf text) noexcept;
  618. bool IsUpperWord(const TWtringBuf text) noexcept;
  619. /* Will check if given word starts with capital letter and the rest of the word is lowercase. Will
  620. * return `false` for empty string. See also `IsLowerWord`.
  621. */
  622. bool IsTitleWord(const TWtringBuf text) noexcept;
  623. /* Check if given string is lowercase/uppercase. Will return `true` if all alphabetic symbols are
  624. * in proper case, all other symbols are ignored. It is expected that `text` is a correct UTF-16
  625. * string.
  626. *
  627. * For example `IsLowerWord("hello")` will return `true` and `IsLowerWord("hello there")` will
  628. * also return true because. Empty string is also considered lowercase.
  629. *
  630. * NOTE: for any case where `IsLowerWord` returns `true` `IsLower` will also return `true`.
  631. */
  632. bool IsLower(const TWtringBuf text) noexcept;
  633. bool IsUpper(const TWtringBuf text) noexcept;
  634. /* Lowercase/uppercase given string inplace. Any alphabetic symbol will be converted to a proper
  635. * case, the rest of the symbols will be kept the same. It is expected that `text` is a correct
  636. * UTF-16 string.
  637. *
  638. * For example `ToLower("heLLo")` will return `"hello"`.
  639. *
  640. * @param text String to modify
  641. * @param pos Position of the first character to modify
  642. * @param count Length of the substring
  643. * @returns `true` if `text` was changed
  644. *
  645. * NOTE: `pos` and `count` are measured in `wchar16`, not in codepoints.
  646. */
  647. bool ToLower(TUtf16String& text, size_t pos = 0, size_t count = TUtf16String::npos);
  648. bool ToUpper(TUtf16String& text, size_t pos = 0, size_t count = TUtf16String::npos);
  649. /* Lowercase/uppercase given string inplace. Any alphabetic symbol will be converted to a proper
  650. * case, the rest of the symbols will be kept the same. It is expected that `text` is a correct
  651. * UTF-32 string.
  652. *
  653. * For example `ToLower("heLLo")` will return `"hello"`.
  654. *
  655. * @param text String to modify
  656. * @param pos Position of the first character to modify
  657. * @param count Length of the substring
  658. * @returns `true` if `text` was changed
  659. *
  660. * NOTE: `pos` and `count` are measured in `wchar16`, not in codepoints.
  661. */
  662. bool ToLower(TUtf32String& /*text*/, size_t /*pos*/ = 0, size_t /*count*/ = TUtf16String::npos);
  663. bool ToUpper(TUtf32String& /*text*/, size_t /*pos*/ = 0, size_t /*count*/ = TUtf16String::npos);
  664. /* Titlecase first symbol and lowercase the rest, see `ToLower` for more details.
  665. */
  666. bool ToTitle(TUtf16String& text, size_t pos = 0, size_t count = TUtf16String::npos);
  667. /* Titlecase first symbol and lowercase the rest, see `ToLower` for more details.
  668. */
  669. bool ToTitle(TUtf32String& /*text*/, size_t /*pos*/ = 0, size_t /*count*/ = TUtf16String::npos);
  670. /* @param text Pointer to the string to modify
  671. * @param length Length of the string to modify
  672. * @param out Pointer to the character array to write to
  673. *
  674. * NOTE: [text, text+length) and [out, out+length) should not interleave.
  675. *
  676. * TODO(yazevnul): replace these functions with `bool(const TWtringBuf, const TArrayRef<wchar16>)`
  677. * overload.
  678. */
  679. bool ToLower(const wchar16* text, size_t length, wchar16* out) noexcept;
  680. bool ToUpper(const wchar16* text, size_t length, wchar16* out) noexcept;
  681. bool ToTitle(const wchar16* text, size_t length, wchar16* out) noexcept;
  682. bool ToLower(const wchar32* text, size_t length, wchar32* out) noexcept;
  683. bool ToUpper(const wchar32* text, size_t length, wchar32* out) noexcept;
  684. bool ToTitle(const wchar32* text, size_t length, wchar32* out) noexcept;
  685. /* @param text Pointer to the string to modify
  686. * @param length Length of the string to modify
  687. *
  688. * TODO(yazevnul): replace these functions with `bool(const TArrayRef<wchar16>)` overload.
  689. */
  690. bool ToLower(wchar16* text, size_t length) noexcept;
  691. bool ToUpper(wchar16* text, size_t length) noexcept;
  692. bool ToTitle(wchar16* text, size_t length) noexcept;
  693. bool ToLower(wchar32* text, size_t length) noexcept;
  694. bool ToUpper(wchar32* text, size_t length) noexcept;
  695. bool ToTitle(wchar32* text, size_t length) noexcept;
  696. /* Convenience wrappers for `ToLower`, `ToUpper` and `ToTitle`.
  697. */
  698. TUtf16String ToLowerRet(TUtf16String text, size_t pos = 0, size_t count = TUtf16String::npos) Y_WARN_UNUSED_RESULT;
  699. TUtf16String ToUpperRet(TUtf16String text, size_t pos = 0, size_t count = TUtf16String::npos) Y_WARN_UNUSED_RESULT;
  700. TUtf16String ToTitleRet(TUtf16String text, size_t pos = 0, size_t count = TUtf16String::npos) Y_WARN_UNUSED_RESULT;
  701. TUtf16String ToLowerRet(const TWtringBuf text, size_t pos = 0, size_t count = TWtringBuf::npos) Y_WARN_UNUSED_RESULT;
  702. TUtf16String ToUpperRet(const TWtringBuf text, size_t pos = 0, size_t count = TWtringBuf::npos) Y_WARN_UNUSED_RESULT;
  703. TUtf16String ToTitleRet(const TWtringBuf text, size_t pos = 0, size_t count = TWtringBuf::npos) Y_WARN_UNUSED_RESULT;
  704. TUtf32String ToLowerRet(const TUtf32StringBuf text, size_t pos = 0, size_t count = TWtringBuf::npos) Y_WARN_UNUSED_RESULT;
  705. TUtf32String ToUpperRet(const TUtf32StringBuf text, size_t pos = 0, size_t count = TWtringBuf::npos) Y_WARN_UNUSED_RESULT;
  706. TUtf32String ToTitleRet(const TUtf32StringBuf text, size_t pos = 0, size_t count = TWtringBuf::npos) Y_WARN_UNUSED_RESULT;
  707. //! replaces the '<', '>' and '&' characters in string with '&lt;', '&gt;' and '&amp;' respectively
  708. // insertBr=true - replace '\r' and '\n' with "<BR>"
  709. template <bool insertBr>
  710. void EscapeHtmlChars(TUtf16String& str);
  711. //! returns number of characters in range. Handle surrogate pairs as one character.
  712. inline size_t CountWideChars(const wchar16* b, const wchar16* e) {
  713. size_t count = 0;
  714. Y_ENSURE(b <= e, TStringBuf("invalid iterators"));
  715. while (b < e) {
  716. b = SkipSymbol(b, e);
  717. ++count;
  718. }
  719. return count;
  720. }
  721. inline size_t CountWideChars(const TWtringBuf str) {
  722. return CountWideChars(str.begin(), str.end());
  723. }
  724. //! checks whether the range is valid UTF-16 sequence
  725. inline bool IsValidUTF16(const wchar16* b, const wchar16* e) {
  726. Y_ENSURE(b <= e, TStringBuf("invalid iterators"));
  727. while (b < e) {
  728. wchar32 symbol = ReadSymbolAndAdvance(b, e);
  729. if (symbol == BROKEN_RUNE)
  730. return false;
  731. }
  732. return true;
  733. }
  734. inline bool IsValidUTF16(const TWtringBuf str) {
  735. return IsValidUTF16(str.begin(), str.end());
  736. }