unicodetext.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /**
  2. * Copyright 2010 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef UTIL_UTF8_PUBLIC_UNICODETEXT_H_
  17. #define UTIL_UTF8_PUBLIC_UNICODETEXT_H_
  18. #include <stddef.h> // for NULL, ptrdiff_t
  19. #include <iterator> // for bidirectional_iterator_tag, etc
  20. #include <string> // for string
  21. #include <utility> // for pair
  22. #include "syntaxnet/base.h"
  23. // ***************************** UnicodeText **************************
  24. //
  25. // A UnicodeText object is a container for a sequence of Unicode
  26. // codepoint values. It has default, copy, and assignment constructors.
  27. // Data can be appended to it from another UnicodeText, from
  28. // iterators, or from a single codepoint.
  29. //
  30. // The internal representation of the text is UTF-8. Since UTF-8 is a
  31. // variable-width format, UnicodeText does not provide random access
  32. // to the text, and changes to the text are permitted only at the end.
  33. //
  34. // The UnicodeText class defines a const_iterator. The dereferencing
  35. // operator (*) returns a codepoint (char32). The iterator is a
  36. // bidirectional, read-only iterator. It becomes invalid if the text
  37. // is changed.
  38. //
  39. // There are methods for appending and retrieving UTF-8 data directly.
  40. // The 'utf8_data' method returns a const char* that contains the
  41. // UTF-8-encoded version of the text; 'utf8_length' returns the number
  42. // of bytes in the UTF-8 data. An iterator's 'get' method stores up to
  43. // 4 bytes of UTF-8 data in a char array and returns the number of
  44. // bytes that it stored.
  45. //
  46. // Codepoints are integers in the range [0, 0xD7FF] or [0xE000,
  47. // 0x10FFFF], but UnicodeText has the additional restriction that it
  48. // can contain only those characters that are valid for interchange on
  49. // the Web. This excludes all of the control codes except for carriage
  50. // return, line feed, and horizontal tab. It also excludes
  51. // non-characters, but codepoints that are in the Private Use regions
  52. // are allowed, as are codepoints that are unassigned. (See the
  53. // Unicode reference for details.) The function UniLib::IsInterchangeValid
  54. // can be used as a test for this property.
  55. //
  56. // UnicodeTexts are safe. Every method that constructs or modifies a
  57. // UnicodeText tests for interchange-validity, and will substitute a
  58. // space for the invalid data. Such cases are reported via
  59. // LOG(WARNING).
  60. //
  61. // MEMORY MANAGEMENT: copy, take ownership, or point to
  62. //
  63. // A UnicodeText is either an "owner", meaning that it owns the memory
  64. // for the data buffer and will free it when the UnicodeText is
  65. // destroyed, or it is an "alias", meaning that it does not.
  66. //
  67. // There are three methods for storing UTF-8 data in a UnicodeText:
  68. //
  69. // CopyUTF8(buffer, len) copies buffer.
  70. //
  71. // TakeOwnershipOfUTF8(buffer, size, capacity) takes ownership of buffer.
  72. //
  73. // PointToUTF8(buffer, size) creates an alias pointing to buffer.
  74. //
  75. // All three methods perform a validity check on the buffer. There are
  76. // private, "unsafe" versions of these functions that bypass the
  77. // validity check. They are used internally and by friend-functions
  78. // that are handling UTF-8 data that has already been validated.
  79. //
  80. // The purpose of an alias is to avoid making an unnecessary copy of a
  81. // UTF-8 buffer while still providing access to the Unicode values
  82. // within that text through iterators or the fast scanners that are
  83. // based on UTF-8 state tables. The lifetime of an alias must not
  84. // exceed the lifetime of the buffer from which it was constructed.
  85. //
  86. // The semantics of an alias might be described as "copy on write or
  87. // repair." The source data is never modified. If push_back() or
  88. // append() is called on an alias, a copy of the data will be created,
  89. // and the UnicodeText will become an owner. If clear() is called on
  90. // an alias, it becomes an (empty) owner.
  91. //
  92. // The copy constructor and the assignment operator produce an owner.
  93. // That is, after direct initialization ("UnicodeText x(y);") or copy
  94. // initialization ("UnicodeText x = y;") x will be an owner, even if y
  95. // was an alias. The assignment operator ("x = y;") also produces an
  96. // owner unless x and y are the same object and y is an alias.
  97. //
  98. // Aliases should be used with care. If the source from which an alias
  99. // was created is freed, or if the contents are changed, while the
  100. // alias is still in use, fatal errors could result. But it can be
  101. // quite useful to have a UnicodeText "window" through which to see a
  102. // UTF-8 buffer without having to pay the price of making a copy.
  103. //
  104. // UTILITIES
  105. //
  106. // The interfaces in util/utf8/public/textutils.h provide higher-level
  107. // utilities for dealing with UnicodeTexts, including routines for
  108. // creating UnicodeTexts (both owners and aliases) from UTF-8 buffers or
  109. // strings, creating strings from UnicodeTexts, normalizing text for
  110. // efficient matching or display, and others.
  111. class UnicodeText {
  112. public:
  113. class const_iterator;
  114. typedef char32 value_type;
  115. // Constructors. These always produce owners.
  116. UnicodeText(); // Create an empty text.
  117. UnicodeText(const UnicodeText& src); // copy constructor
  118. // Construct a substring (copies the data).
  119. UnicodeText(const const_iterator& first, const const_iterator& last);
  120. // Assignment operator. This copies the data and produces an owner
  121. // unless this == &src, e.g., "x = x;", which is a no-op.
  122. UnicodeText& operator=(const UnicodeText& src);
  123. // x.Copy(y) copies the data from y into x.
  124. UnicodeText& Copy(const UnicodeText& src);
  125. inline UnicodeText& assign(const UnicodeText& src) { return Copy(src); }
  126. // x.PointTo(y) changes x so that it points to y's data.
  127. // It does not copy y or take ownership of y's data.
  128. UnicodeText& PointTo(const UnicodeText& src);
  129. UnicodeText& PointTo(const const_iterator& first,
  130. const const_iterator& last);
  131. ~UnicodeText();
  132. void clear(); // Clear text.
  133. bool empty() const { return repr_.size_ == 0; } // Test if text is empty.
  134. // Add a codepoint to the end of the text.
  135. // If the codepoint is not interchange-valid, add a space instead
  136. // and log a warning.
  137. void push_back(char32 codepoint);
  138. // Generic appending operation.
  139. // iterator_traits<ForwardIterator>::value_type must be implicitly
  140. // convertible to char32. Typical uses of this method might include:
  141. // char32 chars[] = {0x1, 0x2, ...};
  142. // vector<char32> more_chars = ...;
  143. // utext.append(chars, chars+arraysize(chars));
  144. // utext.append(more_chars.begin(), more_chars.end());
  145. template<typename ForwardIterator>
  146. UnicodeText& append(ForwardIterator first, const ForwardIterator last) {
  147. while (first != last) { push_back(*first++); }
  148. return *this;
  149. }
  150. // A specialization of the generic append() method.
  151. UnicodeText& append(const const_iterator& first, const const_iterator& last);
  152. // An optimization of append(source.begin(), source.end()).
  153. UnicodeText& append(const UnicodeText& source);
  154. int size() const; // the number of Unicode characters (codepoints)
  155. friend bool operator==(const UnicodeText& lhs, const UnicodeText& rhs);
  156. friend bool operator!=(const UnicodeText& lhs, const UnicodeText& rhs);
  157. class const_iterator {
  158. typedef const_iterator CI;
  159. public:
  160. typedef std::bidirectional_iterator_tag iterator_category;
  161. typedef char32 value_type;
  162. typedef ptrdiff_t difference_type;
  163. typedef void pointer; // (Not needed.)
  164. typedef const char32 reference; // (Needed for const_reverse_iterator)
  165. // Iterators are default-constructible.
  166. const_iterator();
  167. // It's safe to make multiple passes over a UnicodeText.
  168. const_iterator(const const_iterator& other);
  169. const_iterator& operator=(const const_iterator& other);
  170. char32 operator*() const; // Dereference
  171. const_iterator& operator++(); // Advance (++iter)
  172. const_iterator operator++(int) { // (iter++)
  173. const_iterator result(*this);
  174. ++*this;
  175. return result;
  176. }
  177. const_iterator& operator--(); // Retreat (--iter)
  178. const_iterator operator--(int) { // (iter--)
  179. const_iterator result(*this);
  180. --*this;
  181. return result;
  182. }
  183. // We love relational operators.
  184. friend bool operator==(const CI& lhs, const CI& rhs) {
  185. return lhs.it_ == rhs.it_; }
  186. friend bool operator!=(const CI& lhs, const CI& rhs) {
  187. return !(lhs == rhs); }
  188. friend bool operator<(const CI& lhs, const CI& rhs);
  189. friend bool operator>(const CI& lhs, const CI& rhs) {
  190. return rhs < lhs; }
  191. friend bool operator<=(const CI& lhs, const CI& rhs) {
  192. return !(rhs < lhs); }
  193. friend bool operator>=(const CI& lhs, const CI& rhs) {
  194. return !(lhs < rhs); }
  195. friend difference_type distance(const CI& first, const CI& last);
  196. // UTF-8-specific methods
  197. // Store the UTF-8 encoding of the current codepoint into buf,
  198. // which must be at least 4 bytes long. Return the number of
  199. // bytes written.
  200. int get_utf8(char* buf) const;
  201. // Return the UTF-8 character that the iterator points to.
  202. string get_utf8_string() const;
  203. // Return the byte length of the UTF-8 character the iterator points to.
  204. int utf8_length() const;
  205. // Return the iterator's pointer into the UTF-8 data.
  206. const char* utf8_data() const { return it_; }
  207. string DebugString() const;
  208. private:
  209. friend class UnicodeText;
  210. friend class UnicodeTextUtils;
  211. friend class UTF8StateTableProperty;
  212. explicit const_iterator(const char* it) : it_(it) {}
  213. const char* it_;
  214. };
  215. const_iterator begin() const;
  216. const_iterator end() const;
  217. class const_reverse_iterator : public std::reverse_iterator<const_iterator> {
  218. public:
  219. explicit const_reverse_iterator(const_iterator it) :
  220. std::reverse_iterator<const_iterator>(it) {}
  221. const char* utf8_data() const {
  222. const_iterator tmp_it = base();
  223. return (--tmp_it).utf8_data();
  224. }
  225. int get_utf8(char* buf) const {
  226. const_iterator tmp_it = base();
  227. return (--tmp_it).get_utf8(buf);
  228. }
  229. string get_utf8_string() const {
  230. const_iterator tmp_it = base();
  231. return (--tmp_it).get_utf8_string();
  232. }
  233. int utf8_length() const {
  234. const_iterator tmp_it = base();
  235. return (--tmp_it).utf8_length();
  236. }
  237. };
  238. const_reverse_iterator rbegin() const {
  239. return const_reverse_iterator(end());
  240. }
  241. const_reverse_iterator rend() const {
  242. return const_reverse_iterator(begin());
  243. }
  244. // Substring searching. Returns the beginning of the first
  245. // occurrence of "look", or end() if not found.
  246. const_iterator find(const UnicodeText& look, const_iterator start_pos) const;
  247. // Equivalent to find(look, begin())
  248. const_iterator find(const UnicodeText& look) const;
  249. // Returns whether this contains the character U+FFFD. This can
  250. // occur, for example, if the input to Encodings::Decode() had byte
  251. // sequences that were invalid in the source encoding.
  252. bool HasReplacementChar() const;
  253. // UTF-8-specific methods
  254. //
  255. // Return the data, length, and capacity of UTF-8-encoded version of
  256. // the text. Length and capacity are measured in bytes.
  257. const char* utf8_data() const { return repr_.data_; }
  258. int utf8_length() const { return repr_.size_; }
  259. int utf8_capacity() const { return repr_.capacity_; }
  260. // Return the UTF-8 data as a string.
  261. static string UTF8Substring(const const_iterator& first,
  262. const const_iterator& last);
  263. // There are three methods for initializing a UnicodeText from UTF-8
  264. // data. They vary in details of memory management. In all cases,
  265. // the data is tested for interchange-validity. If it is not
  266. // interchange-valid, a LOG(WARNING) is issued, and each
  267. // structurally invalid byte and each interchange-invalid codepoint
  268. // is replaced with a space.
  269. // x.CopyUTF8(buf, len) copies buf into x.
  270. UnicodeText& CopyUTF8(const char* utf8_buffer, int byte_length);
  271. // x.TakeOwnershipOfUTF8(buf, len, capacity). x takes ownership of
  272. // buf. buf is not copied.
  273. UnicodeText& TakeOwnershipOfUTF8(char* utf8_buffer,
  274. int byte_length,
  275. int byte_capacity);
  276. // x.PointToUTF8(buf,len) changes x so that it points to buf
  277. // ("becomes an alias"). It does not take ownership or copy buf.
  278. // If the buffer is not valid, this has the same effect as
  279. // CopyUTF8(utf8_buffer, byte_length).
  280. UnicodeText& PointToUTF8(const char* utf8_buffer, int byte_length);
  281. // Occasionally it is necessary to use functions that operate on the
  282. // pointer returned by utf8_data(). MakeIterator(p) provides a way
  283. // to get back to the UnicodeText level. It uses CHECK to ensure
  284. // that p is a pointer within this object's UTF-8 data, and that it
  285. // points to the beginning of a character.
  286. const_iterator MakeIterator(const char* p) const;
  287. string DebugString() const;
  288. private:
  289. friend class const_iterator;
  290. friend class UnicodeTextUtils;
  291. class Repr { // A byte-string.
  292. public:
  293. char* data_;
  294. int size_;
  295. int capacity_;
  296. bool ours_; // Do we own data_?
  297. Repr() : data_(nullptr), size_(0), capacity_(0), ours_(true) {}
  298. ~Repr() { if (ours_) delete[] data_; }
  299. void clear();
  300. void reserve(int capacity);
  301. void resize(int size);
  302. void append(const char* bytes, int byte_length);
  303. void Copy(const char* data, int size);
  304. void TakeOwnershipOf(char* data, int size, int capacity);
  305. void PointTo(const char* data, int size);
  306. string DebugString() const;
  307. private:
  308. Repr& operator=(const Repr&);
  309. Repr(const Repr& other);
  310. };
  311. Repr repr_;
  312. // UTF-8-specific private methods.
  313. // These routines do not perform a validity check when compiled
  314. // in opt mode.
  315. // It is an error to call these methods with UTF-8 data that
  316. // is not interchange-valid.
  317. //
  318. UnicodeText& UnsafeCopyUTF8(const char* utf8_buffer, int byte_length);
  319. UnicodeText& UnsafeTakeOwnershipOfUTF8(
  320. char* utf8_buffer, int byte_length, int byte_capacity);
  321. UnicodeText& UnsafePointToUTF8(const char* utf8_buffer, int byte_length);
  322. UnicodeText& UnsafeAppendUTF8(const char* utf8_buffer, int byte_length);
  323. const_iterator UnsafeFind(const UnicodeText& look,
  324. const_iterator start_pos) const;
  325. };
  326. bool operator==(const UnicodeText& lhs, const UnicodeText& rhs);
  327. inline bool operator!=(const UnicodeText& lhs, const UnicodeText& rhs) {
  328. return !(lhs == rhs);
  329. }
  330. // UnicodeTextRange is a pair of iterators, useful for specifying text
  331. // segments. If the iterators are ==, the segment is empty.
  332. typedef pair<UnicodeText::const_iterator,
  333. UnicodeText::const_iterator> UnicodeTextRange;
  334. inline bool UnicodeTextRangeIsEmpty(const UnicodeTextRange& r) {
  335. return r.first == r.second;
  336. }
  337. // *************************** Utilities *************************
  338. // A factory function for creating a UnicodeText from a buffer of
  339. // UTF-8 data. The new UnicodeText takes ownership of the buffer. (It
  340. // is an "owner.")
  341. //
  342. // Each byte that is structurally invalid will be replaced with a
  343. // space. Each codepoint that is interchange-invalid will also be
  344. // replaced with a space, even if the codepoint was represented with a
  345. // multibyte sequence in the UTF-8 data.
  346. //
  347. inline UnicodeText MakeUnicodeTextAcceptingOwnership(
  348. char* utf8_buffer, int byte_length, int byte_capacity) {
  349. return UnicodeText().TakeOwnershipOfUTF8(
  350. utf8_buffer, byte_length, byte_capacity);
  351. }
  352. // A factory function for creating a UnicodeText from a buffer of
  353. // UTF-8 data. The new UnicodeText does not take ownership of the
  354. // buffer. (It is an "alias.")
  355. //
  356. inline UnicodeText MakeUnicodeTextWithoutAcceptingOwnership(
  357. const char* utf8_buffer, int byte_length) {
  358. return UnicodeText().PointToUTF8(utf8_buffer, byte_length);
  359. }
  360. // Create a UnicodeText from a UTF-8 string or buffer.
  361. //
  362. // If do_copy is true, then a copy of the string is made. The copy is
  363. // owned by the resulting UnicodeText object and will be freed when
  364. // the object is destroyed. This UnicodeText object is referred to
  365. // as an "owner."
  366. //
  367. // If do_copy is false, then no copy is made. The resulting
  368. // UnicodeText object does NOT take ownership of the string; in this
  369. // case, the lifetime of the UnicodeText object must not exceed the
  370. // lifetime of the string. This Unicodetext object is referred to as
  371. // an "alias." This is the same as MakeUnicodeTextWithoutAcceptingOwnership.
  372. //
  373. // If the input string does not contain valid UTF-8, then a copy is
  374. // made (as if do_copy were true) and coerced to valid UTF-8 by
  375. // replacing each invalid byte with a space.
  376. //
  377. inline UnicodeText UTF8ToUnicodeText(const char* utf8_buf, int len,
  378. bool do_copy) {
  379. UnicodeText t;
  380. if (do_copy) {
  381. t.CopyUTF8(utf8_buf, len);
  382. } else {
  383. t.PointToUTF8(utf8_buf, len);
  384. }
  385. return t;
  386. }
  387. inline UnicodeText UTF8ToUnicodeText(const string& utf_string, bool do_copy) {
  388. return UTF8ToUnicodeText(utf_string.data(), utf_string.size(), do_copy);
  389. }
  390. inline UnicodeText UTF8ToUnicodeText(const char* utf8_buf, int len) {
  391. return UTF8ToUnicodeText(utf8_buf, len, true);
  392. }
  393. inline UnicodeText UTF8ToUnicodeText(const string& utf8_string) {
  394. return UTF8ToUnicodeText(utf8_string, true);
  395. }
  396. // Return a string containing the UTF-8 encoded version of all the
  397. // Unicode characters in t.
  398. inline string UnicodeTextToUTF8(const UnicodeText& t) {
  399. return string(t.utf8_data(), t.utf8_length());
  400. }
  401. // This template function declaration is used in defining arraysize.
  402. // Note that the function doesn't need an implementation, as we only
  403. // use its type.
  404. template <typename T, size_t N>
  405. char (&ArraySizeHelper(T (&array)[N]))[N];
  406. #define arraysize(array) (sizeof(ArraySizeHelper(array)))
  407. // For debugging. Return a string of integers, written in uppercase
  408. // hex (%X), corresponding to the codepoints within the text. Each
  409. // integer is followed by a space. E.g., "61 62 6A 3005 ".
  410. string CodepointString(const UnicodeText& t);
  411. #endif // UTIL_UTF8_PUBLIC_UNICODETEXT_H_