• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

utf8/H03-Dec-2021-890662

README.mdH A D03-Dec-202144.3 KiB1,091772

utf8.hH A D03-Dec-20211.5 KiB355

README.md

1# UTF8-CPP: UTF-8 with C++ in a Portable Way
2
3
4## Introduction
5
6Many C++ developers miss an easy and portable way of handling Unicode encoded strings. The original C++ Standard (known as C++98 or C++03) is Unicode agnostic. C++11 provides some support for Unicode on core language and library level: u8, u, and U character and string literals, char16_t and char32_t character types, u16string and u32string library classes, and codecvt support for conversions between Unicode encoding forms. In the meantime, developers use third party libraries like ICU, OS specific capabilities, or simply roll out their own solutions.
7
8In order to easily handle UTF-8 encoded Unicode strings, I came up with a small, C++98 compatible generic library. For anybody used to work with STL algorithms and iterators, it should be easy and natural to use. The code is freely available for any purpose - check out the license at the beginning of the utf8.h file. The library has been used a lot in the past ten years both in commercial and open-source projects and is considered feature-complete now. If you run into bugs or performance issues, please let me know and I'll do my best to address them.
9
10The purpose of this article is not to offer an introduction to Unicode in general, and UTF-8 in particular. If you are not familiar with Unicode, be sure to check out [Unicode Home Page](http://www.unicode.org/) or some other source of information for Unicode. Also, it is not my aim to advocate the use of UTF-8 encoded strings in C++ programs; if you want to handle UTF-8 encoded strings from C++, I am sure you have good reasons for it.
11
12## Examples of use
13
14### Introductionary Sample
15
16To illustrate the use of the library, let's start with a small but complete program that opens a file containing UTF-8 encoded text, reads it line by line, checks each line for invalid UTF-8 byte sequences, and converts it to UTF-16 encoding and back to UTF-8:
17
18```cpp
19#include <fstream>
20#include <iostream>
21#include <string>
22#include <vector>
23#include "utf8.h"
24using namespace std;
25int main(int argc, char** argv)
26{
27    if (argc != 2) {
28        cout << "\nUsage: docsample filename\n";
29        return 0;
30    }
31
32    const char* test_file_path = argv[1];
33    // Open the test file (contains UTF-8 encoded text)
34    ifstream fs8(test_file_path);
35    if (!fs8.is_open()) {
36    cout << "Could not open " << test_file_path << endl;
37    return 0;
38    }
39
40    unsigned line_count = 1;
41    string line;
42    // Play with all the lines in the file
43    while (getline(fs8, line)) {
44       // check for invalid utf-8 (for a simple yes/no check, there is also utf8::is_valid function)
45        string::iterator end_it = utf8::find_invalid(line.begin(), line.end());
46        if (end_it != line.end()) {
47            cout << "Invalid UTF-8 encoding detected at line " << line_count << "\n";
48            cout << "This part is fine: " << string(line.begin(), end_it) << "\n";
49        }
50
51        // Get the line length (at least for the valid part)
52        int length = utf8::distance(line.begin(), end_it);
53        cout << "Length of line " << line_count << " is " << length <<  "\n";
54
55        // Convert it to utf-16
56        vector<unsigned short> utf16line;
57        utf8::utf8to16(line.begin(), end_it, back_inserter(utf16line));
58
59        // And back to utf-8
60        string utf8line;
61        utf8::utf16to8(utf16line.begin(), utf16line.end(), back_inserter(utf8line));
62
63        // Confirm that the conversion went OK:
64        if (utf8line != string(line.begin(), end_it))
65            cout << "Error in UTF-16 conversion at line: " << line_count << "\n";
66
67        line_count++;
68    }
69    return 0;
70}
71```
72
73In the previous code sample, for each line we performed a detection of invalid UTF-8 sequences with `find_invalid`; the number of characters (more precisely - the number of Unicode code points, including the end of line and even BOM if there is one) in each line was determined with a use of `utf8::distance`; finally, we have converted each line to UTF-16 encoding with `utf8to16` and back to UTF-8 with `utf16to8`.
74
75### Checking if a file contains valid UTF-8 text
76
77Here is a function that checks whether the content of a file is valid UTF-8 encoded text without reading the content into the memory:
78
79```cpp
80bool valid_utf8_file(const char* file_name)
81{
82    ifstream ifs(file_name);
83    if (!ifs)
84        return false; // even better, throw here
85
86    istreambuf_iterator<char> it(ifs.rdbuf());
87    istreambuf_iterator<char> eos;
88
89    return utf8::is_valid(it, eos);
90}
91```
92
93Because the function `utf8::is_valid()` works with input iterators, we were able to pass an `istreambuf_iterator` to it and read the content of the file directly without loading it to the memory first.
94
95Note that other functions that take input iterator arguments can be used in a similar way. For instance, to read the content of a UTF-8 encoded text file and convert the text to UTF-16, just do something like:
96
97```cpp
98    utf8::utf8to16(it, eos, back_inserter(u16string));
99```
100
101### Ensure that a string contains valid UTF-8 text
102
103If we have some text that "probably" contains UTF-8 encoded text and we want to replace any invalid UTF-8 sequence with a replacement character, something like the following function may be used:
104
105```cpp
106void fix_utf8_string(std::string& str)
107{
108    std::string temp;
109    utf8::replace_invalid(str.begin(), str.end(), back_inserter(temp));
110    str = temp;
111}
112```
113
114The function will replace any invalid UTF-8 sequence with a Unicode replacement character. There is an overloaded function that enables the caller to supply their own replacement character.
115
116## Reference
117
118### Functions From utf8 Namespace
119
120#### utf8::append
121
122Available in version 1.0 and later.
123
124Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string.
125
126```cpp
127template <typename octet_iterator>
128octet_iterator append(uint32_t cp, octet_iterator result);
129```
130
131`octet_iterator`: an output iterator.
132`cp`: a 32 bit integer representing a code point to append to the sequence.
133`result`: an output iterator to the place in the sequence where to append the code point.
134Return value: an iterator pointing to the place after the newly appended sequence.
135
136Example of use:
137
138```cpp
139unsigned char u[5] = {0,0,0,0,0};
140unsigned char* end = append(0x0448, u);
141assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0);
142```
143
144Note that `append` does not allocate any memory - it is the burden of the caller to make sure there is enough memory allocated for the operation. To make things more interesting, `append` can add anywhere between 1 and 4 octets to the sequence. In practice, you would most often want to use `std::back_inserter` to ensure that the necessary memory is allocated.
145
146In case of an invalid code point, a `utf8::invalid_code_point` exception is thrown.
147
148#### utf8::next
149
150Available in version 1.0 and later.
151
152Given the iterator to the beginning of the UTF-8 sequence, it returns the code point and moves the iterator to the next position.
153
154```cpp
155template <typename octet_iterator>
156uint32_t next(octet_iterator& it, octet_iterator end);
157```
158
159`octet_iterator`: an input iterator.
160`it`: a reference to an iterator pointing to the beginning of an UTF-8 encoded code point. After the function returns, it is incremented to point to the beginning of the next code point.
161`end`: end of the UTF-8 sequence to be processed. If `it` gets equal to `end` during the extraction of a code point, an `utf8::not_enough_room` exception is thrown.
162Return value: the 32 bit representation of the processed UTF-8 code point.
163
164Example of use:
165
166```cpp
167char* twochars = "\xe6\x97\xa5\xd1\x88";
168char* w = twochars;
169int cp = next(w, twochars + 6);
170assert (cp == 0x65e5);
171assert (w == twochars + 3);
172```
173
174This function is typically used to iterate through a UTF-8 encoded string.
175
176In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown.
177
178#### utf8::peek_next
179
180Available in version 2.1 and later.
181
182Given the iterator to the beginning of the UTF-8 sequence, it returns the code point for the following sequence without changing the value of the iterator.
183
184```cpp
185template <typename octet_iterator>
186uint32_t peek_next(octet_iterator it, octet_iterator end);
187```
188
189
190`octet_iterator`: an input iterator.
191`it`: an iterator pointing to the beginning of an UTF-8 encoded code point.
192`end`: end of the UTF-8 sequence to be processed. If `it` gets equal to `end` during the extraction of a code point, an `utf8::not_enough_room` exception is thrown.
193Return value: the 32 bit representation of the processed UTF-8 code point.
194
195Example of use:
196
197```cpp
198char* twochars = "\xe6\x97\xa5\xd1\x88";
199char* w = twochars;
200int cp = peek_next(w, twochars + 6);
201assert (cp == 0x65e5);
202assert (w == twochars);
203```
204
205In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown.
206
207#### utf8::prior
208
209Available in version 1.02 and later.
210
211Given a reference to an iterator pointing to an octet in a UTF-8 sequence, it decreases the iterator until it hits the beginning of the previous UTF-8 encoded code point and returns the 32 bits representation of the code point.
212
213```cpp
214template <typename octet_iterator>
215uint32_t prior(octet_iterator& it, octet_iterator start);
216```
217
218`octet_iterator`: a bidirectional iterator.
219`it`: a reference pointing to an octet within a UTF-8 encoded string. After the function returns, it is decremented to point to the beginning of the previous code point.
220`start`: an iterator to the beginning of the sequence where the search for the beginning of a code point is performed. It is a safety measure to prevent passing the beginning of the string in the search for a UTF-8 lead octet.
221 Return value: the 32 bit representation of the previous code point.
222
223Example of use:
224
225```cpp
226char* twochars = "\xe6\x97\xa5\xd1\x88";
227unsigned char* w = twochars + 3;
228int cp = prior (w, twochars);
229assert (cp == 0x65e5);
230assert (w == twochars);
231```
232
233This function has two purposes: one is two iterate backwards through a UTF-8 encoded string. Note that it is usually a better idea to iterate forward instead, since `utf8::next` is faster. The second purpose is to find a beginning of a UTF-8 sequence if we have a random position within a string. Note that in that case `utf8::prior` may not detect an invalid UTF-8 sequence in some scenarios: for instance if there are superfluous trail octets, it will just skip them.
234
235`it` will typically point to the beginning of a code point, and `start` will point to the beginning of the string to ensure we don't go backwards too far. `it` is decreased until it points to a lead UTF-8 octet, and then the UTF-8 sequence beginning with that octet is decoded to a 32 bit representation and returned.
236
237In case `start` is reached before a UTF-8 lead octet is hit, or if an invalid UTF-8 sequence is started by the lead octet, an `invalid_utf8` exception is thrown.
238
239In case `start` equals `it`, a `not_enough_room` exception is thrown.
240
241#### utf8::previous
242
243Deprecated in version 1.02 and later.
244
245Given a reference to an iterator pointing to an octet in a UTF-8 seqence, it decreases the iterator until it hits the beginning of the previous UTF-8 encoded code point and returns the 32 bits representation of the code point.
246
247```cpp
248template <typename octet_iterator>
249uint32_t previous(octet_iterator& it, octet_iterator pass_start);
250```
251
252`octet_iterator`: a random access iterator.
253`it`: a reference pointing to an octet within a UTF-8 encoded string. After the function returns, it is decremented to point to the beginning of the previous code point.
254`pass_start`: an iterator to the point in the sequence where the search for the beginning of a code point is aborted if no result was reached. It is a safety measure to prevent passing the beginning of the string in the search for a UTF-8 lead octet.
255Return value: the 32 bit representation of the previous code point.
256
257Example of use:
258
259```cpp
260char* twochars = "\xe6\x97\xa5\xd1\x88";
261unsigned char* w = twochars + 3;
262int cp = previous (w, twochars - 1);
263assert (cp == 0x65e5);
264assert (w == twochars);
265```
266
267
268`utf8::previous` is deprecated, and `utf8::prior` should be used instead, although the existing code can continue using this function. The problem is the parameter `pass_start` that points to the position just before the beginning of the sequence. Standard containers don't have the concept of "pass start" and the function can not be used with their iterators.
269
270`it` will typically point to the beginning of a code point, and `pass_start` will point to the octet just before the beginning of the string to ensure we don't go backwards too far. `it` is decreased until it points to a lead UTF-8 octet, and then the UTF-8 sequence beginning with that octet is decoded to a 32 bit representation and returned.
271
272In case `pass_start` is reached before a UTF-8 lead octet is hit, or if an invalid UTF-8 sequence is started by the lead octet, an `invalid_utf8` exception is thrown
273
274#### utf8::advance
275Available in version 1.0 and later.
276
277Advances an iterator by the specified number of code points within an UTF-8 sequence.
278
279```cpp
280template <typename octet_iterator, typename distance_type>
281void advance (octet_iterator& it, distance_type n, octet_iterator end);
282```
283
284`octet_iterator`: an input iterator.
285`distance_type`: an integral type convertible to `octet_iterator`'s difference type.
286`it`: a reference to an iterator pointing to the beginning of an UTF-8 encoded code point. After the function returns, it is incremented to point to the nth following code point.
287`n`: a positive integer that shows how many code points we want to advance.
288`end`: end of the UTF-8 sequence to be processed. If `it` gets equal to `end` during the extraction of a code point, an `utf8::not_enough_room` exception is thrown.
289
290Example of use:
291
292```cpp
293char* twochars = "\xe6\x97\xa5\xd1\x88";
294unsigned char* w = twochars;
295advance (w, 2, twochars + 6);
296assert (w == twochars + 5);
297```
298
299This function works only "forward". In case of a negative `n`, there is no effect.
300
301In case of an invalid code point, a `utf8::invalid_code_point` exception is thrown.
302
303#### utf8::distance
304
305Available in version 1.0 and later.
306
307Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them.
308
309```cpp
310template <typename octet_iterator>
311typename std::iterator_traits<octet_iterator>::difference_type distance (octet_iterator first, octet_iterator last);
312```
313
314`octet_iterator`: an input iterator.
315`first`: an iterator to a beginning of a UTF-8 encoded code point.
316`last`: an iterator to a "post-end" of the last UTF-8 encoded code point in the sequence we are trying to determine the length. It can be the beginning of a new code point, or not.
317 Return value the distance between the iterators, in code points.
318
319Example of use:
320
321```cpp
322char* twochars = "\xe6\x97\xa5\xd1\x88";
323size_t dist = utf8::distance(twochars, twochars + 5);
324assert (dist == 2);
325```
326
327This function is used to find the length (in code points) of a UTF-8 encoded string. The reason it is called _distance_, rather than, say, _length_ is mainly because developers are used that _length_ is an O(1) function. Computing the length of an UTF-8 string is a linear operation, and it looked better to model it after `std::distance` algorithm.
328
329In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown. If `last` does not point to the past-of-end of a UTF-8 seqence, a `utf8::not_enough_room` exception is thrown.
330
331#### utf8::utf16to8
332
333Available in version 1.0 and later.
334
335Converts a UTF-16 encoded string to UTF-8.
336
337```cpp
338template <typename u16bit_iterator, typename octet_iterator>
339octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);
340```
341
342`u16bit_iterator`: an input iterator.
343`octet_iterator`: an output iterator.
344`start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert.
345`end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert.
346`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion.
347Return value: An iterator pointing to the place after the appended UTF-8 string.
348
349Example of use:
350
351```cpp
352unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
353vector<unsigned char> utf8result;
354utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
355assert (utf8result.size() == 10);
356```
357
358In case of invalid UTF-16 sequence, a `utf8::invalid_utf16` exception is thrown.
359
360#### utf8::utf8to16
361
362Available in version 1.0 and later.
363
364Converts an UTF-8 encoded string to UTF-16
365
366```cpp
367template <typename u16bit_iterator, typename octet_iterator>
368u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result);
369```
370
371`octet_iterator`: an input iterator.
372`u16bit_iterator`: an output iterator.
373`start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. < br /> `end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert.
374`result`: an output iterator to the place in the UTF-16 string where to append the result of conversion.
375Return value: An iterator pointing to the place after the appended UTF-16 string.
376
377Example of use:
378
379```cpp
380char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e";
381vector <unsigned short> utf16result;
382utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result));
383assert (utf16result.size() == 4);
384assert (utf16result[2] == 0xd834);
385assert (utf16result[3] == 0xdd1e);
386```
387
388In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown. If `end` does not point to the past-of-end of a UTF-8 seqence, a `utf8::not_enough_room` exception is thrown.
389
390#### utf8::utf32to8
391
392Available in version 1.0 and later.
393
394Converts a UTF-32 encoded string to UTF-8.
395
396```cpp
397template <typename octet_iterator, typename u32bit_iterator>
398octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result);
399```
400
401`octet_iterator`: an output iterator.
402`u32bit_iterator`: an input iterator.
403`start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert.
404`end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert.
405`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion.
406Return value: An iterator pointing to the place after the appended UTF-8 string.
407
408Example of use:
409
410```
411int utf32string[] = {0x448, 0x65E5, 0x10346, 0};
412vector<unsigned char> utf8result;
413utf32to8(utf32string, utf32string + 3, back_inserter(utf8result));
414assert (utf8result.size() == 9);
415```
416
417In case of invalid UTF-32 string, a `utf8::invalid_code_point` exception is thrown.
418
419#### utf8::utf8to32
420
421Available in version 1.0 and later.
422
423Converts a UTF-8 encoded string to UTF-32.
424
425```cpp
426template <typename octet_iterator, typename u32bit_iterator>
427u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result);
428```
429
430`octet_iterator`: an input iterator.
431`u32bit_iterator`: an output iterator.
432`start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert.
433`end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert.
434`result`: an output iterator to the place in the UTF-32 string where to append the result of conversion.
435Return value: An iterator pointing to the place after the appended UTF-32 string.
436
437Example of use:
438
439```cpp
440char* twochars = "\xe6\x97\xa5\xd1\x88";
441vector<int> utf32result;
442utf8to32(twochars, twochars + 5, back_inserter(utf32result));
443assert (utf32result.size() == 2);
444```
445
446In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown. If `end` does not point to the past-of-end of a UTF-8 seqence, a `utf8::not_enough_room` exception is thrown.
447
448#### utf8::find_invalid
449
450Available in version 1.0 and later.
451
452Detects an invalid sequence within a UTF-8 string.
453
454```cpp
455template <typename octet_iterator>
456octet_iterator find_invalid(octet_iterator start, octet_iterator end);
457```
458
459`octet_iterator`: an input iterator.
460`start`: an iterator pointing to the beginning of the UTF-8 string to test for validity.
461`end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity.
462Return value: an iterator pointing to the first invalid octet in the UTF-8 string. In case none were found, equals `end`.
463
464Example of use:
465
466```cpp
467char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
468char* invalid = find_invalid(utf_invalid, utf_invalid + 6);
469assert (invalid == utf_invalid + 5);
470```
471
472This function is typically used to make sure a UTF-8 string is valid before processing it with other functions. It is especially important to call it if before doing any of the _unchecked_ operations on it.
473
474#### utf8::is_valid
475
476Available in version 1.0 and later.
477
478Checks whether a sequence of octets is a valid UTF-8 string.
479
480```cpp
481template <typename octet_iterator>
482bool is_valid(octet_iterator start, octet_iterator end);
483```
484
485`octet_iterator`: an input iterator.
486`start`: an iterator pointing to the beginning of the UTF-8 string to test for validity.
487`end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity.
488Return value: `true` if the sequence is a valid UTF-8 string; `false` if not.
489
490Example of use:
491
492```cpp
493char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
494bool bvalid = is_valid(utf_invalid, utf_invalid + 6);
495assert (bvalid == false);
496```
497
498`is_valid` is a shorthand for `find_invalid(start, end) == end;`. You may want to use it to make sure that a byte seqence is a valid UTF-8 string without the need to know where it fails if it is not valid.
499
500#### utf8::replace_invalid
501
502Available in version 2.0 and later.
503
504Replaces all invalid UTF-8 sequences within a string with a replacement marker.
505
506```cpp
507template <typename octet_iterator, typename output_iterator>
508output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement);
509template <typename octet_iterator, typename output_iterator>
510output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out);
511```
512
513`octet_iterator`: an input iterator.
514`output_iterator`: an output iterator.
515`start`: an iterator pointing to the beginning of the UTF-8 string to look for invalid UTF-8 sequences.
516`end`: an iterator pointing to pass-the-end of the UTF-8 string to look for invalid UTF-8 sequences.
517`out`: An output iterator to the range where the result of replacement is stored.
518`replacement`: A Unicode code point for the replacement marker. The version without this parameter assumes the value `0xfffd`
519Return value: An iterator pointing to the place after the UTF-8 string with replaced invalid sequences.
520
521Example of use:
522
523```cpp
524char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z";
525vector<char> replace_invalid_result;
526replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), back_inserter(replace_invalid_result), '?');
527bvalid = is_valid(replace_invalid_result.begin(), replace_invalid_result.end());
528assert (bvalid);
529char* fixed_invalid_sequence = "a????z";
530assert (std::equal(replace_invalid_result.begin(), replace_invalid_result.end(), fixed_invalid_sequence));
531```
532
533`replace_invalid` does not perform in-place replacement of invalid sequences. Rather, it produces a copy of the original string with the invalid sequences replaced with a replacement marker. Therefore, `out` must not be in the `[start, end]` range.
534
535If `end` does not point to the past-of-end of a UTF-8 sequence, a `utf8::not_enough_room` exception is thrown.
536
537#### utf8::starts_with_bom
538
539Available in version 2.3 and later. Relaces deprecated `is_bom()` function.
540
541Checks whether an octet sequence starts with a UTF-8 byte order mark (BOM)
542
543```cpp
544template <typename octet_iterator>
545bool starts_with_bom (octet_iterator it, octet_iterator end);
546```
547
548`octet_iterator`: an input iterator.
549`it`: beginning of the octet sequence to check
550`end`: pass-end of the sequence to check
551Return value: `true` if the sequence starts with a UTF-8 byte order mark; `false` if not.
552
553Example of use:
554
555```cpp
556unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf};
557bool bbom = starts_with_bom(byte_order_mark, byte_order_mark + sizeof(byte_order_mark));
558assert (bbom == true);
559```
560
561The typical use of this function is to check the first three bytes of a file. If they form the UTF-8 BOM, we want to skip them before processing the actual UTF-8 encoded text.
562
563#### utf8::is_bom
564
565Available in version 1.0 and later. Deprecated in version 2.3\. `starts_with_bom()` should be used instead.
566
567Checks whether a sequence of three octets is a UTF-8 byte order mark (BOM)
568
569```cpp
570template <typename octet_iterator>
571bool is_bom (octet_iterator it);  // Deprecated
572```
573
574`octet_iterator`: an input iterator.
575`it`: beginning of the 3-octet sequence to check
576Return value: `true` if the sequence is UTF-8 byte order mark; `false` if not.
577
578Example of use:
579
580```cpp
581unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf};
582bool bbom = is_bom(byte_order_mark);
583assert (bbom == true);
584```
585
586The typical use of this function is to check the first three bytes of a file. If they form the UTF-8 BOM, we want to skip them before processing the actual UTF-8 encoded text.
587
588If a sequence is shorter than three bytes, an invalid iterator will be dereferenced. Therefore, this function is deprecated in favor of `starts_with_bom()`that takes the end of sequence as an argument.
589
590### Types From utf8 Namespace
591
592#### utf8::exception
593
594Available in version 2.3 and later.
595
596Base class for the exceptions thrown by UTF CPP library functions.
597
598```cpp
599class exception : public std::exception {};
600```
601
602Example of use:
603
604```cpp
605try {
606  code_that_uses_utf_cpp_library();
607}
608catch(const utf8::exception& utfcpp_ex) {
609  cerr << utfcpp_ex.what();
610}
611```
612
613#### utf8::invalid_code_point
614
615Available in version 1.0 and later.
616
617Thrown by UTF8 CPP functions such as `advance` and `next` if an UTF-8 sequence represents and invalid code point.
618
619```cpp
620class invalid_code_point : public exception {
621public:
622    uint32_t code_point() const;
623};
624```
625
626Member function `code_point()` can be used to determine the invalid code point that caused the exception to be thrown.
627
628#### utf8::invalid_utf8
629
630Available in version 1.0 and later.
631
632Thrown by UTF8 CPP functions such as `next` and `prior` if an invalid UTF-8 sequence is detected during decoding.
633
634```cpp
635class invalid_utf8 : public exception {
636public:
637    uint8_t utf8_octet() const;
638};
639```
640
641Member function `utf8_octet()` can be used to determine the beginning of the byte sequence that caused the exception to be thrown.
642
643#### utf8::invalid_utf16
644
645Available in version 1.0 and later.
646
647Thrown by UTF8 CPP function `utf16to8` if an invalid UTF-16 sequence is detected during decoding.
648
649```cpp
650class invalid_utf16 : public exception {
651public:
652    uint16_t utf16_word() const;
653};
654```
655
656Member function `utf16_word()` can be used to determine the UTF-16 code unit that caused the exception to be thrown.
657
658#### utf8::not_enough_room
659
660Available in version 1.0 and later.
661
662Thrown by UTF8 CPP functions such as `next` if the end of the decoded UTF-8 sequence was reached before the code point was decoded.
663
664```cpp
665class not_enough_room : public exception {};
666```
667
668#### utf8::iterator
669
670Available in version 2.0 and later.
671
672Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets.
673
674```cpp
675template <typename octet_iterator>
676class iterator;
677```
678
679##### Member functions
680
681`iterator();` the deafult constructor; the underlying octet_iterator is constructed with its default constructor.
682`explicit iterator (const octet_iterator& octet_it, const octet_iterator& range_start, const octet_iterator& range_end);` a constructor that initializes the underlying octet_iterator with octet_it and sets the range in which the iterator is considered valid.
683`octet_iterator base () const;` returns the underlying octet_iterator.
684`uint32_t operator * () const;` decodes the utf-8 sequence the underlying octet_iterator is pointing to and returns the code point.
685`bool operator == (const iterator& rhs) const;` returns `true` if the two underlaying iterators are equal.
686`bool operator != (const iterator& rhs) const;` returns `true` if the two underlaying iterators are not equal.
687`iterator& operator ++ ();` the prefix increment - moves the iterator to the next UTF-8 encoded code point.
688`iterator operator ++ (int);` the postfix increment - moves the iterator to the next UTF-8 encoded code point and returns the current one.
689`iterator& operator -- ();` the prefix decrement - moves the iterator to the previous UTF-8 encoded code point.
690`iterator operator -- (int);` the postfix decrement - moves the iterator to the previous UTF-8 encoded code point and returns the current one.
691
692Example of use:
693
694```cpp
695char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
696utf8::iterator<char*> it(threechars, threechars, threechars + 9);
697utf8::iterator<char*> it2 = it;
698assert (it2 == it);
699assert (*it == 0x10346);
700assert (*(++it) == 0x65e5);
701assert ((*it++) == 0x65e5);
702assert (*it == 0x0448);
703assert (it != it2);
704utf8::iterator<char*> endit (threechars + 9, threechars, threechars + 9);
705assert (++it == endit);
706assert (*(--it) == 0x0448);
707assert ((*it--) == 0x0448);
708assert (*it == 0x65e5);
709assert (--it == utf8::iterator<char*>(threechars, threechars, threechars + 9));
710assert (*it == 0x10346);
711```
712
713The purpose of `utf8::iterator` adapter is to enable easy iteration as well as the use of STL algorithms with UTF-8 encoded strings. Increment and decrement operators are implemented in terms of `utf8::next()` and `utf8::prior()` functions.
714
715Note that `utf8::iterator` adapter is a checked iterator. It operates on the range specified in the constructor; any attempt to go out of that range will result in an exception. Even the comparison operators require both iterator object to be constructed against the same range - otherwise an exception is thrown. Typically, the range will be determined by sequence container functions `begin` and `end`, i.e.:
716
717```cpp
718std::string s = "example";
719utf8::iterator i (s.begin(), s.begin(), s.end());
720```
721
722### Functions From utf8::unchecked Namespace
723
724#### utf8::unchecked::append
725
726Available in version 1.0 and later.
727
728Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string.
729
730```cpp
731template <typename octet_iterator>
732octet_iterator append(uint32_t cp, octet_iterator result);
733```
734
735`cp`: A 32 bit integer representing a code point to append to the sequence.
736`result`: An output iterator to the place in the sequence where to append the code point.
737Return value: An iterator pointing to the place after the newly appended sequence.
738
739Example of use:
740
741```cpp
742unsigned char u[5] = {0,0,0,0,0};
743unsigned char* end = unchecked::append(0x0448, u);
744assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0);
745```
746
747This is a faster but less safe version of `utf8::append`. It does not check for validity of the supplied code point, and may produce an invalid UTF-8 sequence.
748
749#### utf8::unchecked::next
750
751Available in version 1.0 and later.
752
753Given the iterator to the beginning of a UTF-8 sequence, it returns the code point and moves the iterator to the next position.
754
755```cpp
756template <typename octet_iterator>
757uint32_t next(octet_iterator& it);
758```
759
760`it`: a reference to an iterator pointing to the beginning of an UTF-8 encoded code point. After the function returns, it is incremented to point to the beginning of the next code point.
761 Return value: the 32 bit representation of the processed UTF-8 code point.
762
763Example of use:
764
765```cpp
766char* twochars = "\xe6\x97\xa5\xd1\x88";
767char* w = twochars;
768int cp = unchecked::next(w);
769assert (cp == 0x65e5);
770assert (w == twochars + 3);
771```
772
773This is a faster but less safe version of `utf8::next`. It does not check for validity of the supplied UTF-8 sequence.
774
775#### utf8::unchecked::peek_next
776
777Available in version 2.1 and later.
778
779Given the iterator to the beginning of a UTF-8 sequence, it returns the code point.
780
781```cpp
782template <typename octet_iterator>
783uint32_t peek_next(octet_iterator it);
784```
785
786`it`: an iterator pointing to the beginning of an UTF-8 encoded code point.
787Return value: the 32 bit representation of the processed UTF-8 code point.
788
789Example of use:
790
791```cpp
792char* twochars = "\xe6\x97\xa5\xd1\x88";
793char* w = twochars;
794int cp = unchecked::peek_next(w);
795assert (cp == 0x65e5);
796assert (w == twochars);
797```
798
799This is a faster but less safe version of `utf8::peek_next`. It does not check for validity of the supplied UTF-8 sequence.
800
801#### utf8::unchecked::prior
802
803Available in version 1.02 and later.
804
805Given a reference to an iterator pointing to an octet in a UTF-8 seqence, it decreases the iterator until it hits the beginning of the previous UTF-8 encoded code point and returns the 32 bits representation of the code point.
806
807```cpp
808template <typename octet_iterator>
809uint32_t prior(octet_iterator& it);
810```
811
812`it`: a reference pointing to an octet within a UTF-8 encoded string. After the function returns, it is decremented to point to the beginning of the previous code point.
813 Return value: the 32 bit representation of the previous code point.
814
815Example of use:
816
817```cpp
818char* twochars = "\xe6\x97\xa5\xd1\x88";
819char* w = twochars + 3;
820int cp = unchecked::prior (w);
821assert (cp == 0x65e5);
822assert (w == twochars);
823```
824
825This is a faster but less safe version of `utf8::prior`. It does not check for validity of the supplied UTF-8 sequence and offers no boundary checking.
826
827#### utf8::unchecked::previous (deprecated, see utf8::unchecked::prior)
828
829Deprecated in version 1.02 and later.
830
831Given a reference to an iterator pointing to an octet in a UTF-8 seqence, it decreases the iterator until it hits the beginning of the previous UTF-8 encoded code point and returns the 32 bits representation of the code point.
832
833```cpp
834template <typename octet_iterator>
835uint32_t previous(octet_iterator& it);
836```
837
838`it`: a reference pointing to an octet within a UTF-8 encoded string. After the function returns, it is decremented to point to the beginning of the previous code point.
839Return value: the 32 bit representation of the previous code point.
840
841Example of use:
842
843```cpp
844char* twochars = "\xe6\x97\xa5\xd1\x88";
845char* w = twochars + 3;
846int cp = unchecked::previous (w);
847assert (cp == 0x65e5);
848assert (w == twochars);
849```
850
851The reason this function is deprecated is just the consistency with the "checked" versions, where `prior` should be used instead of `previous`. In fact, `unchecked::previous` behaves exactly the same as `unchecked::prior`
852
853This is a faster but less safe version of `utf8::previous`. It does not check for validity of the supplied UTF-8 sequence and offers no boundary checking.
854
855#### utf8::unchecked::advance
856
857Available in version 1.0 and later.
858
859Advances an iterator by the specified number of code points within an UTF-8 sequence.
860
861```cpp
862template <typename octet_iterator, typename distance_type>
863void advance (octet_iterator& it, distance_type n);
864```
865
866`it`: a reference to an iterator pointing to the beginning of an UTF-8 encoded code point. After the function returns, it is incremented to point to the nth following code point.
867`n`: a positive integer that shows how many code points we want to advance.
868
869Example of use:
870
871```cpp
872char* twochars = "\xe6\x97\xa5\xd1\x88";
873char* w = twochars;
874unchecked::advance (w, 2);
875assert (w == twochars + 5);
876```
877
878This function works only "forward". In case of a negative `n`, there is no effect.
879
880This is a faster but less safe version of `utf8::advance`. It does not check for validity of the supplied UTF-8 sequence and offers no boundary checking.
881
882#### utf8::unchecked::distance
883
884Available in version 1.0 and later.
885
886Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them.
887
888```cpp
889template <typename octet_iterator>
890typename std::iterator_traits<octet_iterator>::difference_type distance (octet_iterator first, octet_iterator last);
891```
892
893`first`: an iterator to a beginning of a UTF-8 encoded code point.
894`last`: an iterator to a "post-end" of the last UTF-8 encoded code point in the sequence we are trying to determine the length. It can be the beginning of a new code point, or not.
895Return value: the distance between the iterators, in code points.
896
897Example of use:
898
899```cpp
900char* twochars = "\xe6\x97\xa5\xd1\x88";
901size_t dist = utf8::unchecked::distance(twochars, twochars + 5);
902assert (dist == 2);
903```
904
905This is a faster but less safe version of `utf8::distance`. It does not check for validity of the supplied UTF-8 sequence.
906
907#### utf8::unchecked::utf16to8
908
909Available in version 1.0 and later.
910
911Converts a UTF-16 encoded string to UTF-8.
912
913```cpp
914template <typename u16bit_iterator, typename octet_iterator>
915octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);
916```
917
918`start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert.
919`end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert.
920`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion.
921Return value: An iterator pointing to the place after the appended UTF-8 string.
922
923Example of use:
924
925```cpp
926unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
927vector<unsigned char> utf8result;
928unchecked::utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
929assert (utf8result.size() == 10);
930```
931
932This is a faster but less safe version of `utf8::utf16to8`. It does not check for validity of the supplied UTF-16 sequence.
933
934#### utf8::unchecked::utf8to16
935
936Available in version 1.0 and later.
937
938Converts an UTF-8 encoded string to UTF-16
939
940```cpp
941template <typename u16bit_iterator, typename octet_iterator>
942u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result);
943```
944
945`start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. < br /> `end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert.
946`result`: an output iterator to the place in the UTF-16 string where to append the result of conversion.
947Return value: An iterator pointing to the place after the appended UTF-16 string.
948
949Example of use:
950
951```cpp
952char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e";
953vector <unsigned short> utf16result;
954unchecked::utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result));
955assert (utf16result.size() == 4);
956assert (utf16result[2] == 0xd834);
957assert (utf16result[3] == 0xdd1e);
958```
959
960This is a faster but less safe version of `utf8::utf8to16`. It does not check for validity of the supplied UTF-8 sequence.
961
962#### utf8::unchecked::utf32to8
963
964Available in version 1.0 and later.
965
966Converts a UTF-32 encoded string to UTF-8.
967
968```cpp
969template <typename octet_iterator, typename u32bit_iterator>
970octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result);
971```
972
973`start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert.
974`end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert.
975`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion.
976Return value: An iterator pointing to the place after the appended UTF-8 string.
977
978Example of use:
979
980```cpp
981int utf32string[] = {0x448, 0x65e5, 0x10346, 0};
982vector<unsigned char> utf8result;
983utf32to8(utf32string, utf32string + 3, back_inserter(utf8result));
984assert (utf8result.size() == 9);
985```
986
987This is a faster but less safe version of `utf8::utf32to8`. It does not check for validity of the supplied UTF-32 sequence.
988
989#### utf8::unchecked::utf8to32
990
991Available in version 1.0 and later.
992
993Converts a UTF-8 encoded string to UTF-32.
994
995```cpp
996template <typename octet_iterator, typename u32bit_iterator>
997u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result);
998```
999
1000`start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert.
1001`end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert.
1002`result`: an output iterator to the place in the UTF-32 string where to append the result of conversion.
1003Return value: An iterator pointing to the place after the appended UTF-32 string.
1004
1005Example of use:
1006
1007```cpp
1008char* twochars = "\xe6\x97\xa5\xd1\x88";
1009vector<int> utf32result;
1010unchecked::utf8to32(twochars, twochars + 5, back_inserter(utf32result));
1011assert (utf32result.size() == 2);
1012```
1013
1014This is a faster but less safe version of `utf8::utf8to32`. It does not check for validity of the supplied UTF-8 sequence.
1015
1016### Types From utf8::unchecked Namespace
1017
1018#### utf8::iterator
1019
1020Available in version 2.0 and later.
1021
1022Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets.
1023
1024```cpp
1025template <typename octet_iterator>
1026class iterator;
1027```
1028
1029##### Member functions
1030
1031`iterator();` the deafult constructor; the underlying octet_iterator is constructed with its default constructor.
1032`explicit iterator (const octet_iterator& octet_it);` a constructor that initializes the underlying octet_iterator with `octet_it`
1033`octet_iterator base () const;` returns the underlying octet_iterator.
1034`uint32_t operator * () const;` decodes the utf-8 sequence the underlying octet_iterator is pointing to and returns the code point.
1035`bool operator == (const iterator& rhs) const;` returns `true` if the two underlaying iterators are equal.
1036`bool operator != (const iterator& rhs) const;` returns `true` if the two underlaying iterators are not equal.
1037`iterator& operator ++ ();` the prefix increment - moves the iterator to the next UTF-8 encoded code point.
1038`iterator operator ++ (int);` the postfix increment - moves the iterator to the next UTF-8 encoded code point and returns the current one.
1039`iterator& operator -- ();` the prefix decrement - moves the iterator to the previous UTF-8 encoded code point.
1040`iterator operator -- (int);` the postfix decrement - moves the iterator to the previous UTF-8 encoded code point and returns the current one.
1041
1042Example of use:
1043
1044```cpp
1045char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
1046utf8::unchecked::iterator<char*> un_it(threechars);
1047utf8::unchecked::iterator<char*> un_it2 = un_it;
1048assert (un_it2 == un_it);
1049assert (*un_it == 0x10346);
1050assert (*(++un_it) == 0x65e5);
1051assert ((*un_it++) == 0x65e5);
1052assert (*un_it == 0x0448);
1053assert (un_it != un_it2);
1054utf8::::unchecked::iterator<char*> un_endit (threechars + 9);
1055assert (++un_it == un_endit);
1056assert (*(--un_it) == 0x0448);
1057assert ((*un_it--) == 0x0448);
1058assert (*un_it == 0x65e5);
1059assert (--un_it == utf8::unchecked::iterator<char*>(threechars));
1060assert (*un_it == 0x10346);
1061```
1062
1063This is an unchecked version of `utf8::iterator`. It is faster in many cases, but offers no validity or range checks.
1064
1065## Points of interest
1066
1067#### Design goals and decisions
1068
1069The library was designed to be:
1070
10711.  Generic: for better or worse, there are many C++ string classes out there, and the library should work with as many of them as possible.
10722.  Portable: the library should be portable both accross different platforms and compilers. The only non-portable code is a small section that declares unsigned integers of different sizes: three typedefs. They can be changed by the users of the library if they don't match their platform. The default setting should work for Windows (both 32 and 64 bit), and most 32 bit and 64 bit Unix derivatives. At this point I don't plan to use any post C++03 features, so the library should work even with pretty old compilers.
10733.  Lightweight: follow the "pay only for what you use" guideline.
10744.  Unintrusive: avoid forcing any particular design or even programming style on the user. This is a library, not a framework.
1075
1076#### Alternatives
1077
1078In case you want to look into other means of working with UTF-8 strings from C++, here is the list of solutions I am aware of:
1079
10801.  [ICU Library](http://icu.sourceforge.net/). It is very powerful, complete, feature-rich, mature, and widely used. Also big, intrusive, non-generic, and doesn't play well with the Standard Library. I definitelly recommend looking at ICU even if you don't plan to use it.
10812.  C++11 language and library features. Still far from complete, and not easy to use.
10823.  [Glib::ustring](http://www.gtkmm.org/gtkmm2/docs/tutorial/html/ch03s04.html). A class specifically made to work with UTF-8 strings, and also feel like `std::string`. If you prefer to have yet another string class in your code, it may be worth a look. Be aware of the licensing issues, though.
10834.  Platform dependent solutions: Windows and POSIX have functions to convert strings from one encoding to another. That is only a subset of what my library offers, but if that is all you need it may be good enough.
1084
1085## Links
1086
10871.  [The Unicode Consortium](http://www.unicode.org/).
10882.  [ICU Library](http://icu.sourceforge.net/).
10893.  [UTF-8 at Wikipedia](http://en.wikipedia.org/wiki/UTF-8)
10904.  [UTF-8 and Unicode FAQ for Unix/Linux](http://www.cl.cam.ac.uk/~mgk25/unicode.html)
1091