wide.h 27 KB

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