From 6bb44ed91ae8e68576458110e90f74dc528e9679 Mon Sep 17 00:00:00 2001 From: nemtrif Date: Sat, 15 Aug 2015 12:11:54 -0400 Subject: [PATCH 01/18] Initial commit --- README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..57fbd0bce --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# utfcpp +UTF-8 with C++ in a Portable Way From 46d0d807dcb6cd102be305711d1b0e94da943035 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sun, 16 Aug 2015 08:55:59 -0400 Subject: [PATCH 02/18] Initial import Importing utf8 cpp 2.3.4 to GitHub. --- README.md | 1133 ++++++++++++++++- buildrelease.pl | 18 + samples/Makefile | 5 + samples/docsample.cpp | 52 + source/utf8.h | 34 + source/utf8/checked.h | 327 +++++ source/utf8/core.h | 329 +++++ source/utf8/unchecked.h | 228 ++++ test_data/negative/utf8_invalid.txt | Bin 0 -> 20010 bytes test_data/utf8samples/UTF-8-demo.txt | 212 +++ .../utf8samples/Unicode_transcriptions.html | 167 +++ test_data/utf8samples/quickbrown.txt | 126 ++ test_drivers/Makefile | 19 + test_drivers/negative/Makefile | 5 + test_drivers/negative/negative.cpp | 53 + test_drivers/performance/Makefile | 5 + test_drivers/performance/iconvtest.cpp | 132 ++ test_drivers/performance/timer.h | 22 + test_drivers/performance/win32.cpp | 110 ++ test_drivers/runtests.pl | 50 + test_drivers/smoke_test/Makefile | 5 + test_drivers/smoke_test/test.cpp | 297 +++++ test_drivers/utf8reader/Makefile | 5 + test_drivers/utf8reader/utf8reader.cpp | 160 +++ 24 files changed, 3492 insertions(+), 2 deletions(-) create mode 100644 buildrelease.pl create mode 100644 samples/Makefile create mode 100644 samples/docsample.cpp create mode 100644 source/utf8.h create mode 100644 source/utf8/checked.h create mode 100644 source/utf8/core.h create mode 100644 source/utf8/unchecked.h create mode 100644 test_data/negative/utf8_invalid.txt create mode 100644 test_data/utf8samples/UTF-8-demo.txt create mode 100644 test_data/utf8samples/Unicode_transcriptions.html create mode 100644 test_data/utf8samples/quickbrown.txt create mode 100644 test_drivers/Makefile create mode 100644 test_drivers/negative/Makefile create mode 100644 test_drivers/negative/negative.cpp create mode 100644 test_drivers/performance/Makefile create mode 100644 test_drivers/performance/iconvtest.cpp create mode 100644 test_drivers/performance/timer.h create mode 100644 test_drivers/performance/win32.cpp create mode 100644 test_drivers/runtests.pl create mode 100644 test_drivers/smoke_test/Makefile create mode 100644 test_drivers/smoke_test/test.cpp create mode 100644 test_drivers/utf8reader/Makefile create mode 100644 test_drivers/utf8reader/utf8reader.cpp diff --git a/README.md b/README.md index 57fbd0bce..9585b2fe0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,1131 @@ -# utfcpp -UTF-8 with C++ in a Portable Way +# UTF8-CPP: UTF-8 with C++ in a Portable Way + +[The Sourceforge project page](https://sourceforge.net/projects/utfcpp) + +
+ +## Table of Contents + +* [Introduction](#introduction) +* [Examples of Use](#examples) + * [Introductionary Sample](#introsample) + * [Checking if a file contains valid UTF-8 text](#validfile) + * [Ensure that a string contains valid UTF-8 text](#fixinvalid) +* [Reference](#reference) + * [Functions From utf8 Namespace](#funutf8) + * [Types From utf8 Namespace](#typesutf8) + * [Functions From utf8::unchecked Namespace](#fununchecked) + * [Types From utf8::unchecked Namespace](#typesunchecked) +* [Points of Interest](#points) +* [Links](#links) + +
+ +## Introduction + +Many 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. + +In order to easily handle UTF-8 encoded Unicode strings, I came up with a small 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. If you run into bugs or performance issues, please let me know and I'll do my best to address them. + +The 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. + +## Examples of use + +### Introductionary Sample + +To 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: + +
#include 
+#include 
+#include 
+#include 
+#include "utf8.h"
+using namespace std;
+int main(int argc, char** argv)
+{
+    if (argc != 2) {
+        cout << "\nUsage: docsample filename\n";
+        return 0;
+    }
+
+    const char* test_file_path = argv[1];
+    // Open the test file (contains UTF-8 encoded text)
+    ifstream fs8(test_file_path);
+    if (!fs8.is_open()) {
+    cout << "Could not open " << test_file_path << endl;
+    return 0;
+    }
+
+    unsigned line_count = 1;
+    string line;
+    // Play with all the lines in the file
+    while (getline(fs8, line)) {
+       // check for invalid utf-8 (for a simple yes/no check, there is also utf8::is_valid function)
+        string::iterator end_it = utf8::find_invalid(line.begin(), line.end());
+        if (end_it != line.end()) {
+            cout << "Invalid UTF-8 encoding detected at line " << line_count << "\n";
+            cout << "This part is fine: " << string(line.begin(), end_it) << "\n";
+        }
+
+        // Get the line length (at least for the valid part)
+        int length = utf8::distance(line.begin(), end_it);
+        cout << "Length of line " << line_count << " is " << length <<  "\n";
+
+        // Convert it to utf-16
+        vector utf16line;
+        utf8::utf8to16(line.begin(), end_it, back_inserter(utf16line));
+
+        // And back to utf-8
+        string utf8line; 
+        utf8::utf16to8(utf16line.begin(), utf16line.end(), back_inserter(utf8line));
+
+        // Confirm that the conversion went OK:
+        if (utf8line != string(line.begin(), end_it))
+            cout << "Error in UTF-16 conversion at line: " << line_count << "\n";        
+
+        line_count++;
+    }
+    return 0;
+}
+
+ +In 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`. + +### Checking if a file contains valid UTF-8 text + +Here is a function that checks whether the content of a file is valid UTF-8 encoded text without reading the content into the memory: + +
    
+bool valid_utf8_file(iconst char* file_name)
+{
+    ifstream ifs(file_name);
+    if (!ifs)
+        return false; // even better, throw here
+
+    istreambuf_iterator<char> it(ifs.rdbuf());
+    istreambuf_iterator<char> eos;
+
+    return utf8::is_valid(it, eos);
+}
+
+ +Because 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. + +Note 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: + +
    utf8::utf8to16(it, eos, back_inserter(u16string));
+
+ +### Ensure that a string contains valid UTF-8 text + +If 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: + +
void fix_utf8_string(std::string& str)
+{
+    std::string temp;
+    utf8::replace_invalid(str.begin(), str.end(), back_inserter(temp));
+    str = temp;
+}
+
+ +The 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. + +## Reference + +### Functions From utf8 Namespace + +#### utf8::append + +Available in version 1.0 and later. + +Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string. + +
template <typename octet_iterator>
+octet_iterator append(uint32_t cp, octet_iterator result);
+
+
+ +`octet_iterator`: an output iterator. + `cp`: a 32 bit integer representing a code point to append to the sequence. + `result`: an output iterator to the place in the sequence where to append the code point. + Return value: an iterator pointing to the place after the newly appended sequence. + +Example of use: + +
unsigned char u[5] = {0,0,0,0,0};
+unsigned char* end = append(0x0448, u);
+assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0);
+
+ +Note 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. + +In case of an invalid code point, a `utf8::invalid_code_point` exception is thrown. + +#### utf8::next + +Available in version 1.0 and later. + +Given the iterator to the beginning of the UTF-8 sequence, it returns the code point and moves the iterator to the next position. + +
template <typename octet_iterator> 
+uint32_t next(octet_iterator& it, octet_iterator end);
+
+
+ +`octet_iterator`: an input iterator. + `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. + `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. + Return value: the 32 bit representation of the processed UTF-8 code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+int cp = next(w, twochars + 6);
+assert (cp == 0x65e5);
+assert (w == twochars + 3);
+
+ +This function is typically used to iterate through a UTF-8 encoded string. + +In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown. + +#### utf8::peek_next + +Available in version 2.1 and later. + +Given 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. + +
template <typename octet_iterator> 
+uint32_t peek_next(octet_iterator it, octet_iterator end);
+
+
+ +`octet_iterator`: an input iterator. + `it`: an iterator pointing to the beginning of an UTF-8 encoded code point. + `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. + Return value: the 32 bit representation of the processed UTF-8 code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+int cp = peek_next(w, twochars + 6);
+assert (cp == 0x65e5);
+assert (w == twochars);
+
+ +In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown. + +#### utf8::prior + +Available in version 1.02 and later. + +Given 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. + +
template <typename octet_iterator> 
+uint32_t prior(octet_iterator& it, octet_iterator start);
+
+
+ +`octet_iterator`: a bidirectional iterator. + `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. + `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. + Return value: the 32 bit representation of the previous code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+unsigned char* w = twochars + 3;
+int cp = prior (w, twochars);
+assert (cp == 0x65e5);
+assert (w == twochars);
+
+ +This 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. + +`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. + +In 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. + +In case `start` equals `it`, a `not_enough_room` exception is thrown. + +#### utf8::previous + +Deprecated in version 1.02 and later. + +Given 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. + +
template <typename octet_iterator> 
+uint32_t previous(octet_iterator& it, octet_iterator pass_start);
+
+
+ +`octet_iterator`: a random access iterator. + `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. + `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. + Return value: the 32 bit representation of the previous code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+unsigned char* w = twochars + 3;
+int cp = previous (w, twochars - 1);
+assert (cp == 0x65e5);
+assert (w == twochars);
+
+ +`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. + +`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. + +In 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 + +#### utf8::advance + +Available in version 1.0 and later. + +Advances an iterator by the specified number of code points within an UTF-8 sequence. + +
template <typename octet_iterator, typename distance_type> 
+void advance (octet_iterator& it, distance_type n, octet_iterator end);
+
+
+ +`octet_iterator`: an input iterator. + `distance_type`: an integral type convertible to `octet_iterator`'s difference type. + `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. + `n`: a positive integer that shows how many code points we want to advance. + `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. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+unsigned char* w = twochars;
+advance (w, 2, twochars + 6);
+assert (w == twochars + 5);
+
+ +This function works only "forward". In case of a negative `n`, there is no effect. + +In case of an invalid code point, a `utf8::invalid_code_point` exception is thrown. + +#### utf8::distance + +Available in version 1.0 and later. + +Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them. + +
template <typename octet_iterator> 
+typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last);
+
+
+ +`octet_iterator`: an input iterator. + `first`: an iterator to a beginning of a UTF-8 encoded code point. + `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. + Return value the distance between the iterators, in code points. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+size_t dist = utf8::distance(twochars, twochars + 5);
+assert (dist == 2);
+
+ +This 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. + +In 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. + +#### utf8::utf16to8 + +Available in version 1.0 and later. + +Converts a UTF-16 encoded string to UTF-8. + +
template <typename u16bit_iterator, typename octet_iterator>
+octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);
+
+
+ +`u16bit_iterator`: an input iterator. + `octet_iterator`: an output iterator. + `start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert. + `end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert. + `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-8 string. + +Example of use: + +
unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
+vector<unsigned char> utf8result;
+utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
+assert (utf8result.size() == 10);    
+
+ +In case of invalid UTF-16 sequence, a `utf8::invalid_utf16` exception is thrown. + +#### utf8::utf8to16 + +Available in version 1.0 and later. + +Converts an UTF-8 encoded string to UTF-16 + +
template <typename u16bit_iterator, typename octet_iterator>
+u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result);
+
+
+ +`octet_iterator`: an input iterator. + `u16bit_iterator`: an output iterator. + `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. + `result`: an output iterator to the place in the UTF-16 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-16 string. + +Example of use: + +
char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e";
+vector <unsigned short> utf16result;
+utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result));
+assert (utf16result.size() == 4);
+assert (utf16result[2] == 0xd834);
+assert (utf16result[3] == 0xdd1e);
+
+ +In 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. + +#### utf8::utf32to8 + +Available in version 1.0 and later. + +Converts a UTF-32 encoded string to UTF-8. + +
template <typename octet_iterator, typename u32bit_iterator>
+octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result);
+
+
+ +`octet_iterator`: an output iterator. + `u32bit_iterator`: an input iterator. + `start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert. + `end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert. + `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-8 string. + +Example of use: + +
int utf32string[] = {0x448, 0x65E5, 0x10346, 0};
+vector<unsigned char> utf8result;
+utf32to8(utf32string, utf32string + 3, back_inserter(utf8result));
+assert (utf8result.size() == 9);
+
+ +In case of invalid UTF-32 string, a `utf8::invalid_code_point` exception is thrown. + +#### utf8::utf8to32 + +Available in version 1.0 and later. + +Converts a UTF-8 encoded string to UTF-32. + +
template <typename octet_iterator, typename u32bit_iterator>
+u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result);
+
+
+ +`octet_iterator`: an input iterator. + `u32bit_iterator`: an output iterator. + `start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. + `end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert. + `result`: an output iterator to the place in the UTF-32 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-32 string. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+vector<int> utf32result;
+utf8to32(twochars, twochars + 5, back_inserter(utf32result));
+assert (utf32result.size() == 2);
+
+ +In 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. + +#### utf8::find_invalid + +Available in version 1.0 and later. + +Detects an invalid sequence within a UTF-8 string. + +
template <typename octet_iterator> 
+octet_iterator find_invalid(octet_iterator start, octet_iterator end);
+
+ +`octet_iterator`: an input iterator. + `start`: an iterator pointing to the beginning of the UTF-8 string to test for validity. + `end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity. + Return value: an iterator pointing to the first invalid octet in the UTF-8 string. In case none were found, equals `end`. + +Example of use: + +
char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
+char* invalid = find_invalid(utf_invalid, utf_invalid + 6);
+assert (invalid == utf_invalid + 5);
+
+ +This 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. + +#### utf8::is_valid + +Available in version 1.0 and later. + +Checks whether a sequence of octets is a valid UTF-8 string. + +
template <typename octet_iterator> 
+bool is_valid(octet_iterator start, octet_iterator end);
+
+
+ +`octet_iterator`: an input iterator. + `start`: an iterator pointing to the beginning of the UTF-8 string to test for validity. + `end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity. + Return value: `true` if the sequence is a valid UTF-8 string; `false` if not. + +Example of use: + +
char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
+bool bvalid = is_valid(utf_invalid, utf_invalid + 6);
+assert (bvalid == false);
+
+ +`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. + +#### utf8::replace_invalid + +Available in version 2.0 and later. + +Replaces all invalid UTF-8 sequences within a string with a replacement marker. + +
template <typename octet_iterator, typename output_iterator>
+output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement);
+template <typename octet_iterator, typename output_iterator>
+output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out);
+
+
+ +`octet_iterator`: an input iterator. + `output_iterator`: an output iterator. + `start`: an iterator pointing to the beginning of the UTF-8 string to look for invalid UTF-8 sequences. + `end`: an iterator pointing to pass-the-end of the UTF-8 string to look for invalid UTF-8 sequences. + `out`: An output iterator to the range where the result of replacement is stored. + `replacement`: A Unicode code point for the replacement marker. The version without this parameter assumes the value `0xfffd` + Return value: An iterator pointing to the place after the UTF-8 string with replaced invalid sequences. + +Example of use: + +
char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z";
+vector<char> replace_invalid_result;
+replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), back_inserter(replace_invalid_result), '?');
+bvalid = is_valid(replace_invalid_result.begin(), replace_invalid_result.end());
+assert (bvalid);
+char* fixed_invalid_sequence = "a????z";
+assert (std::equal(replace_invalid_result.begin(), replace_invalid_result.end(), fixed_invalid_sequence));
+
+ +`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. + +If `end` does not point to the past-of-end of a UTF-8 sequence, a `utf8::not_enough_room` exception is thrown. + +#### utf8::starts_with_bom + +Available in version 2.3 and later. Relaces deprecated `is_bom()` function. + +Checks whether an octet sequence starts with a UTF-8 byte order mark (BOM) + +
template <typename octet_iterator> 
+bool starts_with_bom (octet_iterator it, octet_iterator end);
+
+ +`octet_iterator`: an input iterator. + `it`: beginning of the octet sequence to check + `end`: pass-end of the sequence to check + Return value: `true` if the sequence starts with a UTF-8 byte order mark; `false` if not. + +Example of use: + +
unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf};
+bool bbom = starts_with_bom(byte_order_mark, byte_order_mark + sizeof(byte_order_mark));
+assert (bbom == true);
+
+ +The 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. + +#### utf8::is_bom + +Available in version 1.0 and later. Deprecated in version 2.3\. `starts_with_bom()` should be used instead. + +Checks whether a sequence of three octets is a UTF-8 byte order mark (BOM) + +
template <typename octet_iterator> 
+bool is_bom (octet_iterator it);  // Deprecated
+
+ +`octet_iterator`: an input iterator. + `it`: beginning of the 3-octet sequence to check + Return value: `true` if the sequence is UTF-8 byte order mark; `false` if not. + +Example of use: + +
unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf};
+bool bbom = is_bom(byte_order_mark);
+assert (bbom == true);
+
+ +The 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. + +If 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. + +### Types From utf8 Namespace + +#### utf8::exception + +Available in version 2.3 and later. + +Base class for the exceptions thrown by UTF CPP library functions. + +
class exception : public std::exception {};
+
+ +Example of use: + +
try {
+  code_that_uses_utf_cpp_library();
+}
+catch(const utf8::exception& utfcpp_ex) {
+  cerr << utfcpp_ex.what();
+}
+
+ +#### utf8::invalid_code_point + +Available in version 1.0 and later. + +Thrown by UTF8 CPP functions such as `advance` and `next` if an UTF-8 sequence represents and invalid code point. + +
class invalid_code_point : public exception {
+public: 
+    uint32_t code_point() const;
+};
+
+
+ +Member function `code_point()` can be used to determine the invalid code point that caused the exception to be thrown. + +#### utf8::invalid_utf8 + +Available in version 1.0 and later. + +Thrown by UTF8 CPP functions such as `next` and `prior` if an invalid UTF-8 sequence is detected during decoding. + +
class invalid_utf8 : public exception {
+public: 
+    uint8_t utf8_octet() const;
+};
+
+ +Member function `utf8_octet()` can be used to determine the beginning of the byte sequence that caused the exception to be thrown. + +#### utf8::invalid_utf16 + +Available in version 1.0 and later. + +Thrown by UTF8 CPP function `utf16to8` if an invalid UTF-16 sequence is detected during decoding. + +
class invalid_utf16 : public exception {
+public: 
+    uint16_t utf16_word() const;
+};
+
+ +Member function `utf16_word()` can be used to determine the UTF-16 code unit that caused the exception to be thrown. + +#### utf8::not_enough_room + +Available in version 1.0 and later. + +Thrown by UTF8 CPP functions such as `next` if the end of the decoded UTF-8 sequence was reached before the code point was decoded. + +
class not_enough_room : public exception {};
+
+ +#### utf8::iterator + +Available in version 2.0 and later. + +Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets. + +
template <typename octet_iterator>
+class iterator;
+
+ +##### Member functions + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +Example of use: + +
char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
+utf8::iterator<char*> it(threechars, threechars, threechars + 9);
+utf8::iterator<char*> it2 = it;
+assert (it2 == it);
+assert (*it == 0x10346);
+assert (*(++it) == 0x65e5);
+assert ((*it++) == 0x65e5);
+assert (*it == 0x0448);
+assert (it != it2);
+utf8::iterator<char*> endit (threechars + 9, threechars, threechars + 9);  
+assert (++it == endit);
+assert (*(--it) == 0x0448);
+assert ((*it--) == 0x0448);
+assert (*it == 0x65e5);
+assert (--it == utf8::iterator<char*>(threechars, threechars, threechars + 9));
+assert (*it == 0x10346);
+
+ +The 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. + +Note 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.: + +
std::string s = "example";
+utf8::iterator i (s.begin(), s.begin(), s.end());
+
+ +### Functions From utf8::unchecked Namespace + +#### utf8::unchecked::append + +Available in version 1.0 and later. + +Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string. + +
template <typename octet_iterator>
+octet_iterator append(uint32_t cp, octet_iterator result);
+
+
+ +`cp`: A 32 bit integer representing a code point to append to the sequence. + `result`: An output iterator to the place in the sequence where to append the code point. + Return value: An iterator pointing to the place after the newly appended sequence. + +Example of use: + +
unsigned char u[5] = {0,0,0,0,0};
+unsigned char* end = unchecked::append(0x0448, u);
+assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0);
+
+ +This 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. + +#### utf8::unchecked::next + +Available in version 1.0 and later. + +Given the iterator to the beginning of a UTF-8 sequence, it returns the code point and moves the iterator to the next position. + +
template <typename octet_iterator>
+uint32_t next(octet_iterator& it);
+
+
+ +`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. + Return value: the 32 bit representation of the processed UTF-8 code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+int cp = unchecked::next(w);
+assert (cp == 0x65e5);
+assert (w == twochars + 3);
+
+ +This is a faster but less safe version of `utf8::next`. It does not check for validity of the supplied UTF-8 sequence. + +#### utf8::unchecked::peek_next + +Available in version 2.1 and later. + +Given the iterator to the beginning of a UTF-8 sequence, it returns the code point. + +
template <typename octet_iterator>
+uint32_t peek_next(octet_iterator it);
+
+
+ +`it`: an iterator pointing to the beginning of an UTF-8 encoded code point. + Return value: the 32 bit representation of the processed UTF-8 code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+int cp = unchecked::peek_next(w);
+assert (cp == 0x65e5);
+assert (w == twochars);
+
+ +This is a faster but less safe version of `utf8::peek_next`. It does not check for validity of the supplied UTF-8 sequence. + +#### utf8::unchecked::prior + +Available in version 1.02 and later. + +Given 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. + +
template <typename octet_iterator>
+uint32_t prior(octet_iterator& it);
+
+
+ +`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. + Return value: the 32 bit representation of the previous code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars + 3;
+int cp = unchecked::prior (w);
+assert (cp == 0x65e5);
+assert (w == twochars);
+
+ +This 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. + +#### utf8::unchecked::previous (deprecated, see utf8::unchecked::prior) + +Deprecated in version 1.02 and later. + +Given 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. + +
template <typename octet_iterator>
+uint32_t previous(octet_iterator& it);
+
+
+ +`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. + Return value: the 32 bit representation of the previous code point. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars + 3;
+int cp = unchecked::previous (w);
+assert (cp == 0x65e5);
+assert (w == twochars);
+
+ +The 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` + +This 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. + +#### utf8::unchecked::advance + +Available in version 1.0 and later. + +Advances an iterator by the specified number of code points within an UTF-8 sequence. + +
template <typename octet_iterator, typename distance_type>
+void advance (octet_iterator& it, distance_type n);
+
+
+ +`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. + `n`: a positive integer that shows how many code points we want to advance. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+unchecked::advance (w, 2);
+assert (w == twochars + 5);
+
+ +This function works only "forward". In case of a negative `n`, there is no effect. + +This 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. + +#### utf8::unchecked::distance + +Available in version 1.0 and later. + +Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them. + +
template <typename octet_iterator>
+typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last);
+
+ +`first`: an iterator to a beginning of a UTF-8 encoded code point. + `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. + Return value the distance between the iterators, in code points. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+size_t dist = utf8::unchecked::distance(twochars, twochars + 5);
+assert (dist == 2);
+
+ +This is a faster but less safe version of `utf8::distance`. It does not check for validity of the supplied UTF-8 sequence. + +#### utf8::unchecked::utf16to8 + +Available in version 1.0 and later. + +Converts a UTF-16 encoded string to UTF-8. + +
template <typename u16bit_iterator, typename octet_iterator>
+octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);
+
+
+ +`start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert. + `end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert. + `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-8 string. + +Example of use: + +
unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
+vector<unsigned char> utf8result;
+unchecked::utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
+assert (utf8result.size() == 10);    
+
+ +This is a faster but less safe version of `utf8::utf16to8`. It does not check for validity of the supplied UTF-16 sequence. + +#### utf8::unchecked::utf8to16 + +Available in version 1.0 and later. + +Converts an UTF-8 encoded string to UTF-16 + +
template <typename u16bit_iterator, typename octet_iterator>
+u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result);
+
+
+ +`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. + `result`: an output iterator to the place in the UTF-16 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-16 string. + +Example of use: + +
char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e";
+vector <unsigned short> utf16result;
+unchecked::utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result));
+assert (utf16result.size() == 4);
+assert (utf16result[2] == 0xd834);
+assert (utf16result[3] == 0xdd1e);
+
+ +This is a faster but less safe version of `utf8::utf8to16`. It does not check for validity of the supplied UTF-8 sequence. + +#### utf8::unchecked::utf32to8 + +Available in version 1.0 and later. + +Converts a UTF-32 encoded string to UTF-8. + +
template <typename octet_iterator, typename u32bit_iterator>
+octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result);
+
+
+ +`start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert. + `end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert. + `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-8 string. + +Example of use: + +
int utf32string[] = {0x448, 0x65e5, 0x10346, 0};
+vector<unsigned char> utf8result;
+utf32to8(utf32string, utf32string + 3, back_inserter(utf8result));
+assert (utf8result.size() == 9);
+
+ +This is a faster but less safe version of `utf8::utf32to8`. It does not check for validity of the supplied UTF-32 sequence. + +#### utf8::unchecked::utf8to32 + +Available in version 1.0 and later. + +Converts a UTF-8 encoded string to UTF-32. + +
template <typename octet_iterator, typename u32bit_iterator>
+u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result);
+
+
+ +`start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. + `end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert. + `result`: an output iterator to the place in the UTF-32 string where to append the result of conversion. + Return value: An iterator pointing to the place after the appended UTF-32 string. + +Example of use: + +
char* twochars = "\xe6\x97\xa5\xd1\x88";
+vector<int> utf32result;
+unchecked::utf8to32(twochars, twochars + 5, back_inserter(utf32result));
+assert (utf32result.size() == 2);
+
+ +This is a faster but less safe version of `utf8::utf8to32`. It does not check for validity of the supplied UTF-8 sequence. + +### Types From utf8::unchecked Namespace + +#### utf8::iterator + +Available in version 2.0 and later. + +Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets. + +
template <typename octet_iterator>
+class iterator;
+
+ +##### Member functions + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +Example of use: + +
char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
+utf8::unchecked::iterator<char*> un_it(threechars);
+utf8::unchecked::iterator<char*> un_it2 = un_it;
+assert (un_it2 == un_it);
+assert (*un_it == 0x10346);
+assert (*(++un_it) == 0x65e5);
+assert ((*un_it++) == 0x65e5);
+assert (*un_it == 0x0448);
+assert (un_it != un_it2);
+utf8::::unchecked::iterator<char*> un_endit (threechars + 9);  
+assert (++un_it == un_endit);
+assert (*(--un_it) == 0x0448);
+assert ((*un_it--) == 0x0448);
+assert (*un_it == 0x65e5);
+assert (--un_it == utf8::unchecked::iterator<char*>(threechars));
+assert (*un_it == 0x10346);
+
+ +This is an unchecked version of `utf8::iterator`. It is faster in many cases, but offers no validity or range checks. + +## Points of interest + +#### Design goals and decisions + +The library was designed to be: + +1. 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. +2. 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. +3. Lightweight: follow the "pay only for what you use" guideline. +4. Unintrusive: avoid forcing any particular design or even programming style on the user. This is a library, not a framework. + +#### Alternatives + +In 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: + +1. [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. +2. C++11 language and library features. Still far from complete, and not widely supported by compiler vendors. +3. [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. +4. 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. + +## Links + +1. [The Unicode Consortium](http://www.unicode.org/). +2. [ICU Library](http://icu.sourceforge.net/). +3. [UTF-8 at Wikipedia](http://en.wikipedia.org/wiki/UTF-8) +4. [UTF-8 and Unicode FAQ for Unix/Linux](http://www.cl.cam.ac.uk/~mgk25/unicode.html) \ No newline at end of file diff --git a/buildrelease.pl b/buildrelease.pl new file mode 100644 index 000000000..ed3a17bbe --- /dev/null +++ b/buildrelease.pl @@ -0,0 +1,18 @@ +#! /usr/bin/perl + +$release_files = 'source/utf8.h source/utf8/core.h source/utf8/checked.h source/utf8/unchecked.h doc/utf8cpp.html doc/ReleaseNotes'; + +# First get the latest version +`svn update`; + +# Then construct the name of the zip file +$argc = @ARGV; +if ($argc > 0) { + $zip_name = $ARGV[0]; +} +else { + $zip_name = "utf8"; +} + +# Zip the files to an archive +`zip $zip_name $release_files`; diff --git a/samples/Makefile b/samples/Makefile new file mode 100644 index 000000000..6cdd3c859 --- /dev/null +++ b/samples/Makefile @@ -0,0 +1,5 @@ +CC = g++ +CFLAGS = -g -Wall -pedantic + +docsample: docsample.cpp ../source/utf8.h + $(CC) $(CFLAGS) docsample.cpp -odocsample diff --git a/samples/docsample.cpp b/samples/docsample.cpp new file mode 100644 index 000000000..6f8953b99 --- /dev/null +++ b/samples/docsample.cpp @@ -0,0 +1,52 @@ +#include "../source/utf8.h" +#include +#include +#include +#include + + +using namespace std; + +int main(int argc, char** argv) +{ + if (argc != 2) { + cout << "\nUsage: docsample filename\n"; + return 0; + } + const char* test_file_path = argv[1]; + // Open the test file (must be UTF-8 encoded) + ifstream fs8(test_file_path); + if (!fs8.is_open()) { + cout << "Could not open " << test_file_path << endl; + return 0; + } + + unsigned line_count = 1; + string line; + // Play with all the lines in the file + while (getline(fs8, line)) { + // check for invalid utf-8 (for a simple yes/no check, there is also utf8::is_valid function) + string::iterator end_it = utf8::find_invalid(line.begin(), line.end()); + if (end_it != line.end()) { + cout << "Invalid UTF-8 encoding detected at line " << line_count << "\n"; + cout << "This part is fine: " << string(line.begin(), end_it) << "\n"; + } + // Get the line length (at least for the valid part) + int length = utf8::distance(line.begin(), end_it); + cout << "Length of line " << line_count << " is " << length << "\n"; + + // Convert it to utf-16 + vector utf16line; + utf8::utf8to16(line.begin(), end_it, back_inserter(utf16line)); + // And back to utf-8; + string utf8line; + utf8::utf16to8(utf16line.begin(), utf16line.end(), back_inserter(utf8line)); + // Confirm that the conversion went OK: + if (utf8line != string(line.begin(), end_it)) + cout << "Error in UTF-16 conversion at line: " << line_count << "\n"; + + line_count++; + } + + return 0; +} diff --git a/source/utf8.h b/source/utf8.h new file mode 100644 index 000000000..82b13f59f --- /dev/null +++ b/source/utf8.h @@ -0,0 +1,34 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include "utf8/checked.h" +#include "utf8/unchecked.h" + +#endif // header guard diff --git a/source/utf8/checked.h b/source/utf8/checked.h new file mode 100644 index 000000000..cc1ec4777 --- /dev/null +++ b/source/utf8/checked.h @@ -0,0 +1,327 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include "core.h" +#include + +namespace utf8 +{ + // Base for the exceptions that may be thrown from the library + class exception : public ::std::exception { + }; + + // Exceptions that may be thrown from the library functions. + class invalid_code_point : public exception { + uint32_t cp; + public: + invalid_code_point(uint32_t cp) : cp(cp) {} + virtual const char* what() const throw() { return "Invalid code point"; } + uint32_t code_point() const {return cp;} + }; + + class invalid_utf8 : public exception { + uint8_t u8; + public: + invalid_utf8 (uint8_t u) : u8(u) {} + virtual const char* what() const throw() { return "Invalid UTF-8"; } + uint8_t utf8_octet() const {return u8;} + }; + + class invalid_utf16 : public exception { + uint16_t u16; + public: + invalid_utf16 (uint16_t u) : u16(u) {} + virtual const char* what() const throw() { return "Invalid UTF-16"; } + uint16_t utf16_word() const {return u16;} + }; + + class not_enough_room : public exception { + public: + virtual const char* what() const throw() { return "Not enough space"; } + }; + + /// The library API - functions intended to be called by the users + + template + octet_iterator append(uint32_t cp, octet_iterator result) + { + if (!utf8::internal::is_code_point_valid(cp)) + throw invalid_code_point(cp); + + if (cp < 0x80) // one octet + *(result++) = static_cast(cp); + else if (cp < 0x800) { // two octets + *(result++) = static_cast((cp >> 6) | 0xc0); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { // three octets + *(result++) = static_cast((cp >> 12) | 0xe0); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else { // four octets + *(result++) = static_cast((cp >> 18) | 0xf0); + *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + return result; + } + + template + output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) + { + while (start != end) { + octet_iterator sequence_start = start; + internal::utf_error err_code = utf8::internal::validate_next(start, end); + switch (err_code) { + case internal::UTF8_OK : + for (octet_iterator it = sequence_start; it != start; ++it) + *out++ = *it; + break; + case internal::NOT_ENOUGH_ROOM: + throw not_enough_room(); + case internal::INVALID_LEAD: + out = utf8::append (replacement, out); + ++start; + break; + case internal::INCOMPLETE_SEQUENCE: + case internal::OVERLONG_SEQUENCE: + case internal::INVALID_CODE_POINT: + out = utf8::append (replacement, out); + ++start; + // just one replacement mark for the sequence + while (start != end && utf8::internal::is_trail(*start)) + ++start; + break; + } + } + return out; + } + + template + inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) + { + static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd); + return utf8::replace_invalid(start, end, out, replacement_marker); + } + + template + uint32_t next(octet_iterator& it, octet_iterator end) + { + uint32_t cp = 0; + internal::utf_error err_code = utf8::internal::validate_next(it, end, cp); + switch (err_code) { + case internal::UTF8_OK : + break; + case internal::NOT_ENOUGH_ROOM : + throw not_enough_room(); + case internal::INVALID_LEAD : + case internal::INCOMPLETE_SEQUENCE : + case internal::OVERLONG_SEQUENCE : + throw invalid_utf8(*it); + case internal::INVALID_CODE_POINT : + throw invalid_code_point(cp); + } + return cp; + } + + template + uint32_t peek_next(octet_iterator it, octet_iterator end) + { + return utf8::next(it, end); + } + + template + uint32_t prior(octet_iterator& it, octet_iterator start) + { + // can't do much if it == start + if (it == start) + throw not_enough_room(); + + octet_iterator end = it; + // Go back until we hit either a lead octet or start + while (utf8::internal::is_trail(*(--it))) + if (it == start) + throw invalid_utf8(*it); // error - no lead byte in the sequence + return utf8::peek_next(it, end); + } + + /// Deprecated in versions that include "prior" + template + uint32_t previous(octet_iterator& it, octet_iterator pass_start) + { + octet_iterator end = it; + while (utf8::internal::is_trail(*(--it))) + if (it == pass_start) + throw invalid_utf8(*it); // error - no lead byte in the sequence + octet_iterator temp = it; + return utf8::next(temp, end); + } + + template + void advance (octet_iterator& it, distance_type n, octet_iterator end) + { + for (distance_type i = 0; i < n; ++i) + utf8::next(it, end); + } + + template + typename std::iterator_traits::difference_type + distance (octet_iterator first, octet_iterator last) + { + typename std::iterator_traits::difference_type dist; + for (dist = 0; first < last; ++dist) + utf8::next(first, last); + return dist; + } + + template + octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) + { + while (start != end) { + uint32_t cp = utf8::internal::mask16(*start++); + // Take care of surrogate pairs first + if (utf8::internal::is_lead_surrogate(cp)) { + if (start != end) { + uint32_t trail_surrogate = utf8::internal::mask16(*start++); + if (utf8::internal::is_trail_surrogate(trail_surrogate)) + cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; + else + throw invalid_utf16(static_cast(trail_surrogate)); + } + else + throw invalid_utf16(static_cast(cp)); + + } + // Lone trail surrogate + else if (utf8::internal::is_trail_surrogate(cp)) + throw invalid_utf16(static_cast(cp)); + + result = utf8::append(cp, result); + } + return result; + } + + template + u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) + { + while (start < end) { + uint32_t cp = utf8::next(start, end); + if (cp > 0xffff) { //make a surrogate pair + *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); + *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); + } + else + *result++ = static_cast(cp); + } + return result; + } + + template + octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) + { + while (start != end) + result = utf8::append(*(start++), result); + + return result; + } + + template + u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) + { + while (start < end) + (*result++) = utf8::next(start, end); + + return result; + } + + // The iterator class + template + class iterator : public std::iterator { + octet_iterator it; + octet_iterator range_start; + octet_iterator range_end; + public: + iterator () {} + explicit iterator (const octet_iterator& octet_it, + const octet_iterator& range_start, + const octet_iterator& range_end) : + it(octet_it), range_start(range_start), range_end(range_end) + { + if (it < range_start || it > range_end) + throw std::out_of_range("Invalid utf-8 iterator position"); + } + // the default "big three" are OK + octet_iterator base () const { return it; } + uint32_t operator * () const + { + octet_iterator temp = it; + return utf8::next(temp, range_end); + } + bool operator == (const iterator& rhs) const + { + if (range_start != rhs.range_start || range_end != rhs.range_end) + throw std::logic_error("Comparing utf-8 iterators defined with different ranges"); + return (it == rhs.it); + } + bool operator != (const iterator& rhs) const + { + return !(operator == (rhs)); + } + iterator& operator ++ () + { + utf8::next(it, range_end); + return *this; + } + iterator operator ++ (int) + { + iterator temp = *this; + utf8::next(it, range_end); + return temp; + } + iterator& operator -- () + { + utf8::prior(it, range_start); + return *this; + } + iterator operator -- (int) + { + iterator temp = *this; + utf8::prior(it, range_start); + return temp; + } + }; // class iterator + +} // namespace utf8 + +#endif //header guard + + diff --git a/source/utf8/core.h b/source/utf8/core.h new file mode 100644 index 000000000..693d388c0 --- /dev/null +++ b/source/utf8/core.h @@ -0,0 +1,329 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include + +namespace utf8 +{ + // The typedefs for 8-bit, 16-bit and 32-bit unsigned integers + // You may need to change them to match your system. + // These typedefs have the same names as ones from cstdint, or boost/cstdint + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + +// Helper code - not intended to be directly called by the library users. May be changed at any time +namespace internal +{ + // Unicode constants + // Leading (high) surrogates: 0xd800 - 0xdbff + // Trailing (low) surrogates: 0xdc00 - 0xdfff + const uint16_t LEAD_SURROGATE_MIN = 0xd800u; + const uint16_t LEAD_SURROGATE_MAX = 0xdbffu; + const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u; + const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu; + const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10); + const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN; + + // Maximum valid value for a Unicode code point + const uint32_t CODE_POINT_MAX = 0x0010ffffu; + + template + inline uint8_t mask8(octet_type oc) + { + return static_cast(0xff & oc); + } + template + inline uint16_t mask16(u16_type oc) + { + return static_cast(0xffff & oc); + } + template + inline bool is_trail(octet_type oc) + { + return ((utf8::internal::mask8(oc) >> 6) == 0x2); + } + + template + inline bool is_lead_surrogate(u16 cp) + { + return (cp >= LEAD_SURROGATE_MIN && cp <= LEAD_SURROGATE_MAX); + } + + template + inline bool is_trail_surrogate(u16 cp) + { + return (cp >= TRAIL_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); + } + + template + inline bool is_surrogate(u16 cp) + { + return (cp >= LEAD_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); + } + + template + inline bool is_code_point_valid(u32 cp) + { + return (cp <= CODE_POINT_MAX && !utf8::internal::is_surrogate(cp)); + } + + template + inline typename std::iterator_traits::difference_type + sequence_length(octet_iterator lead_it) + { + uint8_t lead = utf8::internal::mask8(*lead_it); + if (lead < 0x80) + return 1; + else if ((lead >> 5) == 0x6) + return 2; + else if ((lead >> 4) == 0xe) + return 3; + else if ((lead >> 3) == 0x1e) + return 4; + else + return 0; + } + + template + inline bool is_overlong_sequence(uint32_t cp, octet_difference_type length) + { + if (cp < 0x80) { + if (length != 1) + return true; + } + else if (cp < 0x800) { + if (length != 2) + return true; + } + else if (cp < 0x10000) { + if (length != 3) + return true; + } + + return false; + } + + enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT}; + + /// Helper for get_sequence_x + template + utf_error increase_safely(octet_iterator& it, octet_iterator end) + { + if (++it == end) + return NOT_ENOUGH_ROOM; + + if (!utf8::internal::is_trail(*it)) + return INCOMPLETE_SEQUENCE; + + return UTF8_OK; + } + + #define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;} + + /// get_sequence_x functions decode utf-8 sequences of the length x + template + utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t& code_point) + { + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); + + return UTF8_OK; + } + + template + utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t& code_point) + { + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point = ((code_point << 6) & 0x7ff) + ((*it) & 0x3f); + + return UTF8_OK; + } + + template + utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t& code_point) + { + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point = ((code_point << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point += (*it) & 0x3f; + + return UTF8_OK; + } + + template + utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t& code_point) + { + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point = ((code_point << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point += (utf8::internal::mask8(*it) << 6) & 0xfff; + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point += (*it) & 0x3f; + + return UTF8_OK; + } + + #undef UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR + + template + utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point) + { + // Save the original value of it so we can go back in case of failure + // Of course, it does not make much sense with i.e. stream iterators + octet_iterator original_it = it; + + uint32_t cp = 0; + // Determine the sequence length based on the lead octet + typedef typename std::iterator_traits::difference_type octet_difference_type; + const octet_difference_type length = utf8::internal::sequence_length(it); + + // Get trail octets and calculate the code point + utf_error err = UTF8_OK; + switch (length) { + case 0: + return INVALID_LEAD; + case 1: + err = utf8::internal::get_sequence_1(it, end, cp); + break; + case 2: + err = utf8::internal::get_sequence_2(it, end, cp); + break; + case 3: + err = utf8::internal::get_sequence_3(it, end, cp); + break; + case 4: + err = utf8::internal::get_sequence_4(it, end, cp); + break; + } + + if (err == UTF8_OK) { + // Decoding succeeded. Now, security checks... + if (utf8::internal::is_code_point_valid(cp)) { + if (!utf8::internal::is_overlong_sequence(cp, length)){ + // Passed! Return here. + code_point = cp; + ++it; + return UTF8_OK; + } + else + err = OVERLONG_SEQUENCE; + } + else + err = INVALID_CODE_POINT; + } + + // Failure branch - restore the original value of the iterator + it = original_it; + return err; + } + + template + inline utf_error validate_next(octet_iterator& it, octet_iterator end) { + uint32_t ignored; + return utf8::internal::validate_next(it, end, ignored); + } + +} // namespace internal + + /// The library API - functions intended to be called by the users + + // Byte order mark + const uint8_t bom[] = {0xef, 0xbb, 0xbf}; + + template + octet_iterator find_invalid(octet_iterator start, octet_iterator end) + { + octet_iterator result = start; + while (result != end) { + utf8::internal::utf_error err_code = utf8::internal::validate_next(result, end); + if (err_code != internal::UTF8_OK) + return result; + } + return result; + } + + template + inline bool is_valid(octet_iterator start, octet_iterator end) + { + return (utf8::find_invalid(start, end) == end); + } + + template + inline bool starts_with_bom (octet_iterator it, octet_iterator end) + { + return ( + ((it != end) && (utf8::internal::mask8(*it++)) == bom[0]) && + ((it != end) && (utf8::internal::mask8(*it++)) == bom[1]) && + ((it != end) && (utf8::internal::mask8(*it)) == bom[2]) + ); + } + + //Deprecated in release 2.3 + template + inline bool is_bom (octet_iterator it) + { + return ( + (utf8::internal::mask8(*it++)) == bom[0] && + (utf8::internal::mask8(*it++)) == bom[1] && + (utf8::internal::mask8(*it)) == bom[2] + ); + } +} // namespace utf8 + +#endif // header guard + + diff --git a/source/utf8/unchecked.h b/source/utf8/unchecked.h new file mode 100644 index 000000000..cb2427166 --- /dev/null +++ b/source/utf8/unchecked.h @@ -0,0 +1,228 @@ +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +#include "core.h" + +namespace utf8 +{ + namespace unchecked + { + template + octet_iterator append(uint32_t cp, octet_iterator result) + { + if (cp < 0x80) // one octet + *(result++) = static_cast(cp); + else if (cp < 0x800) { // two octets + *(result++) = static_cast((cp >> 6) | 0xc0); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { // three octets + *(result++) = static_cast((cp >> 12) | 0xe0); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else { // four octets + *(result++) = static_cast((cp >> 18) | 0xf0); + *(result++) = static_cast(((cp >> 12) & 0x3f)| 0x80); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + return result; + } + + template + uint32_t next(octet_iterator& it) + { + uint32_t cp = utf8::internal::mask8(*it); + typename std::iterator_traits::difference_type length = utf8::internal::sequence_length(it); + switch (length) { + case 1: + break; + case 2: + it++; + cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); + break; + case 3: + ++it; + cp = ((cp << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff); + ++it; + cp += (*it) & 0x3f; + break; + case 4: + ++it; + cp = ((cp << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff); + ++it; + cp += (utf8::internal::mask8(*it) << 6) & 0xfff; + ++it; + cp += (*it) & 0x3f; + break; + } + ++it; + return cp; + } + + template + uint32_t peek_next(octet_iterator it) + { + return utf8::unchecked::next(it); + } + + template + uint32_t prior(octet_iterator& it) + { + while (utf8::internal::is_trail(*(--it))) ; + octet_iterator temp = it; + return utf8::unchecked::next(temp); + } + + // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) + template + inline uint32_t previous(octet_iterator& it) + { + return utf8::unchecked::prior(it); + } + + template + void advance (octet_iterator& it, distance_type n) + { + for (distance_type i = 0; i < n; ++i) + utf8::unchecked::next(it); + } + + template + typename std::iterator_traits::difference_type + distance (octet_iterator first, octet_iterator last) + { + typename std::iterator_traits::difference_type dist; + for (dist = 0; first < last; ++dist) + utf8::unchecked::next(first); + return dist; + } + + template + octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) + { + while (start != end) { + uint32_t cp = utf8::internal::mask16(*start++); + // Take care of surrogate pairs first + if (utf8::internal::is_lead_surrogate(cp)) { + uint32_t trail_surrogate = utf8::internal::mask16(*start++); + cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; + } + result = utf8::unchecked::append(cp, result); + } + return result; + } + + template + u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) + { + while (start < end) { + uint32_t cp = utf8::unchecked::next(start); + if (cp > 0xffff) { //make a surrogate pair + *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); + *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); + } + else + *result++ = static_cast(cp); + } + return result; + } + + template + octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) + { + while (start != end) + result = utf8::unchecked::append(*(start++), result); + + return result; + } + + template + u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) + { + while (start < end) + (*result++) = utf8::unchecked::next(start); + + return result; + } + + // The iterator class + template + class iterator : public std::iterator { + octet_iterator it; + public: + iterator () {} + explicit iterator (const octet_iterator& octet_it): it(octet_it) {} + // the default "big three" are OK + octet_iterator base () const { return it; } + uint32_t operator * () const + { + octet_iterator temp = it; + return utf8::unchecked::next(temp); + } + bool operator == (const iterator& rhs) const + { + return (it == rhs.it); + } + bool operator != (const iterator& rhs) const + { + return !(operator == (rhs)); + } + iterator& operator ++ () + { + ::std::advance(it, utf8::internal::sequence_length(it)); + return *this; + } + iterator operator ++ (int) + { + iterator temp = *this; + ::std::advance(it, utf8::internal::sequence_length(it)); + return temp; + } + iterator& operator -- () + { + utf8::unchecked::prior(it); + return *this; + } + iterator operator -- (int) + { + iterator temp = *this; + utf8::unchecked::prior(it); + return temp; + } + }; // class iterator + + } // namespace utf8::unchecked +} // namespace utf8 + + +#endif // header guard + diff --git a/test_data/negative/utf8_invalid.txt b/test_data/negative/utf8_invalid.txt new file mode 100644 index 0000000000000000000000000000000000000000..ae83159328313d3ba57b4f51ccb96db3dbfd79f1 GIT binary patch literal 20010 zcmdU1X_MU6bovBN~mKh6fF_0QAgsswpbL0B%%C@w9FK+vZcy8Zq1!0g4#f{pMW{IDslKE-otkk?5=P@_gAEfdHgKi|B z)6KH}<@4tc4-cDO*!0|9)AgEz{qtYa+uL8iaQ^dTMb=kWH&#~HSJo~$&h>6!#*Dho@!}-$y=+-} zZrF*Fp5I=UIFUH(`pIFC`VvH$4^Fcn+B29=>OVE`BhOEpq9iFbAT5eB>G^JyNft}X z7Z>0WFvZeHX99kq@03yXYq|L;(&dH9ts7p$uh^(gsw*RC$vY zY4j=~Y%hh*Ls*{|AHZ86gsAN%L)t()AWLb*#wIOE+*A(zFyznNBEzA8Rd`-IH)U&f zl+BGO;P3Eo+jsggj1)FaA*9fC*p>*2haGtyviXSFv1s@(Ed6 zy|{UCW$iNDZgp8wql;8_np>*S_2!1R46wF;5O}@=$MJ&$>lhf@1q;MT1j1~2xe?_7i8soFiY{eZsL0IJi`?X4n~y*;FwnIw&Q*V!K8y$>Sqno<}~ap zxg=aT3*GE6pk2;*FQ*rt3UdfN7l;l#mjeu74-IJ{(n-mr;kqdg$y0+MqwIUVID($= zG|Z_F+i|@vz?=zlqf5pBQa1vz!!p=R=vIe>T=mJGk5FQ{lBF9D?(XjHoLiQ|Zh&#Z zINqnIT992B>@!+mY^a@lK-LIZ@S`3Au0}Lh(x4YGx}?KiD-Jal^@6=_W@6P|9Jd7m zcInaw0X+|_wF8ZOgCOl6AX-Hh}9Dt0Fw9I6j?$C z5B8!sq4kz*6%4`L5@!&Vq**nj3a^Cc(Ve=r!$Ua%e4yv<`%c?$AbGI*hz-5=X%o z8|Vz8O-)9Upx1NveCQaw6r)v~%Vz3oqE6jmDvj%pT$QVj?=;{s%0$RSz$lKW7fYa7 z3Yw-Fr9Mr_h1xW86_brufYKN> z;4w#@-$#xF6?{KCM6^Ska10Ua&9&y5s&>7J`+^nFo4Ft`ildc2{3TOgedx)DuU#WA zSrUh-bK^l|j8%P^w_CfQC>NqpECww2Q+izRdgQlP4udwRqpL3?6To&!X_aRyNh2#6 z^rX*u#$Yt>g1N#?ePjUypS+y3i4X6kg`2faZaK;KU>}di8oiL! zQ5GOvxFH-Wf*Tw_cP3FGfYRSU-}Hc*mr$K0Fly#kV1zJkSKwG3q;@)uM}ts>F43pK znHGF$kPXz`Qmr5>RpL235Ds)ukYMADkZHW$Mm^AG(bgJ*c92zxS=Jqk#5yC(S+g-w z#aIod8u0PGA@H554=&S+Bg6s?mKx6Ks<{cNg+PkVBP^S>o>rrWF{GE})Yr&4^{X>q z964(uPqNA`Y|eysR_ZffxW|`^r|*j}zskMP#6n*_Kk@y2IYjX&5A4Tj&wrqhXye5X zeC&nyfAr}WKltMN8h0mk@l>vhT$!r5jq5Y#r+24i)^E;$KEzhpk36BL&U20S4A_Q zBIX>R_iNDO?^8R_%@e2}X0GgvKYi~{XJOtOG;b4RcOXFdT*2hzQb$@H+&1pKr?&8v zeC3!1ZV;~`-Vo83?N$B*;>YVpn+hVNXb_>`9U>}$tu_%~zWG93cc~!4!il)HN|OOh zXH&Kfs51WQyXu>bAnriXO<1@>YAP_0my~V8`Kxne1VY~19_D#s1sz-&Iak1}D&0RJ&LiOnofNn*|25_z`kt zh0AWmHJUNiV?7sOMK(T+n#FTHQyls)KlknU--~m9x*=l;`OniQyr|GV*xGAuxndg8yp|J#-}r(kMW+X%Ny%vLo`pj zu#+YH!-;o#PqjL;l==)vyJ^6k41NlSwBl%A*3;9d=EBR}AN$MA>i{}^iM+>BW*Dg-#cVmWred^bLQ|tG(d`$jE{#O1@ z{$Bn;{!#u({#pJ-{#E`>?#RdG<^Okmpx&T9wkOrGIYS*Cs-v?t+uh3i@fq!JugJg4 zf5?BztMXs+-|~q$Rsw%Dji*%r4Nt#XuqlT@w$9!0lJ`0&O#rERz;Cstl`FjfI~CY-KH*wC zeKZsnDcZTEO)c2G!zLd#6pON@Iz!i<1UoIyw^U1lXU)$|kAZIJ7f9UM(qU@j)0uHx1rmJ~9yQ0b-8TMMd{5G(Jh5B!z z(yQoME5JgvXe+90Pc&{#RyLf!X~jEHS=7Y4eLNcwCODBBYXZJ9z3ym8M980r?llo# zo3U|XAQ81D0#r@N*Jo|U7);F6Yiq`A!I?dU#!IsWiJ5wB%_tt%Nik)`a_ekBOx0^^ zh6}I6Q$TDb%tplIy0&IkR?7{A26qx>L&D2yYi6agpU}{aglSCcjtjY=reTf`qtgd# zhwRueJsJTTIwvAoT4%t;#|Xw)hAhajh^ZQG;p<$c$;oCn78)+9F%mD7ohAkCBiq`+ zUMD6DyI5LlPFUa+KNrt0kQ=vdA0v3s+toc^dif?SmL@jSCJI{W{#-oGx)E`$XZKT0 zPOMAMg+KZ2n_2nV}G!joR1Q@B8RBMcT8Cp+yH^rfrww6fT}V$d7rj<8yQA zjY*#$AN}5+=+hTC@9yZn(x(@LhcpQK_^*=#zwySWPldgB`5}Tmfi^d7IxK_4y(KmK ziN(`5Zhs|(MdNoFr_knB_PI0cp_pWED(W_Sjo5x@`|8)52#gsUh?90x9*Gax@TdJ| zXqrPi8HEA>yn@C^w85t-d;Qr$S6m}!((Fx7G(5r_6>-_4h?O+7(V^M3J>VIUuHR#S zc_VdU5~dHV#LK%B8$~!y{I{W=)R#;{vvz@(T$d8jhEMos^%|kK)=hCN;j(rP<6sKU zacHNyHZHTFJ!Drrau<=ot>$Wrtu61d-eN87CrI zzG;lr?odNO4hVh3lJ@nSjGoCzalixP<$ateuTe$MuusSmEr=yuC4JTQN!z$Mn=EbV z^zl1kbK6WPDEz!z*3Ji-vWsuW zu93qdH9RWB6Bc=iShUfz(G*bvf?axa_Z%AU^o$2&1BxI(ZQ_UdRRKrZ)r(|4-~pzb zDtL=7w&{y71wu&S^lG=au6bfaBYn_mr0Tnmn{qgt`r zqN6s1HE0f?bB$fV3;I48gD}kT0Zfku3D1}5ffjn_LEs-Q7t%xN1a0L<(D2Ji|0wO9 zr?5=7D_s`qn3TWz@LMQ{w{Wkg@WU$8^pCQc9xNIRlj4xn$WY=U3Q&?<(c9{v%{<1T zopb;*RfDcFjChc8L!4|C&C?Zzmf5XqG*k8dT#h*7rF>KXNuT<^^~>=i0We6Im^mtf zIW0~?Q4?xVEYSQTob13P)n1E_&zsD?S8*^8bN6B{Z;74Ih$Z8$H;bq53%T$C(Uh?^ zm$qr3hn}e8vcl=G@7gjjNod7h%9uicNlsI&wRB~valV0GYI9l(c4w3c-zqNpFAw!p z%I$FlFROx!paECb<4_qoxAm+d{h16F7xU4~Lmsx}noA%Mhmxm9*-Y`@j`g$)&IIz; z_Cn1+CAiPFzn%YP@%n}R!2-FwvChUI562TK`5qLaEWGu6?K*Dc5OBQ&^tC6biV48m z$MYg?l!%?8%gBNP5p$M#AvY_K+j+|tdY23;AUOw`7xO{|(9XU1<6)dtytL7|qe~z<}U$s32$R=i>DNdtrhy?T9?G#2A70_o*21 z;i)yKDeCZr8X!$D2h4jgSMwfB`wC-3y=F{9 z_BRqyArT|C$hi3jRK|#R%vgN0TvTohrspnSyn0(!qipS^{CX0Q;*gDV)62We$}1LK}1dW$W7G?26$^~H=_DL^As2yz}wTi5ml7xy+Ncq7l=09TTmb(-OouR-PuA`(!D_iB-8zzm~>~0IiBtT z3rtP-bAVPQasT%t2LxWrj}_}5Lcl7i`6~;j0$;p2j=S?j!YdrHmMfE?$^v_J&BPz( zf9S!6Gcl_!_B?tS&XC>9)hSK}3{AyEU8@dr98^!h_OSQMWd)q~%@?Q2*}3@}8EHk* z2oIc{o4+H1B@tVjOfX(Ib}U{WTnc{DZ0wRIG)`ffp2T}tpQtiY;pwE?GojCfuN@p{ zgM)FEMP~!>wL8z$b~H;gJjAqV-*|B6iq2-Ol8zj)jXQ;QB+WkTG76{TR+c*vAF17y5@tu1s zUU@e8zQDA~DKV{W0`uOAGMKr?zz4_ZR976M^VyrV>CAn`V3u@ROiL#)>(XhwhMqk} zr<(d0ozK;mr}3K{v!v5vS~`JQmrmn3j2B~cD%2RA&)1hHdL96lW0rJUOiL#)>(F`M VE;t6T_-vE^`IE6xPXA%#{2v5ASmOWy literal 0 HcmV?d00001 diff --git a/test_data/utf8samples/UTF-8-demo.txt b/test_data/utf8samples/UTF-8-demo.txt new file mode 100644 index 000000000..4363f27bd --- /dev/null +++ b/test_data/utf8samples/UTF-8-demo.txt @@ -0,0 +1,212 @@ + +UTF-8 encoded sample plain-text file +‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ + +Markus Kuhn [ˈmaʳkʊs kuːn] — 2002-07-25 + + +The ASCII compatible UTF-8 encoding used in this plain-text file +is defined in Unicode, ISO 10646-1, and RFC 2279. + + +Using Unicode/UTF-8, you can write in emails and source code things such as + +Mathematics and sciences: + + ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ⎧⎡⎛┌─────┐⎞⎤⎫ + ⎪⎢⎜│a²+b³ ⎟⎥⎪ + ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ⎪⎢⎜│───── ⎟⎥⎪ + ⎪⎢⎜⎷ c₈ ⎟⎥⎪ + ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⎨⎢⎜ ⎟⎥⎬ + ⎪⎢⎜ ∞ ⎟⎥⎪ + ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (⟦A⟧ ⇔ ⟪B⟫), ⎪⎢⎜ ⎲ ⎟⎥⎪ + ⎪⎢⎜ ⎳aⁱ-bⁱ⎟⎥⎪ + 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm ⎩⎣⎝i=1 ⎠⎦⎭ + +Linguistics and dictionaries: + + ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn + Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] + +APL: + + ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ + +Nicer typography in plain text files: + + ╔══════════════════════════════════════════╗ + ║ ║ + ║ • ‘single’ and “double” quotes ║ + ║ ║ + ║ • Curly apostrophes: “We’ve been here” ║ + ║ ║ + ║ • Latin-1 apostrophe and accents: '´` ║ + ║ ║ + ║ • ‚deutsche‘ „Anführungszeichen“ ║ + ║ ║ + ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ + ║ ║ + ║ • ASCII safety test: 1lI|, 0OD, 8B ║ + ║ ╭─────────╮ ║ + ║ • the euro symbol: │ 14.95 € │ ║ + ║ ╰─────────╯ ║ + ╚══════════════════════════════════════════╝ + +Combining characters: + + STARGΛ̊TE SG-1, a = v̇ = r̈, a⃑ ⊥ b⃑ + +Greek (in Polytonic): + + The Greek anthem: + + Σὲ γνωρίζω ἀπὸ τὴν κόψη + τοῦ σπαθιοῦ τὴν τρομερή, + σὲ γνωρίζω ἀπὸ τὴν ὄψη + ποὺ μὲ βία μετράει τὴ γῆ. + + ᾿Απ᾿ τὰ κόκκαλα βγαλμένη + τῶν ῾Ελλήνων τὰ ἱερά + καὶ σὰν πρῶτα ἀνδρειωμένη + χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! + + From a speech of Demosthenes in the 4th century BC: + + Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, + ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς + λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ + τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ + εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ + πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν + οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, + οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν + ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον + τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι + γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν + προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους + σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ + τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ + τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς + τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. + + Δημοσθένους, Γ´ ᾿Ολυνθιακὸς + +Georgian: + + From a Unicode conference invitation: + + გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო + კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, + ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს + ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, + ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება + ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, + ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. + +Russian: + + From a Unicode conference invitation: + + Зарегистрируйтесь сейчас на Десятую Международную Конференцию по + Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. + Конференция соберет широкий круг экспертов по вопросам глобального + Интернета и Unicode, локализации и интернационализации, воплощению и + применению Unicode в различных операционных системах и программных + приложениях, шрифтах, верстке и многоязычных компьютерных системах. + +Thai (UCS Level 2): + + Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese + classic 'San Gua'): + + [----------------------------|------------------------] + ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ + สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา + ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา + โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ + เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ + ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ + พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ + ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ + + (The above is a two-column text. If combining characters are handled + correctly, the lines of the second column should be aligned with the + | character above.) + +Ethiopian: + + Proverbs in the Amharic language: + + ሰማይ አይታረስ ንጉሥ አይከሰስ። + ብላ ካለኝ እንደአባቴ በቆመጠኝ። + ጌጥ ያለቤቱ ቁምጥና ነው። + ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው። + የአፍ ወለምታ በቅቤ አይታሽም። + አይጥ በበላ ዳዋ ተመታ። + ሲተረጉሙ ይደረግሙ። + ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል። + ድር ቢያብር አንበሳ ያስር። + ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም። + እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም። + የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ። + ሥራ ከመፍታት ልጄን ላፋታት። + ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል። + የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ። + ተንጋሎ ቢተፉ ተመልሶ ባፉ። + ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው። + እግርህን በፍራሽህ ልክ ዘርጋ። + +Runes: + + ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ + + (Old English, which transcribed into Latin reads 'He cwaeth that he + bude thaem lande northweardum with tha Westsae.' and means 'He said + that he lived in the northern land near the Western Sea.') + +Braille: + + ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌ + + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞ + ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎ + ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂ + ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙ + ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑ + ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲ + + ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹ + ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞ + ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕ + ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹ + ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎ + ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎ + ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳ + ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞ + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + (The first couple of paragraphs of "A Christmas Carol" by Dickens) + +Compact font selection example text: + + ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789 + abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ + –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд + ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა + +Greetings in various languages: + + Hello world, Καλημέρα κόσμε, コンニチハ + +Box drawing alignment tests: █ + ▉ + ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳ + ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳ + ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳ + ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳ + ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎ + ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏ + ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ ▗▄▖▛▀▜ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█ + ▝▀▘▙▄▟ diff --git a/test_data/utf8samples/Unicode_transcriptions.html b/test_data/utf8samples/Unicode_transcriptions.html new file mode 100644 index 000000000..69b29ffa5 --- /dev/null +++ b/test_data/utf8samples/Unicode_transcriptions.html @@ -0,0 +1,167 @@ +? *Unicode Transcriptions* Notes <#Notes> + +Glyphs | Samples + | Charts + | UTF + | Forms + | +Home . + + +Name Text Image +Arabic (Arabic) يونِكود ? +Arabic (Persian) یونی‌کُد / ?/ +Armenian Յունիկօդ +Bengali য়ূনিকোড +Bopomofo ㄊㄨㄥ˅ ㄧˋ ㄇㄚ˅ +ㄨㄢˋ ㄍㄨㄛˊ ㄇㄚ˅ +Braille +Buhid +Canadian Aboriginal ᔫᗂᑰᑦ +Cherokee ᏳᏂᎪᏛ +Cypriot +Cyrillic (Russian) Юникод ? +Deseret (English) ??????? +Devanagari (Hindi) यूनिकोड ? +Ethiopic ዩኒኮድ +Georgian უნიკოდი ? +Gothic +Greek Γιούνικοντ +Gujarati યૂનિકોડ +Gurmukhi ਯੂਨਿਕੋਡ +Han (Chinese) 统一码 ? +統一碼 ? +万国码 ? +萬國碼 ? +Hangul 유니코드 +Hanunoo +Hebrew יוניקוד +Hebrew (pointed) יוּנִיקוׁד +Hebrew (Yiddish) יוניקאָד ? +Hiragana (Japanese) ゆにこおど +Katakana (Japanese) ユニコード ? +Kannada ಯೂನಿಕೋಡ್ +Khmer យូនីគោដ +Lao +Latin Unicode Unicode +Latin (IPA <#English_Pronunciation>) ˈjunɪˌkoːd ? +Latin (Am. Dict. <#American_Dictionary>) Ūnĭcōde̽ ? +Limbu +Linear B +Malayalam യൂനികോഡ് +Mongolian +Myanmar +Ogham ᚔᚒᚅᚔᚉᚑᚇ / / +Old Italic +Oriya ୟୂନିକୋଡ +Osmanya +Runic (Anglo-Saxon) ᛡᚢᚾᛁᚳᚩᛞ +Shavian +Sinhala යණනිකෞද් +Syriac ܝܘܢܝܩܘܕ +Tagbanwa +Tagalog +Tai Le +Tamil யூனிகோட் +Telugu యూనికోడ్ +Thaana +Thai ยูนืโคด +Tibetan (Dzongkha) ཨུ་ནི་ཀོཌྲ། +Ugaritic +Yi + + + Notes: + +There are different ways to transcribe the word “Unicode”, depending on +the language and script. In some cases there is only one language that +customarily uses a given script; in others there are many languages. The +goal here is at a minimum to collect at least one transcription for each +script in a language customarily written in that script, with more +languages if possible. If the transcription is the same for multiple +languages in a script, then a single representative language is used. + +Still missing are transcriptions for the items above in RED (in at least +one language). I would appreciate any other transcriptions, or +corrections for the ones listed here. Send to mark3@macchiato.com +, using the directions below: + + * *Supplying Missing Items* + o Most Latin-script languages will follow the spelling, and + change the pronunciation. For any that would not, it would + be good to have the alternate spelling. + o For non-Latin scripts the goal is to match the English + pronunciation — /*not*/ spelling. Above is the IPA <#IPA> + (in phonemic transcription) that should be matched as + closely as possible (without sounding affected in the target + language) + o Text would be best in either the UTF-8 text, or the code + points in hex HTML. E.g. either of the following: + + "Юникод" + + "Юникод" + + Note: for / supplementary characters/ + , + there should be one hex number per code point, not two + surrogates + : + # 𐀀 /*not*/ �&xDC00; + o If you have a good font, I'd also appreciate a GIF. It + should be *96 x 24* bits, with the text centered, in black + on white (plus grays if smoothed). + * *Other Comments* + o Because some browsers won't handle the text, both text and + GIF image are supplied. If you can’t read the text columns, + see Display Problems + . + o The Chinese versions (inc. Bopomofo) are translations, not + transcriptions, since "transcription in Chinese is pretty + lame" [J. Becker]. + o There are other "translations" of Unicode that may be in + use, such as the Vietnamese "Thống Nhất Mã". + o For sample pages in different languages on the Unicode site, + see What is Unicode? + + o Americans are not generally used to IPA, and find a variety + of different systems in their dictionaries. This one leaves + the base letters as they are, and uses diacritics for + pronunciation. + * *Etymology of /Unicode/* + o Coined by J. Becker. Not related to previous usages, such as: + + A telegraphic code in which one word or set of letters + represents a sentence or phrase; a telegram or message + in this. (late 19th century, OED) + o According to my references, the prefix "uni" is directly + from Latin while the word "code" is through French. + o The original Indo-European apparently would have been + *oino-kau-do ("one strike give"): *kau apparently being + related to such English words as: hew, haggle, hoe, hag, + hay, hack, caudad, caudal, caudate, caudex, coda, codex, + codicil, coward, incus, and Kovač (personal name: "smith"). + + I will leave the exact derivations to the exegetes, + but I like the association with "haggle" myself. + * *Contributions* + o This draws on contributions or comments from: + + Dixon Au + + Joe Becker + + Maurice Bauhahn + + Abel Cheung + + Peter Constable + + Michael Everson + + Christopher John Fynn + + Michael Kaplan + + George Kiraz + + Abdul Malik + + Siva Nataraja + + Roozbeh Pournader + + Jonathan Rosenne + + Jungshik Shin + +------------------------------------------------------------------------ + + +Terms of Use . Last updated: +MED - 04/20/2003 15:30:33. + + + + diff --git a/test_data/utf8samples/quickbrown.txt b/test_data/utf8samples/quickbrown.txt new file mode 100644 index 000000000..5db944343 --- /dev/null +++ b/test_data/utf8samples/quickbrown.txt @@ -0,0 +1,126 @@ +Sentences that contain all letters commonly used in a language +-------------------------------------------------------------- + +Markus Kuhn -- 2001-09-02 + +This file is UTF-8 encoded. + + +Danish (da) +--------- + + Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen + Wolther spillede på xylofon. + (= Quiz contestants were eating strawbery with cream while Wolther + the circus clown played on xylophone.) + +German (de) +----------- + + Falsches Üben von Xylophonmusik quält jeden größeren Zwerg + (= Wrongful practicing of xylophone music tortures every larger dwarf) + + Zwölf Boxkämpfer jagten Eva quer über den Sylter Deich + (= Twelve boxing fighters hunted Eva across the dike of Sylt) + + Heizölrückstoßabdämpfung + (= fuel oil recoil absorber) + (jqvwxy missing, but all non-ASCII letters in one word) + +English (en) +------------ + + The quick brown fox jumps over the lazy dog + +Spanish (es) +------------ + + El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y + frío, añoraba a su querido cachorro. + (Contains every letter and every accent, but not every combination + of vowel + acute.) + +French (fr) +----------- + + Portez ce vieux whisky au juge blond qui fume sur son île intérieure, à + côté de l'alcôve ovoïde, où les bûches se consument dans l'âtre, ce + qui lui permet de penser à la cænogenèse de l'être dont il est question + dans la cause ambiguë entendue à Moÿ, dans un capharnaüm qui, + pense-t-il, diminue çà et là la qualité de son œuvre. + + l'île exiguë + Où l'obèse jury mûr + Fête l'haï volapük, + Âne ex aéquo au whist, + Ôtez ce vœu déçu. + + Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en + canoë au delà des îles, près du mälström où brûlent les novæ. + +Irish Gaelic (ga) +----------------- + + D'fhuascail Íosa, Úrmhac na hÓighe Beannaithe, pór Éava agus Ádhaimh + +Hungarian (hu) +-------------- + + Árvíztűrő tükörfúrógép + (= flood-proof mirror-drilling machine, only all non-ASCII letters) + +Icelandic (is) +-------------- + + Kæmi ný öxi hér ykist þjófum nú bæði víl og ádrepa + + Sævör grét áðan því úlpan var ónýt + (some ASCII letters missing) + +Japanese (jp) +------------- + + Hiragana: (Iroha) + + いろはにほへとちりぬるを + わかよたれそつねならむ + うゐのおくやまけふこえて + あさきゆめみしゑひもせす + + Katakana: + + イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム + ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン + +Hebrew (iw) +----------- + + ? דג סקרן שט בים מאוכזב ולפתע מצא לו חברה איך הקליטה + +Polish (pl) +----------- + + Pchnąć w tę łódź jeża lub ośm skrzyń fig + (= To push a hedgehog or eight bins of figs in this boat) + +Russian (ru) +------------ + + В чащах юга жил бы цитрус? Да, но фальшивый экземпляр! + (= Would a citrus live in the bushes of south? Yes, but only a fake one!) + +Thai (th) +--------- + + [--------------------------|------------------------] + ๏ เป็นมนุษย์สุดประเสริฐเลิศคุณค่า กว่าบรรดาฝูงสัตว์เดรัจฉาน + จงฝ่าฟันพัฒนาวิชาการ อย่าล้างผลาญฤๅเข่นฆ่าบีฑาใคร + ไม่ถือโทษโกรธแช่งซัดฮึดฮัดด่า หัดอภัยเหมือนกีฬาอัชฌาสัย + ปฏิบัติประพฤติกฎกำหนดใจ พูดจาให้จ๊ะๆ จ๋าๆ น่าฟังเอย ฯ + + [The copyright for the Thai example is owned by The Computer + Association of Thailand under the Royal Patronage of His Majesty the + King.] + +Please let me know if you find others! Special thanks to the people +from all over the world who contributed these sentences. diff --git a/test_drivers/Makefile b/test_drivers/Makefile new file mode 100644 index 000000000..a2cbe4c2e --- /dev/null +++ b/test_drivers/Makefile @@ -0,0 +1,19 @@ +CC = g++ +CFLAGS = -g + +all: smoketest regressiontest negativetest utf8readertest + +smoketest: + cd smoke_test && $(MAKE) $@ + +regressiontest: + cd regression_tests && $(MAKE) $@ + +negativetest: + cd negative && $(MAKE) $@ + +utf8readertest: + cd utf8reader && $(MAKE) $@ + +clean: + rm smoke_test/smoketest regression_tests/regressiontest negative/negative utf8reader/utf8reader diff --git a/test_drivers/negative/Makefile b/test_drivers/negative/Makefile new file mode 100644 index 000000000..00f4a7d31 --- /dev/null +++ b/test_drivers/negative/Makefile @@ -0,0 +1,5 @@ +CC = g++ +CFLAGS = -g -Wall -pedantic + +negativetest: negative.cpp ../../source/utf8.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h + $(CC) $(CFLAGS) negative.cpp -onegative diff --git a/test_drivers/negative/negative.cpp b/test_drivers/negative/negative.cpp new file mode 100644 index 000000000..0f1015d0e --- /dev/null +++ b/test_drivers/negative/negative.cpp @@ -0,0 +1,53 @@ +#include "../../source/utf8.h" +using namespace utf8; + +#include +#include +#include +#include +using namespace std; + +const unsigned INVALID_LINES[] = { 75, 76, 83, 84, 85, 93, 102, 103, 105, 106, 107, 108, 109, 110, 114, 115, 116, 117, 124, 125, 130, 135, 140, 145, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 169, 175, 176, 177, 207, 208, 209, 210, 211, 220, 221, 222, 223, 224, 232, 233, 234, 235, 236, 247, 248, 249, 250, 251, 252, 253, 257, 258, 259, 260, 261, 262, 263, 264}; +const unsigned* INVALID_LINES_END = INVALID_LINES + sizeof(INVALID_LINES)/sizeof(unsigned); + +int main(int argc, char** argv) +{ + string test_file_path; + if (argc == 2) + test_file_path = argv[1]; + else { + cout << "Wrong number of arguments" << endl; + exit(0); + } + // Open the test file + ifstream fs8(test_file_path.c_str()); + if (!fs8.is_open()) { + cout << "Could not open " << test_file_path << endl; + return 0; + } + + // Read it line by line + unsigned int line_count = 0; + char byte; + while (!fs8.eof()) { + string line; + while ((byte = static_cast(fs8.get())) != '\n' && !fs8.eof()) + line.push_back(byte); + + line_count++; + bool expected_valid = (find(INVALID_LINES, INVALID_LINES_END, line_count) == INVALID_LINES_END); + // Print out lines that contain unexpected invalid UTF-8 + if (!is_valid(line.begin(), line.end())) { + if (expected_valid) + cout << "Unexpected invalid utf-8 at line " << line_count << '\n'; + + // try fixing it: + string fixed_line; + replace_invalid(line.begin(), line.end(), back_inserter(fixed_line)); + if (!is_valid(fixed_line.begin(), fixed_line.end())) + cout << "replace_invalid() resulted in an invalid utf-8 at line " << line_count << '\n'; + } + else if (!expected_valid) + cout << "Invalid utf-8 NOT detected at line " << line_count << '\n'; + } +} diff --git a/test_drivers/performance/Makefile b/test_drivers/performance/Makefile new file mode 100644 index 000000000..b38544506 --- /dev/null +++ b/test_drivers/performance/Makefile @@ -0,0 +1,5 @@ +CC = g++ +CFLAGS = -O3 + +iconvtest: iconvtest.cpp ../../source/utf8.h timer.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h + $(CC) $(CFLAGS) iconvtest.cpp -oiconvtest diff --git a/test_drivers/performance/iconvtest.cpp b/test_drivers/performance/iconvtest.cpp new file mode 100644 index 000000000..95e73e747 --- /dev/null +++ b/test_drivers/performance/iconvtest.cpp @@ -0,0 +1,132 @@ +#include +#include +#include "../../source/utf8.h" +#include "timer.h" +#include +#include +#include +using namespace std; + +using namespace utf8; + +int main(int argc, char** argv) +{ + if (argc != 2) { + cout << "\nUsage: iconvtest filename\n"; + return 0; + } + const char* test_file_path = argv[1]; + // Open the test file (UTF-8 encoded text) + ifstream fs8(test_file_path, ios::binary); + if (!fs8.is_open()) { + cout << "Could not open " << test_file_path << endl; + return 0; + } + // get length + fs8.seekg(0, ios::end); + int length = fs8.tellg(); + fs8.seekg(0, ios::beg); + + // allocate the buffer (no vector - we are benchmarking conversions, not STL + char* buf = new char[length]; + char* end_buf = buf + length; + // fill the data + fs8.read(buf, length); + fs8.close(); + // the UTF-16 result will not be larger than this (I hope :) ) + vector temputf16; + utf8::utf8to16(buf, end_buf, back_inserter(temputf16)); + int wlength = temputf16.size(); + unsigned short* utf16buf = new unsigned short[wlength]; + + cout << "UTF8 to UTF-16\n"; + { + memset (utf16buf, 0 , wlength * sizeof(unsigned short)); + // utf-8 cpp: + cout << "utf8::utf8to16: "; + timer t(cout); + utf8::utf8to16(buf, buf + length, utf16buf); + t.print_time(); + } + + { + memset (utf16buf, 0 , wlength * sizeof(unsigned short)); + // utf-8 cpp: + cout << "unchecked::utf8to16: "; + timer t(cout); + utf8::unchecked::utf8to16(buf, buf + length, utf16buf); + t.print_time(); + } + + // the UTF-16 result will not be larger than this (I hope :) ) + unsigned short* utf16iconvbuf = new unsigned short[wlength]; + { + memset (utf16iconvbuf, 0 , wlength * sizeof(unsigned short)); + // iconv + cout << "iconv: "; + + iconv_t cd = iconv_open("UTF-16LE", "UTF-8"); + if (cd == iconv_t(-1)) { + cout << "Error openning the iconv stream"; + return 0; + } + char* inbuf = buf; + size_t in_bytes_left = length; + char* outbuf = (char*)utf16iconvbuf; + size_t out_bytes_left = wlength * sizeof (unsigned short); + { + timer t(cout); + iconv(cd, &inbuf, &in_bytes_left, &outbuf, &out_bytes_left); + t.print_time(); + } + iconv_close(cd); + } + + // just check the correctness while we are here: + if (!equal(utf16buf, utf16buf + wlength, utf16iconvbuf)) + cout << "Different result!!!\n"; + + // the other way around + cout << "UTF16 to UTF-8\n"; + { + //iconv + memset(buf, 0, length); + cout<< "iconv: "; + + iconv_t cd = iconv_open("UTF-8", "UTF-16LE"); + if (cd == iconv_t(-1)) { + cout << "Error openning the iconv stream"; + return 0; + } + char* inbuf = (char*)utf16buf; + size_t in_bytes_left = wlength * sizeof(unsigned short); + char* outbuf =buf; + size_t out_bytes_left = length; + { + timer t(cout); + iconv(cd, &inbuf, &in_bytes_left, &outbuf, &out_bytes_left); + t.print_time(); + } + iconv_close(cd); + } + + { + memset (buf, 0 , length); + // utf-8 cpp: + cout << "unchecked::utf16to8: "; + timer t(cout); + utf8::unchecked::utf16to8(utf16buf, utf16buf + wlength, buf); + t.print_time(); + } + + { + memset (buf, 0 , length); + cout << "utf16to8: "; + timer t(cout); + utf8::utf16to8(utf16buf, utf16buf + wlength, buf); + t.print_time(); + } + + delete [] buf; + delete [] utf16buf; +} diff --git a/test_drivers/performance/timer.h b/test_drivers/performance/timer.h new file mode 100644 index 000000000..807752317 --- /dev/null +++ b/test_drivers/performance/timer.h @@ -0,0 +1,22 @@ +#include +#include +struct timer { + timer(std::ostream& report) : report(report) + {start = std::clock();} + + void print_time() + { + using namespace std; + clock_t now = clock(); + unsigned milliseconds = (now - start)*1000 / CLOCKS_PER_SEC; + report << "Spent " << milliseconds << "ms here\n"; + } + + std::clock_t start; + std::ostream& report; + +private: + // just to surpress a VC++ 8.0 warning + timer& operator = (const timer&); + timer(const timer&); +}; diff --git a/test_drivers/performance/win32.cpp b/test_drivers/performance/win32.cpp new file mode 100644 index 000000000..3ec861a26 --- /dev/null +++ b/test_drivers/performance/win32.cpp @@ -0,0 +1,110 @@ +#include +#include "../../source/utf8.h" +#include "timer.h" +#include +#include +#include +using namespace std; + +using namespace utf8; + +int main(int argc, char** argv) +{ + if (argc != 2) { + cout << "\nUsage: win32test filename\n"; + return 0; + } + const char* test_file_path = argv[1]; + // Open the test file (UTF-8 encoded text) + ifstream fs8(test_file_path, ios::binary); + if (!fs8.is_open()) { + cout << "Could not open " << test_file_path << endl; + return 0; + } + // get length + fs8.seekg(0, ios::end); + int length = fs8.tellg(); + fs8.seekg(0, ios::beg); + + // allocate the buffer (no vector - we are benchmarking conversions, not STL + char* buf = new char[length]; + // fill the data + fs8.read(buf, length); + fs8.close(); + cout << "UTF8 > UTF16\n"; + // the UTF-16 result will not be larger than this (I hope :) ) + vector temputf16; + utf8::utf8to16(buf, buf + length, back_inserter(temputf16)); + vector::size_type wlength = temputf16.size(); + wchar_t* utf16buf = new wchar_t[wlength]; + + { + memset (utf16buf, 0 , wlength * sizeof(wchar_t)); + // utf-8 cpp: + cout << "utf8::utf8to16: "; + timer t(cout); + utf8::utf8to16(buf, buf + length, utf16buf); + t.print_time(); + } + + { + memset (utf16buf, 0 , wlength * sizeof(wchar_t)); + // utf-8 cpp: + cout << "unchecked::utf8to16: "; + timer t(cout); + utf8::unchecked::utf8to16(buf, buf + length, utf16buf); + t.print_time(); + } + // the UTF-16 result will not be larger than this (I hope :) ) + wchar_t* utf16iconvbuf = new wchar_t[wlength]; + { + memset (utf16iconvbuf, 0 , wlength * sizeof(wchar_t)); + // win32 + cout << "win32: "; + + { + timer t(cout); + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, buf, length, utf16iconvbuf, int(wlength)); + t.print_time(); + } + + } + + // just check the correctness while we are here: + if (!equal(utf16buf, utf16buf + wlength, utf16iconvbuf)) + cout << "Different result!!!"; + + // the other way around + cout << "UTF16 to UTF-8\n"; + { + //win32 + memset(buf, 0, length); + cout<< "win32: "; + + { + timer t(cout); + WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, utf16buf, int(wlength), buf, length, NULL, NULL); + t.print_time(); + } + } + + { + memset (buf, 0 , length); + // utf-8 cpp: + cout << "unchecked::utf16to8: "; + timer t(cout); + utf8::unchecked::utf16to8(utf16buf, utf16buf + wlength, buf); + t.print_time(); + } + + { + memset (buf, 0 , length); + cout << "utf16to8: "; + timer t(cout); + utf8::utf16to8(utf16buf, utf16buf + wlength, buf); + t.print_time(); + } + + delete [] buf; + delete [] utf16buf; +} diff --git a/test_drivers/runtests.pl b/test_drivers/runtests.pl new file mode 100644 index 000000000..7d63f1843 --- /dev/null +++ b/test_drivers/runtests.pl @@ -0,0 +1,50 @@ +#! /usr/bin/perl + +$report_name = './report.txt'; + +# Create the report file +die if !open(REPORT, ">$report_name"); + +# First, build everything +print REPORT "==================Make output==================\n"; +close($report_name); + +`make >> $report_name`; +die if !open(REPORT, ">>$report_name"); +print REPORT "==================End of Make output==================\n"; +print REPORT "\n"; +# Now, run individual tests and create the report +print REPORT "==================Smoke Test ==================\n"; +close($report_name); +chdir 'smoke_test'; +`./smoketest >> ../$report_name`; +chdir '..'; +die if !open(REPORT, ">>$report_name"); +print REPORT "==================End of smoke test==================\n"; +print REPORT "\n"; +print REPORT "==================Regression Test ==================\n"; +close($report_name); +chdir 'regression_tests'; +`./regressiontest >> ../$report_name`; +chdir '..'; +die if !open(REPORT, ">>$report_name"); +print REPORT "==================End of regression test==================\n"; +print REPORT "\n"; +print REPORT "==================Negative Test ==================\n"; +close($report_name); +chdir 'negative'; +`./negative ../../test_data/negative/utf8_invalid.txt >> ../$report_name`; +chdir '..'; +die if !open(REPORT, ">>$report_name"); +print REPORT "==================End of negative test==================\n"; +print REPORT "\n"; +print REPORT "==================utf8reader runs ==================\n"; +close($report_name); +chdir 'utf8reader'; +`./utf8reader ../../test_data/utf8samples/quickbrown.txt >> ../$report_name`; +`./utf8reader ../../test_data/utf8samples/Unicode_transcriptions.html >> ../$report_name`; +`./utf8reader ../../test_data/utf8samples/UTF-8-demo.txt >> ../$report_name`; +chdir '..'; +die if !open(REPORT, ">>$report_name"); +print REPORT "==================End of utf8reader runs==================\n"; +print REPORT "\n"; diff --git a/test_drivers/smoke_test/Makefile b/test_drivers/smoke_test/Makefile new file mode 100644 index 000000000..f66f3af95 --- /dev/null +++ b/test_drivers/smoke_test/Makefile @@ -0,0 +1,5 @@ +CC = g++ +CFLAGS = -g -Wall + +smoketest: test.cpp ../../source/utf8.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h + $(CC) $(CFLAGS) test.cpp -osmoketest diff --git a/test_drivers/smoke_test/test.cpp b/test_drivers/smoke_test/test.cpp new file mode 100644 index 000000000..70d6f15d3 --- /dev/null +++ b/test_drivers/smoke_test/test.cpp @@ -0,0 +1,297 @@ +#include +#include +#include +#include "../../source/utf8.h" +using namespace utf8; +using namespace std; + +int main() +{ + //append + unsigned char u[5] = {0,0,0,0,0}; + + append(0x0448, u); + assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0); + + append(0x65e5, u); + assert (u[0] == 0xe6 && u[1] == 0x97 && u[2] == 0xa5 && u[3] == 0 && u[4] == 0); + + append(0x3044, u); + assert (u[0] == 0xe3 && u[1] == 0x81 && u[2] == 0x84 && u[3] == 0 && u[4] == 0); + + append(0x10346, u); + assert (u[0] == 0xf0 && u[1] == 0x90 && u[2] == 0x8d && u[3] == 0x86 && u[4] == 0); + + + //next + const char* twochars = "\xe6\x97\xa5\xd1\x88"; + const char* w = twochars; + int cp = next(w, twochars + 6); + assert (cp == 0x65e5); + assert (w == twochars + 3); + + const char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88"; + w = threechars; + cp = next(w, threechars + 9); + assert (cp == 0x10346); + assert (w == threechars + 4); + cp = next(w, threechars + 9); + assert (cp == 0x65e5); + assert (w == threechars + 7); + cp = next(w, threechars + 9); + assert (cp == 0x0448); + assert (w == threechars + 9); + + //peek_next + const char* const cw = twochars; + cp = peek_next(cw, cw + 6); + assert (cp == 0x65e5); + assert (cw == twochars); + + //prior + w = twochars + 3; + cp = prior (w, twochars); + assert (cp == 0x65e5); + assert (w == twochars); + + w = threechars + 9; + cp = prior(w, threechars); + assert (cp == 0x0448); + assert (w == threechars + 7); + cp = prior(w, threechars); + assert (cp == 0x65e5); + assert (w == threechars + 4); + cp = prior(w, threechars); + assert (cp == 0x10346); + assert (w == threechars); + + //previous (deprecated) + w = twochars + 3; + cp = previous (w, twochars - 1); + assert (cp == 0x65e5); + assert (w == twochars); + + w = threechars + 9; + cp = previous(w, threechars - 1); + assert (cp == 0x0448); + assert (w == threechars + 7); + cp = previous(w, threechars -1); + assert (cp == 0x65e5); + assert (w == threechars + 4); + cp = previous(w, threechars - 1); + assert (cp == 0x10346); + assert (w == threechars); + + // advance + w = twochars; + advance (w, 2, twochars + 6); + assert (w == twochars + 5); + + // distance + size_t dist = utf8::distance(twochars, twochars + 5); + assert (dist == 2); + + // utf32to8 + int utf32string[] = {0x448, 0x65E5, 0x10346, 0}; + vector utf8result; + utf32to8(utf32string, utf32string + 3, back_inserter(utf8result)); + assert (utf8result.size() == 9); + // try it with the return value; + char* utf8_end = utf32to8(utf32string, utf32string + 3, &utf8result[0]); + assert (utf8_end == &utf8result[0] + 9); + + //utf8to32 + vector utf32result; + utf8to32(twochars, twochars + 5, back_inserter(utf32result)); + assert (utf32result.size() == 2); + // try it with the return value; + int* utf32_end = utf8to32(twochars, twochars + 5, &utf32result[0]); + assert (utf32_end == &utf32result[0] + 2); + + //utf16to8 + unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e}; + utf8result.clear(); + utf16to8(utf16string, utf16string + 5, back_inserter(utf8result)); + assert (utf8result.size() == 10); + // try it with the return value; + utf8_end = utf16to8 (utf16string, utf16string + 5, &utf8result[0]); + assert (utf8_end == &utf8result[0] + 10); + + //utf8to16 + char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e"; + vector utf16result; + utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result)); + assert (utf16result.size() == 4); + assert (utf16result[2] == 0xd834); + assert (utf16result[3] == 0xdd1e); + // try it with the return value; + unsigned short* utf16_end = utf8to16 (utf8_with_surrogates, utf8_with_surrogates + 9, &utf16result[0]); + assert (utf16_end == &utf16result[0] + 4); + + //find_invalid + char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa"; + char* invalid = find_invalid(utf_invalid, utf_invalid + 6); + assert (invalid == utf_invalid + 5); + + //is_valid + bool bvalid = is_valid(utf_invalid, utf_invalid + 6); + assert (bvalid == false); + bvalid = is_valid(utf8_with_surrogates, utf8_with_surrogates + 9); + assert (bvalid == true); + + //starts_with_bom + unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf}; + bool bbom = starts_with_bom(byte_order_mark, byte_order_mark + sizeof(byte_order_mark)); + assert (bbom == true); + bool no_bbom = starts_with_bom(threechars, threechars + sizeof(threechars)); + assert (no_bbom == false); + + //is_bom + bool unsafe_bbom = is_bom(byte_order_mark); + assert (unsafe_bbom == true); + + + //replace_invalid + char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z"; + vector replace_invalid_result(50); + replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), replace_invalid_result.begin(), '?'); + bvalid = is_valid(replace_invalid_result.begin(), replace_invalid_result.end()); + assert (bvalid); + const char* fixed_invalid_sequence = "a????z"; + assert (std::equal(replace_invalid_result.begin(), replace_invalid_result.begin() + sizeof(fixed_invalid_sequence), fixed_invalid_sequence)); + + // iterator + utf8::iterator it(threechars, threechars, threechars + 9); + utf8::iterator it2 = it; + assert (it2 == it); + assert (*it == 0x10346); + assert (*(++it) == 0x65e5); + assert ((*it++) == 0x65e5); + assert (*it == 0x0448); + assert (it != it2); + utf8::iterator endit (threechars + 9, threechars, threechars + 9); + assert (++it == endit); + assert (*(--it) == 0x0448); + assert ((*it--) == 0x0448); + assert (*it == 0x65e5); + assert (--it == utf8::iterator(threechars, threechars, threechars + 9)); + assert (*it == 0x10346); + + ////////////////////////////////////////////////////////// + //// Unchecked variants + ////////////////////////////////////////////////////////// + + //append + memset(u, 0, 5); + append(0x0448, u); + assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0); + + append(0x65e5, u); + assert (u[0] == 0xe6 && u[1] == 0x97 && u[2] == 0xa5 && u[3] == 0 && u[4] == 0); + + append(0x10346, u); + assert (u[0] == 0xf0 && u[1] == 0x90 && u[2] == 0x8d && u[3] == 0x86 && u[4] == 0); + + //next + w = twochars; + cp = unchecked::next(w); + assert (cp == 0x65e5); + assert (w == twochars + 3); + + w = threechars; + cp = unchecked::next(w); + assert (cp == 0x10346); + assert (w == threechars + 4); + cp = unchecked::next(w); + assert (cp == 0x65e5); + assert (w == threechars + 7); + cp = unchecked::next(w); + assert (cp == 0x0448); + assert (w == threechars + 9); + + //peek_next + cp = unchecked::peek_next(cw); + assert (cp == 0x65e5); + assert (cw == twochars); + + + //previous (calls prior internally) + + w = twochars + 3; + cp = unchecked::previous (w); + assert (cp == 0x65e5); + assert (w == twochars); + + w = threechars + 9; + cp = unchecked::previous(w); + assert (cp == 0x0448); + assert (w == threechars + 7); + cp = unchecked::previous(w); + assert (cp == 0x65e5); + assert (w == threechars + 4); + cp = unchecked::previous(w); + assert (cp == 0x10346); + assert (w == threechars); + + // advance + w = twochars; + unchecked::advance (w, 2); + assert (w == twochars + 5); + + // distance + dist = unchecked::distance(twochars, twochars + 5); + assert (dist == 2); + + // utf32to8 + utf8result.clear(); + unchecked::utf32to8(utf32string, utf32string + 3, back_inserter(utf8result)); + assert (utf8result.size() == 9); + // try it with the return value; + utf8_end = utf32to8(utf32string, utf32string + 3, &utf8result[0]); + assert(utf8_end == &utf8result[0] + 9); + + //utf8to32 + utf32result.clear(); + unchecked::utf8to32(twochars, twochars + 5, back_inserter(utf32result)); + assert (utf32result.size() == 2); + // try it with the return value; + utf32_end = utf8to32(twochars, twochars + 5, &utf32result[0]); + assert (utf32_end == &utf32result[0] + 2); + + //utf16to8 + utf8result.clear(); + unchecked::utf16to8(utf16string, utf16string + 5, back_inserter(utf8result)); + assert (utf8result.size() == 10); + // try it with the return value; + utf8_end = utf16to8 (utf16string, utf16string + 5, &utf8result[0]); + assert (utf8_end == &utf8result[0] + 10); + + //utf8to16 + utf16result.clear(); + unchecked::utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result)); + assert (utf16result.size() == 4); + assert (utf16result[2] == 0xd834); + assert (utf16result[3] == 0xdd1e); + // try it with the return value; + utf16_end = utf8to16 (utf8_with_surrogates, utf8_with_surrogates + 9, &utf16result[0]); + assert (utf16_end == &utf16result[0] + 4); + + // iterator + utf8::unchecked::iterator un_it(threechars); + utf8::unchecked::iterator un_it2 = un_it; + assert (un_it2 == un_it); + assert (*un_it == 0x10346); + assert (*(++un_it) == 0x65e5); + assert ((*un_it++) == 0x65e5); + assert (un_it != un_it2); + assert (*un_it == 0x0448); + utf8::unchecked::iterator un_endit (threechars + 9); + assert (++un_it == un_endit); + assert (*(--un_it) == 0x0448); + assert ((*un_it--) == 0x0448); + assert (*un_it == 0x65e5); + assert (--un_it == utf8::unchecked::iterator(threechars)); + assert (*un_it == 0x10346); +} + + diff --git a/test_drivers/utf8reader/Makefile b/test_drivers/utf8reader/Makefile new file mode 100644 index 000000000..29a9aa886 --- /dev/null +++ b/test_drivers/utf8reader/Makefile @@ -0,0 +1,5 @@ +CC = g++ +CFLAGS = -g -Wall -pedantic + +utf8readertest: utf8reader.cpp ../../source/utf8.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h + $(CC) $(CFLAGS) utf8reader.cpp -o utf8reader diff --git a/test_drivers/utf8reader/utf8reader.cpp b/test_drivers/utf8reader/utf8reader.cpp new file mode 100644 index 000000000..c88a5ee1b --- /dev/null +++ b/test_drivers/utf8reader/utf8reader.cpp @@ -0,0 +1,160 @@ +#include "../../source/utf8.h" +using namespace utf8; + +#include +#include +#include +#include +using namespace std; + +int main(int argc, char** argv) +{ + if (argc != 2) { + cout << "\nUsage: utfreader filename\n"; + return 0; + } + const char* TEST_FILE_PATH = argv[1]; + // Open the test file + ifstream fs8(TEST_FILE_PATH); + if (!fs8.is_open()) { + cout << "Could not open " << TEST_FILE_PATH << endl; + return 0; + } + + // Read it line by line + unsigned int line_count = 0; + char byte; + while (!fs8.eof()) { + string line; + while ((byte = static_cast(fs8.get())) != '\n' && !fs8.eof()) + line.push_back(byte); + + line_count++; + // Play around with each line and convert it to utf16 + string::iterator line_start = line.begin(); + string::iterator line_end = line.end(); + line_end = find_invalid(line_start, line_end); + if (line_end != line.end()) + cout << "Line " << line_count << ": Invalid utf-8 at byte " << int(line.end() - line_end) << '\n'; + + // Convert it to utf-16 and write to the file + vector utf16_line; + utf8to16(line_start, line_end, back_inserter(utf16_line)); + + // Back to utf-8 and compare it to the original line. + string back_to_utf8; + utf16to8(utf16_line.begin(), utf16_line.end(), back_inserter(back_to_utf8)); + if (back_to_utf8.compare(string(line_start, line_end)) != 0) + cout << "Line " << line_count << ": Conversion to UTF-16 and back failed" << '\n'; + + // Now, convert it to utf-32, back to utf-8 and compare + vector utf32_line; + utf8to32(line_start, line_end, back_inserter(utf32_line)); + back_to_utf8.clear(); + utf32to8(utf32_line.begin(), utf32_line.end(), back_inserter(back_to_utf8)); + if (back_to_utf8.compare(string(line_start, line_end)) != 0) + cout << "Line " << line_count << ": Conversion to UTF-32 and back failed" << '\n'; + + // Now, iterate and back + unsigned char_count = 0; + string::iterator it = line_start; + while (it != line_end) { + unsigned int next_cp = peek_next(it, line_end); + if (next(it, line_end) != next_cp) + cout << "Line " << line_count << ": Error: peek_next gave a different result than next" << '\n'; + char_count++; + } + if (char_count != utf32_line.size()) + cout << "Line " << line_count << ": Error in iterating with next - wrong number of characters" << '\n'; + + string::iterator adv_it = line_start; + utf8::advance(adv_it, char_count, line_end); + if (adv_it != line_end) + cout << "Line " << line_count << ": Error in advance function" << '\n'; + + if (string::size_type(utf8::distance(line_start, line_end)) != char_count) + cout << "Line " << line_count << ": Error in distance function" << '\n'; + + while (it != line_start) { + previous(it, line.rend().base()); + char_count--; + } + if (char_count != 0) + cout << "Line " << line_count << ": Error in iterating with previous - wrong number of characters" << '\n'; + + // Try utf8::iterator + utf8::iterator u8it(line_start, line_start, line_end); + if (!utf32_line.empty() && *u8it != utf32_line.at(0)) + cout << "Line " << line_count << ": Error in utf::iterator * operator" << '\n'; + if (std::distance(u8it, utf8::iterator(line_end, line_start, line_end)) != static_cast(utf32_line.size())) + cout << "Line " << line_count << ": Error in using utf::iterator with std::distance - wrong number of characters" << '\n'; + + std::advance(u8it, utf32_line.size()); + if (u8it != utf8::iterator(line_end, line_start, line_end)) + cout << "Line " << line_count << ": Error in using utf::iterator with std::advance" << '\n'; + + + //======================== Now, the unchecked versions ====================== + // Convert it to utf-16 and compare to the checked version + vector utf16_line_unchecked; + unchecked::utf8to16(line_start, line_end, back_inserter(utf16_line_unchecked)); + + if (utf16_line != utf16_line_unchecked) + cout << "Line " << line_count << ": Error in unchecked::utf8to16" << '\n'; + + // Back to utf-8 and compare it to the original line. + back_to_utf8.clear(); + unchecked::utf16to8(utf16_line_unchecked.begin(), utf16_line_unchecked.end(), back_inserter(back_to_utf8)); + if (back_to_utf8.compare(string(line_start, line_end)) != 0) + cout << "Line " << line_count << ": Unchecked conversion to UTF-16 and back failed" << '\n'; + + // Now, convert it to utf-32, back to utf-8 and compare + vector utf32_line_unchecked; + unchecked::utf8to32(line_start, line_end, back_inserter(utf32_line_unchecked)); + if (utf32_line != utf32_line_unchecked) + cout << "Line " << line_count << ": Error in unchecked::utf8to32" << '\n'; + + back_to_utf8.clear(); + unchecked::utf32to8(utf32_line.begin(), utf32_line.end(), back_inserter(back_to_utf8)); + if (back_to_utf8.compare(string(line_start, line_end)) != 0) + cout << "Line " << line_count << ": Unchecked conversion to UTF-32 and back failed" << '\n'; + + // Now, iterate and back + char_count = 0; + it = line_start; + while (it != line_end) { + unsigned int next_cp = unchecked::peek_next(it); + if (unchecked::next(it) != next_cp) + cout << "Line " << line_count << ": Error: unchecked::peek_next gave a different result than unchecked::next" << '\n';; + char_count++; + } + if (char_count != utf32_line.size()) + cout << "Line " << line_count << ": Error in iterating with unchecked::next - wrong number of characters" << '\n'; + + adv_it = line_start; + utf8::unchecked::advance(adv_it, char_count); + if (adv_it != line_end) + cout << "Line " << line_count << ": Error in unchecked::advance function" << '\n'; + + if (string::size_type(utf8::unchecked::distance(line_start, line_end)) != char_count) + cout << "Line " << line_count << ": Error in unchecked::distance function" << '\n'; + + while (it != line_start) { + unchecked::previous(it); + char_count--; + } + if (char_count != 0) + cout << "Line " << line_count << ": Error in iterating with unchecked::previous - wrong number of characters" << '\n'; + + // Try utf8::unchecked::iterator + utf8::unchecked::iterator un_u8it(line_start); + if (!utf32_line.empty() && *un_u8it != utf32_line.at(0)) + cout << "Line " << line_count << ": Error in utf::unchecked::iterator * operator" << '\n'; + if (std::distance(un_u8it, utf8::unchecked::iterator(line_end)) != static_cast(utf32_line.size())) + cout << "Line " << line_count << ": Error in using utf::unchecked::iterator with std::distance - wrong number of characters" << '\n'; + + std::advance(un_u8it, utf32_line.size()); + if (un_u8it != utf8::unchecked::iterator(line_end)) + cout << "Line " << line_count << ": Error in using utf::unchecked::iterator with std::advance" << '\n'; + } +} From 735b8b73738054e234177c534d92b6c6f32c5a1e Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 12 Sep 2015 20:41:43 -0400 Subject: [PATCH 03/18] Fixing Readme.md --- README.md | 961 ++++++++++++++++++++++++++---------------------------- 1 file changed, 460 insertions(+), 501 deletions(-) diff --git a/README.md b/README.md index 9585b2fe0..108216080 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,5 @@ # UTF8-CPP: UTF-8 with C++ in a Portable Way -[The Sourceforge project page](https://sourceforge.net/projects/utfcpp) - -
- -## Table of Contents - -* [Introduction](#introduction) -* [Examples of Use](#examples) - * [Introductionary Sample](#introsample) - * [Checking if a file contains valid UTF-8 text](#validfile) - * [Ensure that a string contains valid UTF-8 text](#fixinvalid) -* [Reference](#reference) - * [Functions From utf8 Namespace](#funutf8) - * [Types From utf8 Namespace](#typesutf8) - * [Functions From utf8::unchecked Namespace](#fununchecked) - * [Types From utf8::unchecked Namespace](#typesunchecked) -* [Points of Interest](#points) -* [Links](#links) - -
## Introduction @@ -35,59 +15,60 @@ The purpose of this article is not to offer an introduction to Unicode in genera To 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: -
#include 
-#include 
-#include 
-#include 
-#include "utf8.h"
-using namespace std;
-int main(int argc, char** argv)
+```
+#include 
+#include 
+#include 
+#include 
+#include "utf8.h"
+using namespace std;
+int main(int argc, char** argv)
 {
-    if (argc != 2) {
-        cout << "\nUsage: docsample filename\n";
-        return 0;
+    if (argc != 2) {
+        cout << "\nUsage: docsample filename\n";
+        return 0;
     }
 
-    const char* test_file_path = argv[1];
-    // Open the test file (contains UTF-8 encoded text)
+    const char* test_file_path = argv[1];
+    // Open the test file (contains UTF-8 encoded text)
     ifstream fs8(test_file_path);
-    if (!fs8.is_open()) {
-    cout << "Could not open " << test_file_path << endl;
-    return 0;
+    if (!fs8.is_open()) {
+    cout << "Could not open " << test_file_path << endl;
+    return 0;
     }
 
-    unsigned line_count = 1;
+    unsigned line_count = 1;
     string line;
-    // Play with all the lines in the file
-    while (getline(fs8, line)) {
-       // check for invalid utf-8 (for a simple yes/no check, there is also utf8::is_valid function)
+    // Play with all the lines in the file
+    while (getline(fs8, line)) {
+       // check for invalid utf-8 (for a simple yes/no check, there is also utf8::is_valid function)
         string::iterator end_it = utf8::find_invalid(line.begin(), line.end());
-        if (end_it != line.end()) {
-            cout << "Invalid UTF-8 encoding detected at line " << line_count << "\n";
-            cout << "This part is fine: " << string(line.begin(), end_it) << "\n";
+        if (end_it != line.end()) {
+            cout << "Invalid UTF-8 encoding detected at line " << line_count << "\n";
+            cout << "This part is fine: " << string(line.begin(), end_it) << "\n";
         }
 
-        // Get the line length (at least for the valid part)
-        int length = utf8::distance(line.begin(), end_it);
-        cout << "Length of line " << line_count << " is " << length <<  "\n";
+        // Get the line length (at least for the valid part)
+        int length = utf8::distance(line.begin(), end_it);
+        cout << "Length of line " << line_count << " is " << length <<  "\n";
 
-        // Convert it to utf-16
+        // Convert it to utf-16
         vector utf16line;
         utf8::utf8to16(line.begin(), end_it, back_inserter(utf16line));
 
-        // And back to utf-8
+        // And back to utf-8
         string utf8line; 
         utf8::utf16to8(utf16line.begin(), utf16line.end(), back_inserter(utf8line));
 
-        // Confirm that the conversion went OK:
-        if (utf8line != string(line.begin(), end_it))
-            cout << "Error in UTF-16 conversion at line: " << line_count << "\n";        
+        // Confirm that the conversion went OK:
+        if (utf8line != string(line.begin(), end_it))
+            cout << "Error in UTF-16 conversion at line: " << line_count << "\n";        
 
         line_count++;
     }
-    return 0;
+    return 0;
 }
-
+``` In 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`. @@ -95,38 +76,40 @@ In the previous code sample, for each line we performed a detection of invalid U Here is a function that checks whether the content of a file is valid UTF-8 encoded text without reading the content into the memory: -
    
-bool valid_utf8_file(iconst char* file_name)
+```
+bool valid_utf8_file(const char* file_name)
 {
     ifstream ifs(file_name);
-    if (!ifs)
-        return false; // even better, throw here
+    if (!ifs)
+        return false; // even better, throw here
 
-    istreambuf_iterator<char> it(ifs.rdbuf());
-    istreambuf_iterator<char> eos;
+    istreambuf_iterator it(ifs.rdbuf());
+    istreambuf_iterator eos;
 
-    return utf8::is_valid(it, eos);
+    return utf8::is_valid(it, eos);
 }
-
+``` Because 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. Note 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: -
    utf8::utf8to16(it, eos, back_inserter(u16string));
-
+``` + utf8::utf8to16(it, eos, back_inserter(u16string)); +``` ### Ensure that a string contains valid UTF-8 text If 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: -
void fix_utf8_string(std::string& str)
+```
+void fix_utf8_string(std::string& str)
 {
     std::string temp;
     utf8::replace_invalid(str.begin(), str.end(), back_inserter(temp));
     str = temp;
 }
-
+``` The 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. @@ -140,22 +123,23 @@ Available in version 1.0 and later. Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string. -
template <typename octet_iterator>
+```
+template 
 octet_iterator append(uint32_t cp, octet_iterator result);
-
-
+``` `octet_iterator`: an output iterator. - `cp`: a 32 bit integer representing a code point to append to the sequence. - `result`: an output iterator to the place in the sequence where to append the code point. - Return value: an iterator pointing to the place after the newly appended sequence. +`cp`: a 32 bit integer representing a code point to append to the sequence. +`result`: an output iterator to the place in the sequence where to append the code point. +Return value: an iterator pointing to the place after the newly appended sequence. Example of use: -
unsigned char u[5] = {0,0,0,0,0};
-unsigned char* end = append(0x0448, u);
-assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0);
-
+``` +unsigned char u[5] = {0,0,0,0,0}; +unsigned char* end = append(0x0448, u); +assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0); +``` Note 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. @@ -167,24 +151,25 @@ Available in version 1.0 and later. Given the iterator to the beginning of the UTF-8 sequence, it returns the code point and moves the iterator to the next position. -
template <typename octet_iterator> 
+```
+template  
 uint32_t next(octet_iterator& it, octet_iterator end);
-
-
+``` `octet_iterator`: an input iterator. - `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. - `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. - Return value: the 32 bit representation of the processed UTF-8 code point. +`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. +`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. +Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars;
-int cp = next(w, twochars + 6);
-assert (cp == 0x65e5);
-assert (w == twochars + 3);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +char* w = twochars; +int cp = next(w, twochars + 6); +assert (cp == 0x65e5); +assert (w == twochars + 3); +``` This function is typically used to iterate through a UTF-8 encoded string. @@ -196,24 +181,26 @@ Available in version 2.1 and later. Given 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. -
template <typename octet_iterator> 
+```
+template  
 uint32_t peek_next(octet_iterator it, octet_iterator end);
+```
 
-
`octet_iterator`: an input iterator. - `it`: an iterator pointing to the beginning of an UTF-8 encoded code point. - `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. - Return value: the 32 bit representation of the processed UTF-8 code point. +`it`: an iterator pointing to the beginning of an UTF-8 encoded code point. +`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. +Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars;
-int cp = peek_next(w, twochars + 6);
-assert (cp == 0x65e5);
+```
+char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+int cp = peek_next(w, twochars + 6);
+assert (cp == 0x65e5);
 assert (w == twochars);
-
+``` In case of an invalid UTF-8 seqence, a `utf8::invalid_utf8` exception is thrown. @@ -223,24 +210,25 @@ Available in version 1.02 and later. Given 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. -
template <typename octet_iterator> 
+```
+template  
 uint32_t prior(octet_iterator& it, octet_iterator start);
-
-
+``` `octet_iterator`: a bidirectional iterator. - `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. - `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. - Return value: the 32 bit representation of the previous code point. +`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. +`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. + Return value: the 32 bit representation of the previous code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-unsigned char* w = twochars + 3;
-int cp = prior (w, twochars);
-assert (cp == 0x65e5);
+```
+char* twochars = "\xe6\x97\xa5\xd1\x88";
+unsigned char* w = twochars + 3;
+int cp = prior (w, twochars);
+assert (cp == 0x65e5);
 assert (w == twochars);
-
+``` This 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. @@ -256,24 +244,26 @@ Deprecated in version 1.02 and later. Given 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. -
template <typename octet_iterator> 
+```
+template  
 uint32_t previous(octet_iterator& it, octet_iterator pass_start);
-
-
+``` `octet_iterator`: a random access iterator. - `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. - `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. - Return value: the 32 bit representation of the previous code point. +`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. +`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. +Return value: the 32 bit representation of the previous code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-unsigned char* w = twochars + 3;
-int cp = previous (w, twochars - 1);
-assert (cp == 0x65e5);
+```
+char* twochars = "\xe6\x97\xa5\xd1\x88";
+unsigned char* w = twochars + 3;
+int cp = previous (w, twochars - 1);
+assert (cp == 0x65e5);
 assert (w == twochars);
-
+``` + `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. @@ -282,29 +272,29 @@ assert (w == twochars); In 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 #### utf8::advance - Available in version 1.0 and later. Advances an iterator by the specified number of code points within an UTF-8 sequence. -
template <typename octet_iterator, typename distance_type> 
-void advance (octet_iterator& it, distance_type n, octet_iterator end);
-
-
+``` +template +void advance (octet_iterator& it, distance_type n, octet_iterator end); +``` `octet_iterator`: an input iterator. - `distance_type`: an integral type convertible to `octet_iterator`'s difference type. - `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. - `n`: a positive integer that shows how many code points we want to advance. - `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. +`distance_type`: an integral type convertible to `octet_iterator`'s difference type. +`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. +`n`: a positive integer that shows how many code points we want to advance. +`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. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-unsigned char* w = twochars;
-advance (w, 2, twochars + 6);
-assert (w == twochars + 5);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +unsigned char* w = twochars; +advance (w, 2, twochars + 6); +assert (w == twochars + 5); +``` This function works only "forward". In case of a negative `n`, there is no effect. @@ -316,22 +306,23 @@ Available in version 1.0 and later. Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them. -
template <typename octet_iterator> 
-typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last);
-
-
+``` +template +typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last); +``` `octet_iterator`: an input iterator. - `first`: an iterator to a beginning of a UTF-8 encoded code point. - `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. - Return value the distance between the iterators, in code points. +`first`: an iterator to a beginning of a UTF-8 encoded code point. +`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. + Return value the distance between the iterators, in code points. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-size_t dist = utf8::distance(twochars, twochars + 5);
-assert (dist == 2);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +size_t dist = utf8::distance(twochars, twochars + 5); +assert (dist == 2); +``` This 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. @@ -343,25 +334,26 @@ Available in version 1.0 and later. Converts a UTF-16 encoded string to UTF-8. -
template <typename u16bit_iterator, typename octet_iterator>
+```
+template 
 octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);
-
-
+``` `u16bit_iterator`: an input iterator. - `octet_iterator`: an output iterator. - `start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert. - `end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert. - `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-8 string. +`octet_iterator`: an output iterator. +`start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert. +`end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert. +`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -
unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
-vector<unsigned char> utf8result;
-utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
-assert (utf8result.size() == 10);    
-
+``` +unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e}; +vector utf8result; +utf16to8(utf16string, utf16string + 5, back_inserter(utf8result)); +assert (utf8result.size() == 10); +``` In case of invalid UTF-16 sequence, a `utf8::invalid_utf16` exception is thrown. @@ -371,26 +363,27 @@ Available in version 1.0 and later. Converts an UTF-8 encoded string to UTF-16 -
template <typename u16bit_iterator, typename octet_iterator>
+```
+template 
 u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result);
-
-
+``` `octet_iterator`: an input iterator. - `u16bit_iterator`: an output iterator. - `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. - `result`: an output iterator to the place in the UTF-16 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-16 string. +`u16bit_iterator`: an output iterator. +`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. +`result`: an output iterator to the place in the UTF-16 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-16 string. Example of use: -
char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e";
-vector <unsigned short> utf16result;
-utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result));
-assert (utf16result.size() == 4);
-assert (utf16result[2] == 0xd834);
-assert (utf16result[3] == 0xdd1e);
-
+``` +char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e"; +vector utf16result; +utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result)); +assert (utf16result.size() == 4); +assert (utf16result[2] == 0xd834); +assert (utf16result[3] == 0xdd1e); +``` In 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. @@ -400,25 +393,26 @@ Available in version 1.0 and later. Converts a UTF-32 encoded string to UTF-8. -
template <typename octet_iterator, typename u32bit_iterator>
+```
+template 
 octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result);
-
-
+``` `octet_iterator`: an output iterator. - `u32bit_iterator`: an input iterator. - `start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert. - `end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert. - `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-8 string. +`u32bit_iterator`: an input iterator. +`start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert. +`end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert. +`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -
int utf32string[] = {0x448, 0x65E5, 0x10346, 0};
-vector<unsigned char> utf8result;
-utf32to8(utf32string, utf32string + 3, back_inserter(utf8result));
-assert (utf8result.size() == 9);
-
+``` +int utf32string[] = {0x448, 0x65E5, 0x10346, 0}; +vector utf8result; +utf32to8(utf32string, utf32string + 3, back_inserter(utf8result)); +assert (utf8result.size() == 9); +``` In case of invalid UTF-32 string, a `utf8::invalid_code_point` exception is thrown. @@ -428,25 +422,26 @@ Available in version 1.0 and later. Converts a UTF-8 encoded string to UTF-32. -
template <typename octet_iterator, typename u32bit_iterator>
+```
+template 
 u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result);
-
-
+``` `octet_iterator`: an input iterator. - `u32bit_iterator`: an output iterator. - `start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. - `end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert. - `result`: an output iterator to the place in the UTF-32 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-32 string. +`u32bit_iterator`: an output iterator. +`start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. +`end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert. +`result`: an output iterator to the place in the UTF-32 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-32 string. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-vector<int> utf32result;
-utf8to32(twochars, twochars + 5, back_inserter(utf32result));
-assert (utf32result.size() == 2);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +vector utf32result; +utf8to32(twochars, twochars + 5, back_inserter(utf32result)); +assert (utf32result.size() == 2); +``` In 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. @@ -456,21 +451,23 @@ Available in version 1.0 and later. Detects an invalid sequence within a UTF-8 string. -
template <typename octet_iterator> 
+```
+template  
 octet_iterator find_invalid(octet_iterator start, octet_iterator end);
-
+``` `octet_iterator`: an input iterator. - `start`: an iterator pointing to the beginning of the UTF-8 string to test for validity. - `end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity. - Return value: an iterator pointing to the first invalid octet in the UTF-8 string. In case none were found, equals `end`. +`start`: an iterator pointing to the beginning of the UTF-8 string to test for validity. +`end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity. +Return value: an iterator pointing to the first invalid octet in the UTF-8 string. In case none were found, equals `end`. Example of use: -
char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
-char* invalid = find_invalid(utf_invalid, utf_invalid + 6);
-assert (invalid == utf_invalid + 5);
-
+``` +char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa"; +char* invalid = find_invalid(utf_invalid, utf_invalid + 6); +assert (invalid == utf_invalid + 5); +``` This 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. @@ -480,22 +477,23 @@ Available in version 1.0 and later. Checks whether a sequence of octets is a valid UTF-8 string. -
template <typename octet_iterator> 
-bool is_valid(octet_iterator start, octet_iterator end);
-
-
+``` +template +bool is_valid(octet_iterator start, octet_iterator end); +``` `octet_iterator`: an input iterator. - `start`: an iterator pointing to the beginning of the UTF-8 string to test for validity. - `end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity. - Return value: `true` if the sequence is a valid UTF-8 string; `false` if not. +`start`: an iterator pointing to the beginning of the UTF-8 string to test for validity. +`end`: an iterator pointing to pass-the-end of the UTF-8 string to test for validity. +Return value: `true` if the sequence is a valid UTF-8 string; `false` if not. Example of use: -
char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
-bool bvalid = is_valid(utf_invalid, utf_invalid + 6);
+```
+char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa";
+bool bvalid = is_valid(utf_invalid, utf_invalid + 6);
 assert (bvalid == false);
-
+``` `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. @@ -505,31 +503,32 @@ Available in version 2.0 and later. Replaces all invalid UTF-8 sequences within a string with a replacement marker. -
template <typename octet_iterator, typename output_iterator>
+```
+template 
 output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement);
-template <typename octet_iterator, typename output_iterator>
+template 
 output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out);
-
-
+``` `octet_iterator`: an input iterator. - `output_iterator`: an output iterator. - `start`: an iterator pointing to the beginning of the UTF-8 string to look for invalid UTF-8 sequences. - `end`: an iterator pointing to pass-the-end of the UTF-8 string to look for invalid UTF-8 sequences. - `out`: An output iterator to the range where the result of replacement is stored. - `replacement`: A Unicode code point for the replacement marker. The version without this parameter assumes the value `0xfffd` - Return value: An iterator pointing to the place after the UTF-8 string with replaced invalid sequences. +`output_iterator`: an output iterator. +`start`: an iterator pointing to the beginning of the UTF-8 string to look for invalid UTF-8 sequences. +`end`: an iterator pointing to pass-the-end of the UTF-8 string to look for invalid UTF-8 sequences. +`out`: An output iterator to the range where the result of replacement is stored. +`replacement`: A Unicode code point for the replacement marker. The version without this parameter assumes the value `0xfffd` +Return value: An iterator pointing to the place after the UTF-8 string with replaced invalid sequences. Example of use: -
char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z";
-vector<char> replace_invalid_result;
-replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), back_inserter(replace_invalid_result), '?');
+```
+char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z";
+vector replace_invalid_result;
+replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), back_inserter(replace_invalid_result), '?');
 bvalid = is_valid(replace_invalid_result.begin(), replace_invalid_result.end());
 assert (bvalid);
-char* fixed_invalid_sequence = "a????z";
+char* fixed_invalid_sequence = "a????z";
 assert (std::equal(replace_invalid_result.begin(), replace_invalid_result.end(), fixed_invalid_sequence));
-
+``` `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. @@ -541,21 +540,23 @@ Available in version 2.3 and later. Relaces deprecated `is_bom()` function. Checks whether an octet sequence starts with a UTF-8 byte order mark (BOM) -
template <typename octet_iterator> 
-bool starts_with_bom (octet_iterator it, octet_iterator end);
-
+``` +template +bool starts_with_bom (octet_iterator it, octet_iterator end); +``` `octet_iterator`: an input iterator. - `it`: beginning of the octet sequence to check - `end`: pass-end of the sequence to check - Return value: `true` if the sequence starts with a UTF-8 byte order mark; `false` if not. +`it`: beginning of the octet sequence to check +`end`: pass-end of the sequence to check +Return value: `true` if the sequence starts with a UTF-8 byte order mark; `false` if not. Example of use: -
unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf};
-bool bbom = starts_with_bom(byte_order_mark, byte_order_mark + sizeof(byte_order_mark));
-assert (bbom == true);
-
+``` +unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf}; +bool bbom = starts_with_bom(byte_order_mark, byte_order_mark + sizeof(byte_order_mark)); +assert (bbom == true); +``` The 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. @@ -565,20 +566,22 @@ Available in version 1.0 and later. Deprecated in version 2.3\. `starts_with_bom Checks whether a sequence of three octets is a UTF-8 byte order mark (BOM) -
template <typename octet_iterator> 
-bool is_bom (octet_iterator it);  // Deprecated
-
+``` +template +bool is_bom (octet_iterator it); // Deprecated +``` `octet_iterator`: an input iterator. - `it`: beginning of the 3-octet sequence to check - Return value: `true` if the sequence is UTF-8 byte order mark; `false` if not. +`it`: beginning of the 3-octet sequence to check +Return value: `true` if the sequence is UTF-8 byte order mark; `false` if not. Example of use: -
unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf};
-bool bbom = is_bom(byte_order_mark);
-assert (bbom == true);
-
+``` +unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf}; +bool bbom = is_bom(byte_order_mark); +assert (bbom == true); +``` The 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. @@ -592,18 +595,20 @@ Available in version 2.3 and later. Base class for the exceptions thrown by UTF CPP library functions. -
class exception : public std::exception {};
-
+``` +class exception : public std::exception {}; +``` Example of use: -
try {
+```
+try {
   code_that_uses_utf_cpp_library();
 }
-catch(const utf8::exception& utfcpp_ex) {
+catch(const utf8::exception& utfcpp_ex) {
   cerr << utfcpp_ex.what();
 }
-
+``` #### utf8::invalid_code_point @@ -611,12 +616,12 @@ Available in version 1.0 and later. Thrown by UTF8 CPP functions such as `advance` and `next` if an UTF-8 sequence represents and invalid code point. -
class invalid_code_point : public exception {
-public: 
-    uint32_t code_point() const;
+```
+class invalid_code_point : public exception {
+public: 
+    uint32_t code_point() const;
 };
-
-
+``` Member function `code_point()` can be used to determine the invalid code point that caused the exception to be thrown. @@ -626,11 +631,12 @@ Available in version 1.0 and later. Thrown by UTF8 CPP functions such as `next` and `prior` if an invalid UTF-8 sequence is detected during decoding. -
class invalid_utf8 : public exception {
-public: 
-    uint8_t utf8_octet() const;
+```
+class invalid_utf8 : public exception {
+public: 
+    uint8_t utf8_octet() const;
 };
-
+``` Member function `utf8_octet()` can be used to determine the beginning of the byte sequence that caused the exception to be thrown. @@ -640,11 +646,12 @@ Available in version 1.0 and later. Thrown by UTF8 CPP function `utf16to8` if an invalid UTF-16 sequence is detected during decoding. -
class invalid_utf16 : public exception {
-public: 
-    uint16_t utf16_word() const;
+```
+class invalid_utf16 : public exception {
+public: 
+    uint16_t utf16_word() const;
 };
-
+``` Member function `utf16_word()` can be used to determine the UTF-16 code unit that caused the exception to be thrown. @@ -654,8 +661,9 @@ Available in version 1.0 and later. Thrown by UTF8 CPP functions such as `next` if the end of the decoded UTF-8 sequence was reached before the code point was decoded. -
class not_enough_room : public exception {};
-
+``` +class not_enough_room : public exception {}; +``` #### utf8::iterator @@ -663,83 +671,53 @@ Available in version 2.0 and later. Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets. -
template <typename octet_iterator>
-class iterator;
-
+``` +template +class iterator; +``` ##### Member functions -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
+`iterator();` the deafult constructor; the underlying octet_iterator is constructed with its default constructor. +`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. +`octet_iterator base () const;` returns the underlying octet_iterator. +`uint32_t operator * () const;` decodes the utf-8 sequence the underlying octet_iterator is pointing to and returns the code point. +`bool operator == (const iterator& rhs) const;` returns `true` if the two underlaying iterators are equal. +`bool operator != (const iterator& rhs) const;` returns `true` if the two underlaying iterators are not equal. +`iterator& operator ++ ();` the prefix increment - moves the iterator to the next UTF-8 encoded code point. +`iterator operator ++ (int);` the postfix increment - moves the iterator to the next UTF-8 encoded code point and returns the current one. +`iterator& operator -- ();` the prefix decrement - moves the iterator to the previous UTF-8 encoded code point. +`iterator operator -- (int);` the postfix decrement - moves the iterator to the previous UTF-8 encoded code point and returns the current one. Example of use: -
char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
-utf8::iterator<char*> it(threechars, threechars, threechars + 9);
-utf8::iterator<char*> it2 = it;
+```
+char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
+utf8::iterator it(threechars, threechars, threechars + 9);
+utf8::iterator it2 = it;
 assert (it2 == it);
-assert (*it == 0x10346);
-assert (*(++it) == 0x65e5);
-assert ((*it++) == 0x65e5);
-assert (*it == 0x0448);
+assert (*it == 0x10346);
+assert (*(++it) == 0x65e5);
+assert ((*it++) == 0x65e5);
+assert (*it == 0x0448);
 assert (it != it2);
-utf8::iterator<char*> endit (threechars + 9, threechars, threechars + 9);  
+utf8::iterator endit (threechars + 9, threechars, threechars + 9);  
 assert (++it == endit);
-assert (*(--it) == 0x0448);
-assert ((*it--) == 0x0448);
-assert (*it == 0x65e5);
-assert (--it == utf8::iterator<char*>(threechars, threechars, threechars + 9));
-assert (*it == 0x10346);
-
+assert (*(--it) == 0x0448); +assert ((*it--) == 0x0448); +assert (*it == 0x65e5); +assert (--it == utf8::iterator(threechars, threechars, threechars + 9)); +assert (*it == 0x10346); +``` The 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. Note 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.: -
std::string s = "example";
+```
+std::string s = "example";
 utf8::iterator i (s.begin(), s.begin(), s.end());
-
+``` ### Functions From utf8::unchecked Namespace @@ -749,21 +727,22 @@ Available in version 1.0 and later. Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string. -
template <typename octet_iterator>
+```
+template 
 octet_iterator append(uint32_t cp, octet_iterator result);
-
-
+``` `cp`: A 32 bit integer representing a code point to append to the sequence. - `result`: An output iterator to the place in the sequence where to append the code point. - Return value: An iterator pointing to the place after the newly appended sequence. +`result`: An output iterator to the place in the sequence where to append the code point. +Return value: An iterator pointing to the place after the newly appended sequence. Example of use: -
unsigned char u[5] = {0,0,0,0,0};
-unsigned char* end = unchecked::append(0x0448, u);
-assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0);
-
+``` +unsigned char u[5] = {0,0,0,0,0}; +unsigned char* end = unchecked::append(0x0448, u); +assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0); +``` This 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. @@ -773,22 +752,23 @@ Available in version 1.0 and later. Given the iterator to the beginning of a UTF-8 sequence, it returns the code point and moves the iterator to the next position. -
template <typename octet_iterator>
+```
+template 
 uint32_t next(octet_iterator& it);
-
-
+``` `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. - Return value: the 32 bit representation of the processed UTF-8 code point. + Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars;
-int cp = unchecked::next(w);
-assert (cp == 0x65e5);
-assert (w == twochars + 3);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +char* w = twochars; +int cp = unchecked::next(w); +assert (cp == 0x65e5); +assert (w == twochars + 3); +``` This is a faster but less safe version of `utf8::next`. It does not check for validity of the supplied UTF-8 sequence. @@ -798,22 +778,23 @@ Available in version 2.1 and later. Given the iterator to the beginning of a UTF-8 sequence, it returns the code point. -
template <typename octet_iterator>
+```
+template 
 uint32_t peek_next(octet_iterator it);
-
-
+``` `it`: an iterator pointing to the beginning of an UTF-8 encoded code point. - Return value: the 32 bit representation of the processed UTF-8 code point. +Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars;
-int cp = unchecked::peek_next(w);
-assert (cp == 0x65e5);
+```
+char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars;
+int cp = unchecked::peek_next(w);
+assert (cp == 0x65e5);
 assert (w == twochars);
-
+``` This is a faster but less safe version of `utf8::peek_next`. It does not check for validity of the supplied UTF-8 sequence. @@ -823,22 +804,23 @@ Available in version 1.02 and later. Given 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. -
template <typename octet_iterator>
+```
+template 
 uint32_t prior(octet_iterator& it);
-
-
+``` `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. - Return value: the 32 bit representation of the previous code point. + Return value: the 32 bit representation of the previous code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars + 3;
-int cp = unchecked::prior (w);
-assert (cp == 0x65e5);
+```
+char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars + 3;
+int cp = unchecked::prior (w);
+assert (cp == 0x65e5);
 assert (w == twochars);
-
+``` This 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. @@ -848,22 +830,23 @@ Deprecated in version 1.02 and later. Given 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. -
template <typename octet_iterator>
+```
+template 
 uint32_t previous(octet_iterator& it);
-
-
+``` `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. - Return value: the 32 bit representation of the previous code point. +Return value: the 32 bit representation of the previous code point. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars + 3;
-int cp = unchecked::previous (w);
-assert (cp == 0x65e5);
+```
+char* twochars = "\xe6\x97\xa5\xd1\x88";
+char* w = twochars + 3;
+int cp = unchecked::previous (w);
+assert (cp == 0x65e5);
 assert (w == twochars);
-
+``` The 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` @@ -875,21 +858,22 @@ Available in version 1.0 and later. Advances an iterator by the specified number of code points within an UTF-8 sequence. -
template <typename octet_iterator, typename distance_type>
-void advance (octet_iterator& it, distance_type n);
-
-
+``` +template +void advance (octet_iterator& it, distance_type n); +``` `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. - `n`: a positive integer that shows how many code points we want to advance. +`n`: a positive integer that shows how many code points we want to advance. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-char* w = twochars;
-unchecked::advance (w, 2);
-assert (w == twochars + 5);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +char* w = twochars; +unchecked::advance (w, 2); +assert (w == twochars + 5); +``` This function works only "forward". In case of a negative `n`, there is no effect. @@ -901,20 +885,22 @@ Available in version 1.0 and later. Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them. -
template <typename octet_iterator>
-typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last);
-
+``` +template +typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last); +``` `first`: an iterator to a beginning of a UTF-8 encoded code point. - `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. - Return value the distance between the iterators, in code points. +`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. +Return value: the distance between the iterators, in code points. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-size_t dist = utf8::unchecked::distance(twochars, twochars + 5);
-assert (dist == 2);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +size_t dist = utf8::unchecked::distance(twochars, twochars + 5); +assert (dist == 2); +``` This is a faster but less safe version of `utf8::distance`. It does not check for validity of the supplied UTF-8 sequence. @@ -924,23 +910,24 @@ Available in version 1.0 and later. Converts a UTF-16 encoded string to UTF-8. -
template <typename u16bit_iterator, typename octet_iterator>
+```
+template 
 octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);
-
-
+``` `start`: an iterator pointing to the beginning of the UTF-16 encoded string to convert. - `end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert. - `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-8 string. +`end`: an iterator pointing to pass-the-end of the UTF-16 encoded string to convert. +`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -
unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
-vector<unsigned char> utf8result;
-unchecked::utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
-assert (utf8result.size() == 10);    
-
+``` +unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e}; +vector utf8result; +unchecked::utf16to8(utf16string, utf16string + 5, back_inserter(utf8result)); +assert (utf8result.size() == 10); +``` This is a faster but less safe version of `utf8::utf16to8`. It does not check for validity of the supplied UTF-16 sequence. @@ -950,24 +937,25 @@ Available in version 1.0 and later. Converts an UTF-8 encoded string to UTF-16 -
template <typename u16bit_iterator, typename octet_iterator>
+```
+template 
 u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result);
-
-
+``` `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. - `result`: an output iterator to the place in the UTF-16 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-16 string. +`result`: an output iterator to the place in the UTF-16 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-16 string. Example of use: -
char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e";
-vector <unsigned short> utf16result;
-unchecked::utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result));
-assert (utf16result.size() == 4);
-assert (utf16result[2] == 0xd834);
-assert (utf16result[3] == 0xdd1e);
-
+``` +char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e"; +vector utf16result; +unchecked::utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result)); +assert (utf16result.size() == 4); +assert (utf16result[2] == 0xd834); +assert (utf16result[3] == 0xdd1e); +``` This is a faster but less safe version of `utf8::utf8to16`. It does not check for validity of the supplied UTF-8 sequence. @@ -977,23 +965,24 @@ Available in version 1.0 and later. Converts a UTF-32 encoded string to UTF-8. -
template <typename octet_iterator, typename u32bit_iterator>
+```
+template 
 octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result);
-
-
+``` `start`: an iterator pointing to the beginning of the UTF-32 encoded string to convert. - `end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert. - `result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-8 string. +`end`: an iterator pointing to pass-the-end of the UTF-32 encoded string to convert. +`result`: an output iterator to the place in the UTF-8 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -
int utf32string[] = {0x448, 0x65e5, 0x10346, 0};
-vector<unsigned char> utf8result;
-utf32to8(utf32string, utf32string + 3, back_inserter(utf8result));
-assert (utf8result.size() == 9);
-
+``` +int utf32string[] = {0x448, 0x65e5, 0x10346, 0}; +vector utf8result; +utf32to8(utf32string, utf32string + 3, back_inserter(utf8result)); +assert (utf8result.size() == 9); +``` This is a faster but less safe version of `utf8::utf32to8`. It does not check for validity of the supplied UTF-32 sequence. @@ -1003,23 +992,24 @@ Available in version 1.0 and later. Converts a UTF-8 encoded string to UTF-32. -
template <typename octet_iterator, typename u32bit_iterator>
+```
+template 
 u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result);
-
-
+``` `start`: an iterator pointing to the beginning of the UTF-8 encoded string to convert. - `end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert. - `result`: an output iterator to the place in the UTF-32 string where to append the result of conversion. - Return value: An iterator pointing to the place after the appended UTF-32 string. +`end`: an iterator pointing to pass-the-end of the UTF-8 encoded string to convert. +`result`: an output iterator to the place in the UTF-32 string where to append the result of conversion. +Return value: An iterator pointing to the place after the appended UTF-32 string. Example of use: -
char* twochars = "\xe6\x97\xa5\xd1\x88";
-vector<int> utf32result;
-unchecked::utf8to32(twochars, twochars + 5, back_inserter(utf32result));
-assert (utf32result.size() == 2);
-
+``` +char* twochars = "\xe6\x97\xa5\xd1\x88"; +vector utf32result; +unchecked::utf8to32(twochars, twochars + 5, back_inserter(utf32result)); +assert (utf32result.size() == 2); +``` This is a faster but less safe version of `utf8::utf8to32`. It does not check for validity of the supplied UTF-8 sequence. @@ -1031,75 +1021,44 @@ Available in version 2.0 and later. Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets. -
template <typename octet_iterator>
-class iterator;
-
+``` +template +class iterator; +``` ##### Member functions -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
+`iterator();` the deafult constructor; the underlying octet_iterator is constructed with its default constructor. +`explicit iterator (const octet_iterator& octet_it);` a constructor that initializes the underlying octet_iterator with `octet_it` +`octet_iterator base () const;` returns the underlying octet_iterator. +`uint32_t operator * () const;` decodes the utf-8 sequence the underlying octet_iterator is pointing to and returns the code point. +`bool operator == (const iterator& rhs) const;` returns `true` if the two underlaying iterators are equal. +`bool operator != (const iterator& rhs) const;` returns `true` if the two underlaying iterators are not equal. +`iterator& operator ++ ();` the prefix increment - moves the iterator to the next UTF-8 encoded code point. +`iterator operator ++ (int);` the postfix increment - moves the iterator to the next UTF-8 encoded code point and returns the current one. +`iterator& operator -- ();` the prefix decrement - moves the iterator to the previous UTF-8 encoded code point. +`iterator operator -- (int);` the postfix decrement - moves the iterator to the previous UTF-8 encoded code point and returns the current one. Example of use: -
char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
-utf8::unchecked::iterator<char*> un_it(threechars);
-utf8::unchecked::iterator<char*> un_it2 = un_it;
+```
+char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88";
+utf8::unchecked::iterator un_it(threechars);
+utf8::unchecked::iterator un_it2 = un_it;
 assert (un_it2 == un_it);
-assert (*un_it == 0x10346);
-assert (*(++un_it) == 0x65e5);
-assert ((*un_it++) == 0x65e5);
-assert (*un_it == 0x0448);
+assert (*un_it == 0x10346);
+assert (*(++un_it) == 0x65e5);
+assert ((*un_it++) == 0x65e5);
+assert (*un_it == 0x0448);
 assert (un_it != un_it2);
-utf8::::unchecked::iterator<char*> un_endit (threechars + 9);  
+utf8::::unchecked::iterator un_endit (threechars + 9);  
 assert (++un_it == un_endit);
-assert (*(--un_it) == 0x0448);
-assert ((*un_it--) == 0x0448);
-assert (*un_it == 0x65e5);
-assert (--un_it == utf8::unchecked::iterator<char*>(threechars));
-assert (*un_it == 0x10346);
-
+assert (*(--un_it) == 0x0448); +assert ((*un_it--) == 0x0448); +assert (*un_it == 0x65e5); +assert (--un_it == utf8::unchecked::iterator(threechars)); +assert (*un_it == 0x10346); +``` This is an unchecked version of `utf8::iterator`. It is faster in many cases, but offers no validity or range checks. From 1cbc1877be5a005d9b6bc71e3693b8c9a754ff12 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Fri, 2 Oct 2015 18:56:06 -0400 Subject: [PATCH 04/18] Removing various infrastructure files --- buildrelease.pl | 18 ---- test_drivers/performance/Makefile | 5 - test_drivers/performance/iconvtest.cpp | 132 ------------------------- test_drivers/performance/timer.h | 22 ----- test_drivers/performance/win32.cpp | 110 --------------------- test_drivers/runtests.pl | 50 ---------- 6 files changed, 337 deletions(-) delete mode 100644 buildrelease.pl delete mode 100644 test_drivers/performance/Makefile delete mode 100644 test_drivers/performance/iconvtest.cpp delete mode 100644 test_drivers/performance/timer.h delete mode 100644 test_drivers/performance/win32.cpp delete mode 100644 test_drivers/runtests.pl diff --git a/buildrelease.pl b/buildrelease.pl deleted file mode 100644 index ed3a17bbe..000000000 --- a/buildrelease.pl +++ /dev/null @@ -1,18 +0,0 @@ -#! /usr/bin/perl - -$release_files = 'source/utf8.h source/utf8/core.h source/utf8/checked.h source/utf8/unchecked.h doc/utf8cpp.html doc/ReleaseNotes'; - -# First get the latest version -`svn update`; - -# Then construct the name of the zip file -$argc = @ARGV; -if ($argc > 0) { - $zip_name = $ARGV[0]; -} -else { - $zip_name = "utf8"; -} - -# Zip the files to an archive -`zip $zip_name $release_files`; diff --git a/test_drivers/performance/Makefile b/test_drivers/performance/Makefile deleted file mode 100644 index b38544506..000000000 --- a/test_drivers/performance/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -CC = g++ -CFLAGS = -O3 - -iconvtest: iconvtest.cpp ../../source/utf8.h timer.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h - $(CC) $(CFLAGS) iconvtest.cpp -oiconvtest diff --git a/test_drivers/performance/iconvtest.cpp b/test_drivers/performance/iconvtest.cpp deleted file mode 100644 index 95e73e747..000000000 --- a/test_drivers/performance/iconvtest.cpp +++ /dev/null @@ -1,132 +0,0 @@ -#include -#include -#include "../../source/utf8.h" -#include "timer.h" -#include -#include -#include -using namespace std; - -using namespace utf8; - -int main(int argc, char** argv) -{ - if (argc != 2) { - cout << "\nUsage: iconvtest filename\n"; - return 0; - } - const char* test_file_path = argv[1]; - // Open the test file (UTF-8 encoded text) - ifstream fs8(test_file_path, ios::binary); - if (!fs8.is_open()) { - cout << "Could not open " << test_file_path << endl; - return 0; - } - // get length - fs8.seekg(0, ios::end); - int length = fs8.tellg(); - fs8.seekg(0, ios::beg); - - // allocate the buffer (no vector - we are benchmarking conversions, not STL - char* buf = new char[length]; - char* end_buf = buf + length; - // fill the data - fs8.read(buf, length); - fs8.close(); - // the UTF-16 result will not be larger than this (I hope :) ) - vector temputf16; - utf8::utf8to16(buf, end_buf, back_inserter(temputf16)); - int wlength = temputf16.size(); - unsigned short* utf16buf = new unsigned short[wlength]; - - cout << "UTF8 to UTF-16\n"; - { - memset (utf16buf, 0 , wlength * sizeof(unsigned short)); - // utf-8 cpp: - cout << "utf8::utf8to16: "; - timer t(cout); - utf8::utf8to16(buf, buf + length, utf16buf); - t.print_time(); - } - - { - memset (utf16buf, 0 , wlength * sizeof(unsigned short)); - // utf-8 cpp: - cout << "unchecked::utf8to16: "; - timer t(cout); - utf8::unchecked::utf8to16(buf, buf + length, utf16buf); - t.print_time(); - } - - // the UTF-16 result will not be larger than this (I hope :) ) - unsigned short* utf16iconvbuf = new unsigned short[wlength]; - { - memset (utf16iconvbuf, 0 , wlength * sizeof(unsigned short)); - // iconv - cout << "iconv: "; - - iconv_t cd = iconv_open("UTF-16LE", "UTF-8"); - if (cd == iconv_t(-1)) { - cout << "Error openning the iconv stream"; - return 0; - } - char* inbuf = buf; - size_t in_bytes_left = length; - char* outbuf = (char*)utf16iconvbuf; - size_t out_bytes_left = wlength * sizeof (unsigned short); - { - timer t(cout); - iconv(cd, &inbuf, &in_bytes_left, &outbuf, &out_bytes_left); - t.print_time(); - } - iconv_close(cd); - } - - // just check the correctness while we are here: - if (!equal(utf16buf, utf16buf + wlength, utf16iconvbuf)) - cout << "Different result!!!\n"; - - // the other way around - cout << "UTF16 to UTF-8\n"; - { - //iconv - memset(buf, 0, length); - cout<< "iconv: "; - - iconv_t cd = iconv_open("UTF-8", "UTF-16LE"); - if (cd == iconv_t(-1)) { - cout << "Error openning the iconv stream"; - return 0; - } - char* inbuf = (char*)utf16buf; - size_t in_bytes_left = wlength * sizeof(unsigned short); - char* outbuf =buf; - size_t out_bytes_left = length; - { - timer t(cout); - iconv(cd, &inbuf, &in_bytes_left, &outbuf, &out_bytes_left); - t.print_time(); - } - iconv_close(cd); - } - - { - memset (buf, 0 , length); - // utf-8 cpp: - cout << "unchecked::utf16to8: "; - timer t(cout); - utf8::unchecked::utf16to8(utf16buf, utf16buf + wlength, buf); - t.print_time(); - } - - { - memset (buf, 0 , length); - cout << "utf16to8: "; - timer t(cout); - utf8::utf16to8(utf16buf, utf16buf + wlength, buf); - t.print_time(); - } - - delete [] buf; - delete [] utf16buf; -} diff --git a/test_drivers/performance/timer.h b/test_drivers/performance/timer.h deleted file mode 100644 index 807752317..000000000 --- a/test_drivers/performance/timer.h +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include -struct timer { - timer(std::ostream& report) : report(report) - {start = std::clock();} - - void print_time() - { - using namespace std; - clock_t now = clock(); - unsigned milliseconds = (now - start)*1000 / CLOCKS_PER_SEC; - report << "Spent " << milliseconds << "ms here\n"; - } - - std::clock_t start; - std::ostream& report; - -private: - // just to surpress a VC++ 8.0 warning - timer& operator = (const timer&); - timer(const timer&); -}; diff --git a/test_drivers/performance/win32.cpp b/test_drivers/performance/win32.cpp deleted file mode 100644 index 3ec861a26..000000000 --- a/test_drivers/performance/win32.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include "../../source/utf8.h" -#include "timer.h" -#include -#include -#include -using namespace std; - -using namespace utf8; - -int main(int argc, char** argv) -{ - if (argc != 2) { - cout << "\nUsage: win32test filename\n"; - return 0; - } - const char* test_file_path = argv[1]; - // Open the test file (UTF-8 encoded text) - ifstream fs8(test_file_path, ios::binary); - if (!fs8.is_open()) { - cout << "Could not open " << test_file_path << endl; - return 0; - } - // get length - fs8.seekg(0, ios::end); - int length = fs8.tellg(); - fs8.seekg(0, ios::beg); - - // allocate the buffer (no vector - we are benchmarking conversions, not STL - char* buf = new char[length]; - // fill the data - fs8.read(buf, length); - fs8.close(); - cout << "UTF8 > UTF16\n"; - // the UTF-16 result will not be larger than this (I hope :) ) - vector temputf16; - utf8::utf8to16(buf, buf + length, back_inserter(temputf16)); - vector::size_type wlength = temputf16.size(); - wchar_t* utf16buf = new wchar_t[wlength]; - - { - memset (utf16buf, 0 , wlength * sizeof(wchar_t)); - // utf-8 cpp: - cout << "utf8::utf8to16: "; - timer t(cout); - utf8::utf8to16(buf, buf + length, utf16buf); - t.print_time(); - } - - { - memset (utf16buf, 0 , wlength * sizeof(wchar_t)); - // utf-8 cpp: - cout << "unchecked::utf8to16: "; - timer t(cout); - utf8::unchecked::utf8to16(buf, buf + length, utf16buf); - t.print_time(); - } - // the UTF-16 result will not be larger than this (I hope :) ) - wchar_t* utf16iconvbuf = new wchar_t[wlength]; - { - memset (utf16iconvbuf, 0 , wlength * sizeof(wchar_t)); - // win32 - cout << "win32: "; - - { - timer t(cout); - MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, buf, length, utf16iconvbuf, int(wlength)); - t.print_time(); - } - - } - - // just check the correctness while we are here: - if (!equal(utf16buf, utf16buf + wlength, utf16iconvbuf)) - cout << "Different result!!!"; - - // the other way around - cout << "UTF16 to UTF-8\n"; - { - //win32 - memset(buf, 0, length); - cout<< "win32: "; - - { - timer t(cout); - WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, utf16buf, int(wlength), buf, length, NULL, NULL); - t.print_time(); - } - } - - { - memset (buf, 0 , length); - // utf-8 cpp: - cout << "unchecked::utf16to8: "; - timer t(cout); - utf8::unchecked::utf16to8(utf16buf, utf16buf + wlength, buf); - t.print_time(); - } - - { - memset (buf, 0 , length); - cout << "utf16to8: "; - timer t(cout); - utf8::utf16to8(utf16buf, utf16buf + wlength, buf); - t.print_time(); - } - - delete [] buf; - delete [] utf16buf; -} diff --git a/test_drivers/runtests.pl b/test_drivers/runtests.pl deleted file mode 100644 index 7d63f1843..000000000 --- a/test_drivers/runtests.pl +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/bin/perl - -$report_name = './report.txt'; - -# Create the report file -die if !open(REPORT, ">$report_name"); - -# First, build everything -print REPORT "==================Make output==================\n"; -close($report_name); - -`make >> $report_name`; -die if !open(REPORT, ">>$report_name"); -print REPORT "==================End of Make output==================\n"; -print REPORT "\n"; -# Now, run individual tests and create the report -print REPORT "==================Smoke Test ==================\n"; -close($report_name); -chdir 'smoke_test'; -`./smoketest >> ../$report_name`; -chdir '..'; -die if !open(REPORT, ">>$report_name"); -print REPORT "==================End of smoke test==================\n"; -print REPORT "\n"; -print REPORT "==================Regression Test ==================\n"; -close($report_name); -chdir 'regression_tests'; -`./regressiontest >> ../$report_name`; -chdir '..'; -die if !open(REPORT, ">>$report_name"); -print REPORT "==================End of regression test==================\n"; -print REPORT "\n"; -print REPORT "==================Negative Test ==================\n"; -close($report_name); -chdir 'negative'; -`./negative ../../test_data/negative/utf8_invalid.txt >> ../$report_name`; -chdir '..'; -die if !open(REPORT, ">>$report_name"); -print REPORT "==================End of negative test==================\n"; -print REPORT "\n"; -print REPORT "==================utf8reader runs ==================\n"; -close($report_name); -chdir 'utf8reader'; -`./utf8reader ../../test_data/utf8samples/quickbrown.txt >> ../$report_name`; -`./utf8reader ../../test_data/utf8samples/Unicode_transcriptions.html >> ../$report_name`; -`./utf8reader ../../test_data/utf8samples/UTF-8-demo.txt >> ../$report_name`; -chdir '..'; -die if !open(REPORT, ">>$report_name"); -print REPORT "==================End of utf8reader runs==================\n"; -print REPORT "\n"; From 2620091238a08f6e59456d030a606cb296dd7141 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 17 Oct 2015 20:16:06 -0400 Subject: [PATCH 05/18] Initial CMake files --- CMakeLists.txt | 5 +++++ samples/CMakeLists.txt | 1 + 2 files changed, 6 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 samples/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..4a23de7a6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,5 @@ +cmake_minimum_required (VERSION 2.6) +project (utf8cpp) + +include_directories ("${PROJECT_SOURCE_DIR}/source") +add_subdirectory (samples) diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt new file mode 100644 index 000000000..255e01cd4 --- /dev/null +++ b/samples/CMakeLists.txt @@ -0,0 +1 @@ +add_executable (sample docsample.cpp) From f029fcc2fbc7cd979925f198f7e6ca8170d45000 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 17 Oct 2015 20:41:24 -0400 Subject: [PATCH 06/18] CMake for negative test --- CMakeLists.txt | 3 ++- test_drivers/CMakeLists.txt | 1 + test_drivers/negative/CMakeLists.txt | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 test_drivers/CMakeLists.txt create mode 100644 test_drivers/negative/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 4a23de7a6..49c9fade2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,4 +2,5 @@ cmake_minimum_required (VERSION 2.6) project (utf8cpp) include_directories ("${PROJECT_SOURCE_DIR}/source") -add_subdirectory (samples) +add_subdirectory (samples) +add_subdirectory (test_drivers) diff --git a/test_drivers/CMakeLists.txt b/test_drivers/CMakeLists.txt new file mode 100644 index 000000000..78822a140 --- /dev/null +++ b/test_drivers/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory (negative) diff --git a/test_drivers/negative/CMakeLists.txt b/test_drivers/negative/CMakeLists.txt new file mode 100644 index 000000000..f0d5e1565 --- /dev/null +++ b/test_drivers/negative/CMakeLists.txt @@ -0,0 +1 @@ +add_executable (negative negative.cpp) \ No newline at end of file From 4ddacd67dc588001a34b6f065a6bfb0c36d03d37 Mon Sep 17 00:00:00 2001 From: Muhammad Mominul Huque Date: Tue, 29 Dec 2015 03:18:50 +0600 Subject: [PATCH 07/18] Syntax Highlighting --- README.md | 138 +++++++++++++++++++++++++++--------------------------- 1 file changed, 69 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 108216080..e8f915533 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ The purpose of this article is not to offer an introduction to Unicode in genera To 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: -``` +```cpp #include #include #include @@ -76,7 +76,7 @@ In the previous code sample, for each line we performed a detection of invalid U Here is a function that checks whether the content of a file is valid UTF-8 encoded text without reading the content into the memory: -``` +```cpp bool valid_utf8_file(const char* file_name) { ifstream ifs(file_name); @@ -94,7 +94,7 @@ Because the function `utf8::is_valid()` works with input iterators, we were able Note 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: -``` +```cpp utf8::utf8to16(it, eos, back_inserter(u16string)); ``` @@ -102,7 +102,7 @@ Note that other functions that take input iterator arguments can be used in a si If 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: -``` +```cpp void fix_utf8_string(std::string& str) { std::string temp; @@ -123,7 +123,7 @@ Available in version 1.0 and later. Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string. -``` +```cpp template octet_iterator append(uint32_t cp, octet_iterator result); ``` @@ -135,7 +135,7 @@ Return value: an iterator pointing to the place after the newly appended sequenc Example of use: -``` +```cpp unsigned char u[5] = {0,0,0,0,0}; unsigned char* end = append(0x0448, u); assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0); @@ -151,7 +151,7 @@ Available in version 1.0 and later. Given the iterator to the beginning of the UTF-8 sequence, it returns the code point and moves the iterator to the next position. -``` +```cpp template uint32_t next(octet_iterator& it, octet_iterator end); ``` @@ -163,7 +163,7 @@ Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars; int cp = next(w, twochars + 6); @@ -181,7 +181,7 @@ Available in version 2.1 and later. Given 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. -``` +```cpp template uint32_t peek_next(octet_iterator it, octet_iterator end); ``` @@ -194,7 +194,7 @@ Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars; int cp = peek_next(w, twochars + 6); @@ -210,7 +210,7 @@ Available in version 1.02 and later. Given 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. -``` +```cpp template uint32_t prior(octet_iterator& it, octet_iterator start); ``` @@ -222,7 +222,7 @@ uint32_t prior(octet_iterator& it, octet_iterator start); Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; unsigned char* w = twochars + 3; int cp = prior (w, twochars); @@ -244,7 +244,7 @@ Deprecated in version 1.02 and later. Given 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. -``` +```cpp template uint32_t previous(octet_iterator& it, octet_iterator pass_start); ``` @@ -256,7 +256,7 @@ Return value: the 32 bit representation of the previous code point. Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; unsigned char* w = twochars + 3; int cp = previous (w, twochars - 1); @@ -276,7 +276,7 @@ Available in version 1.0 and later. Advances an iterator by the specified number of code points within an UTF-8 sequence. -``` +```cpp template void advance (octet_iterator& it, distance_type n, octet_iterator end); ``` @@ -289,7 +289,7 @@ void advance (octet_iterator& it, distance_type n, octet_iterator end); Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; unsigned char* w = twochars; advance (w, 2, twochars + 6); @@ -306,7 +306,7 @@ Available in version 1.0 and later. Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them. -``` +```cpp template typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last); ``` @@ -318,7 +318,7 @@ typename std::iterator_traits::difference_type distance (octet_i Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; size_t dist = utf8::distance(twochars, twochars + 5); assert (dist == 2); @@ -334,7 +334,7 @@ Available in version 1.0 and later. Converts a UTF-16 encoded string to UTF-8. -``` +```cpp template octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result); ``` @@ -348,7 +348,7 @@ Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -``` +```cpp unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e}; vector utf8result; utf16to8(utf16string, utf16string + 5, back_inserter(utf8result)); @@ -363,7 +363,7 @@ Available in version 1.0 and later. Converts an UTF-8 encoded string to UTF-16 -``` +```cpp template u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result); ``` @@ -376,7 +376,7 @@ Return value: An iterator pointing to the place after the appended UTF-16 string Example of use: -``` +```cpp char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e"; vector utf16result; utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result)); @@ -393,7 +393,7 @@ Available in version 1.0 and later. Converts a UTF-32 encoded string to UTF-8. -``` +```cpp template octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result); ``` @@ -422,7 +422,7 @@ Available in version 1.0 and later. Converts a UTF-8 encoded string to UTF-32. -``` +```cpp template u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result); ``` @@ -436,7 +436,7 @@ Return value: An iterator pointing to the place after the appended UTF-32 string Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; vector utf32result; utf8to32(twochars, twochars + 5, back_inserter(utf32result)); @@ -451,7 +451,7 @@ Available in version 1.0 and later. Detects an invalid sequence within a UTF-8 string. -``` +```cpp template octet_iterator find_invalid(octet_iterator start, octet_iterator end); ``` @@ -463,7 +463,7 @@ Return value: an iterator pointing to the first invalid octet in the UTF-8 strin Example of use: -``` +```cpp char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa"; char* invalid = find_invalid(utf_invalid, utf_invalid + 6); assert (invalid == utf_invalid + 5); @@ -477,7 +477,7 @@ Available in version 1.0 and later. Checks whether a sequence of octets is a valid UTF-8 string. -``` +```cpp template bool is_valid(octet_iterator start, octet_iterator end); ``` @@ -489,7 +489,7 @@ Return value: `true` if the sequence is a valid UTF-8 string; `false` if not. Example of use: -``` +```cpp char utf_invalid[] = "\xe6\x97\xa5\xd1\x88\xfa"; bool bvalid = is_valid(utf_invalid, utf_invalid + 6); assert (bvalid == false); @@ -503,7 +503,7 @@ Available in version 2.0 and later. Replaces all invalid UTF-8 sequences within a string with a replacement marker. -``` +```cpp template output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement); template @@ -520,7 +520,7 @@ Return value: An iterator pointing to the place after the UTF-8 string with repl Example of use: -``` +```cpp char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z"; vector replace_invalid_result; replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), back_inserter(replace_invalid_result), '?'); @@ -540,7 +540,7 @@ Available in version 2.3 and later. Relaces deprecated `is_bom()` function. Checks whether an octet sequence starts with a UTF-8 byte order mark (BOM) -``` +```cpp template bool starts_with_bom (octet_iterator it, octet_iterator end); ``` @@ -552,7 +552,7 @@ Return value: `true` if the sequence starts with a UTF-8 byte order mark; `false Example of use: -``` +```cpp unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf}; bool bbom = starts_with_bom(byte_order_mark, byte_order_mark + sizeof(byte_order_mark)); assert (bbom == true); @@ -566,7 +566,7 @@ Available in version 1.0 and later. Deprecated in version 2.3\. `starts_with_bom Checks whether a sequence of three octets is a UTF-8 byte order mark (BOM) -``` +```cpp template bool is_bom (octet_iterator it); // Deprecated ``` @@ -577,7 +577,7 @@ Return value: `true` if the sequence is UTF-8 byte order mark; `false` if not. Example of use: -``` +```cpp unsigned char byte_order_mark[] = {0xef, 0xbb, 0xbf}; bool bbom = is_bom(byte_order_mark); assert (bbom == true); @@ -595,13 +595,13 @@ Available in version 2.3 and later. Base class for the exceptions thrown by UTF CPP library functions. -``` +```cpp class exception : public std::exception {}; ``` Example of use: -``` +```cpp try { code_that_uses_utf_cpp_library(); } @@ -616,7 +616,7 @@ Available in version 1.0 and later. Thrown by UTF8 CPP functions such as `advance` and `next` if an UTF-8 sequence represents and invalid code point. -``` +```cpp class invalid_code_point : public exception { public: uint32_t code_point() const; @@ -631,7 +631,7 @@ Available in version 1.0 and later. Thrown by UTF8 CPP functions such as `next` and `prior` if an invalid UTF-8 sequence is detected during decoding. -``` +```cpp class invalid_utf8 : public exception { public: uint8_t utf8_octet() const; @@ -646,7 +646,7 @@ Available in version 1.0 and later. Thrown by UTF8 CPP function `utf16to8` if an invalid UTF-16 sequence is detected during decoding. -``` +```cpp class invalid_utf16 : public exception { public: uint16_t utf16_word() const; @@ -661,7 +661,7 @@ Available in version 1.0 and later. Thrown by UTF8 CPP functions such as `next` if the end of the decoded UTF-8 sequence was reached before the code point was decoded. -``` +```cpp class not_enough_room : public exception {}; ``` @@ -671,7 +671,7 @@ Available in version 2.0 and later. Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets. -``` +```cpp template class iterator; ``` @@ -691,7 +691,7 @@ class iterator; Example of use: -``` +```cpp char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88"; utf8::iterator it(threechars, threechars, threechars + 9); utf8::iterator it2 = it; @@ -714,7 +714,7 @@ The purpose of `utf8::iterator` adapter is to enable easy iteration as well as t Note 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.: -``` +```cpp std::string s = "example"; utf8::iterator i (s.begin(), s.begin(), s.end()); ``` @@ -727,7 +727,7 @@ Available in version 1.0 and later. Encodes a 32 bit code point as a UTF-8 sequence of octets and appends the sequence to a UTF-8 string. -``` +```cpp template octet_iterator append(uint32_t cp, octet_iterator result); ``` @@ -738,7 +738,7 @@ Return value: An iterator pointing to the place after the newly appended sequenc Example of use: -``` +```cpp unsigned char u[5] = {0,0,0,0,0}; unsigned char* end = unchecked::append(0x0448, u); assert (u[0] == 0xd1 && u[1] == 0x88 && u[2] == 0 && u[3] == 0 && u[4] == 0); @@ -752,7 +752,7 @@ Available in version 1.0 and later. Given the iterator to the beginning of a UTF-8 sequence, it returns the code point and moves the iterator to the next position. -``` +```cpp template uint32_t next(octet_iterator& it); ``` @@ -762,7 +762,7 @@ uint32_t next(octet_iterator& it); Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars; int cp = unchecked::next(w); @@ -778,7 +778,7 @@ Available in version 2.1 and later. Given the iterator to the beginning of a UTF-8 sequence, it returns the code point. -``` +```cpp template uint32_t peek_next(octet_iterator it); ``` @@ -788,7 +788,7 @@ Return value: the 32 bit representation of the processed UTF-8 code point. Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars; int cp = unchecked::peek_next(w); @@ -804,7 +804,7 @@ Available in version 1.02 and later. Given 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. -``` +```cpp template uint32_t prior(octet_iterator& it); ``` @@ -814,7 +814,7 @@ uint32_t prior(octet_iterator& it); Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars + 3; int cp = unchecked::prior (w); @@ -830,7 +830,7 @@ Deprecated in version 1.02 and later. Given 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. -``` +```cpp template uint32_t previous(octet_iterator& it); ``` @@ -840,7 +840,7 @@ Return value: the 32 bit representation of the previous code point. Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars + 3; int cp = unchecked::previous (w); @@ -858,7 +858,7 @@ Available in version 1.0 and later. Advances an iterator by the specified number of code points within an UTF-8 sequence. -``` +```cpp template void advance (octet_iterator& it, distance_type n); ``` @@ -868,7 +868,7 @@ void advance (octet_iterator& it, distance_type n); Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; char* w = twochars; unchecked::advance (w, 2); @@ -885,7 +885,7 @@ Available in version 1.0 and later. Given the iterators to two UTF-8 encoded code points in a seqence, returns the number of code points between them. -``` +```cpp template typename std::iterator_traits::difference_type distance (octet_iterator first, octet_iterator last); ``` @@ -896,7 +896,7 @@ Return value: the distance between the iterators, in code points. Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; size_t dist = utf8::unchecked::distance(twochars, twochars + 5); assert (dist == 2); @@ -910,7 +910,7 @@ Available in version 1.0 and later. Converts a UTF-16 encoded string to UTF-8. -``` +```cpp template octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result); ``` @@ -922,7 +922,7 @@ Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -``` +```cpp unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e}; vector utf8result; unchecked::utf16to8(utf16string, utf16string + 5, back_inserter(utf8result)); @@ -937,7 +937,7 @@ Available in version 1.0 and later. Converts an UTF-8 encoded string to UTF-16 -``` +```cpp template u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result); ``` @@ -948,7 +948,7 @@ Return value: An iterator pointing to the place after the appended UTF-16 string Example of use: -``` +```cpp char utf8_with_surrogates[] = "\xe6\x97\xa5\xd1\x88\xf0\x9d\x84\x9e"; vector utf16result; unchecked::utf8to16(utf8_with_surrogates, utf8_with_surrogates + 9, back_inserter(utf16result)); @@ -965,7 +965,7 @@ Available in version 1.0 and later. Converts a UTF-32 encoded string to UTF-8. -``` +```cpp template octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result); ``` @@ -977,7 +977,7 @@ Return value: An iterator pointing to the place after the appended UTF-8 string. Example of use: -``` +```cpp int utf32string[] = {0x448, 0x65e5, 0x10346, 0}; vector utf8result; utf32to8(utf32string, utf32string + 3, back_inserter(utf8result)); @@ -992,7 +992,7 @@ Available in version 1.0 and later. Converts a UTF-8 encoded string to UTF-32. -``` +```cpp template u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result); ``` @@ -1004,7 +1004,7 @@ Return value: An iterator pointing to the place after the appended UTF-32 string Example of use: -``` +```cpp char* twochars = "\xe6\x97\xa5\xd1\x88"; vector utf32result; unchecked::utf8to32(twochars, twochars + 5, back_inserter(utf32result)); @@ -1021,7 +1021,7 @@ Available in version 2.0 and later. Adapts the underlying octet iterator to iterate over the sequence of code points, rather than raw octets. -``` +```cpp template class iterator; ``` @@ -1041,7 +1041,7 @@ class iterator; Example of use: -``` +```cpp char* threechars = "\xf0\x90\x8d\x86\xe6\x97\xa5\xd1\x88"; utf8::unchecked::iterator un_it(threechars); utf8::unchecked::iterator un_it2 = un_it; @@ -1087,4 +1087,4 @@ In case you want to look into other means of working with UTF-8 strings from C++ 1. [The Unicode Consortium](http://www.unicode.org/). 2. [ICU Library](http://icu.sourceforge.net/). 3. [UTF-8 at Wikipedia](http://en.wikipedia.org/wiki/UTF-8) -4. [UTF-8 and Unicode FAQ for Unix/Linux](http://www.cl.cam.ac.uk/~mgk25/unicode.html) \ No newline at end of file +4. [UTF-8 and Unicode FAQ for Unix/Linux](http://www.cl.cam.ac.uk/~mgk25/unicode.html) From 9d52bc19dc48523bb8c44fd4a86cefc70676379a Mon Sep 17 00:00:00 2001 From: Greg Hewgill Date: Wed, 28 Sep 2016 13:32:08 +1300 Subject: [PATCH 08/18] Check for end iterator before using iterator If it == end, then sequence_length(it) will be called which will attempt to dereference the it iterator. This is normally harmless, because the get_sequence_x() functions each check to see whether it == end. However, some runtime libraries (MSVC CRT debug build in particular) check the validity of every iterator dereference, and a runtime check will be triggered inside sequence_length() if it is at the end. --- source/utf8/core.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source/utf8/core.h b/source/utf8/core.h index 693d388c0..ae0f367db 100644 --- a/source/utf8/core.h +++ b/source/utf8/core.h @@ -222,6 +222,9 @@ namespace internal template utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point) { + if (it == end) + return NOT_ENOUGH_ROOM; + // Save the original value of it so we can go back in case of failure // Of course, it does not make much sense with i.e. stream iterators octet_iterator original_it = it; From 67036a031d131b5a929a525677e4356850fa4e37 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 5 Nov 2016 18:46:04 -0400 Subject: [PATCH 09/18] Consolidate CMakeLists.txt The build has only one CMakeLists.txt now. Added support for CTest --- CMakeLists.txt | 15 +++++++++++---- samples/CMakeLists.txt | 1 - samples/Makefile | 5 ----- test_drivers/CMakeLists.txt | 1 - test_drivers/Makefile | 19 ------------------- test_drivers/negative/CMakeLists.txt | 1 - test_drivers/negative/Makefile | 5 ----- test_drivers/smoke_test/Makefile | 5 ----- test_drivers/utf8reader/Makefile | 5 ----- 9 files changed, 11 insertions(+), 46 deletions(-) delete mode 100644 samples/CMakeLists.txt delete mode 100644 samples/Makefile delete mode 100644 test_drivers/CMakeLists.txt delete mode 100644 test_drivers/Makefile delete mode 100644 test_drivers/negative/CMakeLists.txt delete mode 100644 test_drivers/negative/Makefile delete mode 100644 test_drivers/smoke_test/Makefile delete mode 100644 test_drivers/utf8reader/Makefile diff --git a/CMakeLists.txt b/CMakeLists.txt index 49c9fade2..667d2881d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,13 @@ -cmake_minimum_required (VERSION 2.6) +cmake_minimum_required (VERSION 2.8.0) project (utf8cpp) - include_directories ("${PROJECT_SOURCE_DIR}/source") -add_subdirectory (samples) -add_subdirectory (test_drivers) + +add_executable(smoke ${PROJECT_SOURCE_DIR}/test_drivers/smoke_test/test.cpp) +add_executable(negative ${PROJECT_SOURCE_DIR}/test_drivers/negative/negative.cpp) +add_executable(utf8reader ${PROJECT_SOURCE_DIR}/test_drivers/utf8reader/utf8reader.cpp) + +add_executable(docsample ${PROJECT_SOURCE_DIR}/samples/docsample.cpp) + +enable_testing() +add_test(smoke_test smoke) +add_test(negative_test negative ${PROJECT_SOURCE_DIR}/test_data/negative/utf8_invalid.txt) diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt deleted file mode 100644 index 255e01cd4..000000000 --- a/samples/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_executable (sample docsample.cpp) diff --git a/samples/Makefile b/samples/Makefile deleted file mode 100644 index 6cdd3c859..000000000 --- a/samples/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -CC = g++ -CFLAGS = -g -Wall -pedantic - -docsample: docsample.cpp ../source/utf8.h - $(CC) $(CFLAGS) docsample.cpp -odocsample diff --git a/test_drivers/CMakeLists.txt b/test_drivers/CMakeLists.txt deleted file mode 100644 index 78822a140..000000000 --- a/test_drivers/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory (negative) diff --git a/test_drivers/Makefile b/test_drivers/Makefile deleted file mode 100644 index a2cbe4c2e..000000000 --- a/test_drivers/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -CC = g++ -CFLAGS = -g - -all: smoketest regressiontest negativetest utf8readertest - -smoketest: - cd smoke_test && $(MAKE) $@ - -regressiontest: - cd regression_tests && $(MAKE) $@ - -negativetest: - cd negative && $(MAKE) $@ - -utf8readertest: - cd utf8reader && $(MAKE) $@ - -clean: - rm smoke_test/smoketest regression_tests/regressiontest negative/negative utf8reader/utf8reader diff --git a/test_drivers/negative/CMakeLists.txt b/test_drivers/negative/CMakeLists.txt deleted file mode 100644 index f0d5e1565..000000000 --- a/test_drivers/negative/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_executable (negative negative.cpp) \ No newline at end of file diff --git a/test_drivers/negative/Makefile b/test_drivers/negative/Makefile deleted file mode 100644 index 00f4a7d31..000000000 --- a/test_drivers/negative/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -CC = g++ -CFLAGS = -g -Wall -pedantic - -negativetest: negative.cpp ../../source/utf8.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h - $(CC) $(CFLAGS) negative.cpp -onegative diff --git a/test_drivers/smoke_test/Makefile b/test_drivers/smoke_test/Makefile deleted file mode 100644 index f66f3af95..000000000 --- a/test_drivers/smoke_test/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -CC = g++ -CFLAGS = -g -Wall - -smoketest: test.cpp ../../source/utf8.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h - $(CC) $(CFLAGS) test.cpp -osmoketest diff --git a/test_drivers/utf8reader/Makefile b/test_drivers/utf8reader/Makefile deleted file mode 100644 index 29a9aa886..000000000 --- a/test_drivers/utf8reader/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -CC = g++ -CFLAGS = -g -Wall -pedantic - -utf8readertest: utf8reader.cpp ../../source/utf8.h ../../source/utf8/core.h ../../source/utf8/checked.h ../../source/utf8/unchecked.h - $(CC) $(CFLAGS) utf8reader.cpp -o utf8reader From 5408022bd69cb0a0a792ed13747743d1410f6e18 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 5 Nov 2016 18:58:26 -0400 Subject: [PATCH 10/18] Fix -Wshadow warnings Fix the GNU and CLang's -Wshadow warning by renaming the input parameters. --- source/utf8/checked.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/utf8/checked.h b/source/utf8/checked.h index cc1ec4777..2aef5838d 100644 --- a/source/utf8/checked.h +++ b/source/utf8/checked.h @@ -1,4 +1,4 @@ -// Copyright 2006 Nemanja Trifunovic +// Copyright 2006-2016 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization @@ -41,7 +41,7 @@ namespace utf8 class invalid_code_point : public exception { uint32_t cp; public: - invalid_code_point(uint32_t cp) : cp(cp) {} + invalid_code_point(uint32_t codepoint) : cp(codepoint) {} virtual const char* what() const throw() { return "Invalid code point"; } uint32_t code_point() const {return cp;} }; @@ -272,9 +272,9 @@ namespace utf8 public: iterator () {} explicit iterator (const octet_iterator& octet_it, - const octet_iterator& range_start, - const octet_iterator& range_end) : - it(octet_it), range_start(range_start), range_end(range_end) + const octet_iterator& rangestart, + const octet_iterator& rangeend) : + it(octet_it), range_start(rangestart), range_end(rangeend) { if (it < range_start || it > range_end) throw std::out_of_range("Invalid utf-8 iterator position"); From 0232ab8188b16ae6f2293a5817f1d9b0030879a3 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 5 Nov 2016 19:34:38 -0400 Subject: [PATCH 11/18] Minor documentation update. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e8f915533..d4369e85d 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Many 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. -In order to easily handle UTF-8 encoded Unicode strings, I came up with a small 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. If you run into bugs or performance issues, please let me know and I'll do my best to address them. +In 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. The 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. @@ -1069,7 +1069,7 @@ This is an unchecked version of `utf8::iterator`. It is faster in many cases, bu The library was designed to be: 1. 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. -2. 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. +2. 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. 3. Lightweight: follow the "pay only for what you use" guideline. 4. Unintrusive: avoid forcing any particular design or even programming style on the user. This is a library, not a framework. @@ -1078,7 +1078,7 @@ The library was designed to be: In 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: 1. [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. -2. C++11 language and library features. Still far from complete, and not widely supported by compiler vendors. +2. C++11 language and library features. Still far from complete, and not easy to use. 3. [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. 4. 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. From 17ca704d3a1ba5dc7da8fdfacdaea733acd2c340 Mon Sep 17 00:00:00 2001 From: Will Frey Date: Fri, 21 Jul 2017 23:07:07 -0400 Subject: [PATCH 12/18] Update test.cpp This test was failing for me when I compiled with clang. Must have a different initializer. I changed the test to match the example from the README and it passes when I build with both clang and gcc. --- test_drivers/smoke_test/test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test_drivers/smoke_test/test.cpp b/test_drivers/smoke_test/test.cpp index 70d6f15d3..d7bc4268e 100644 --- a/test_drivers/smoke_test/test.cpp +++ b/test_drivers/smoke_test/test.cpp @@ -153,7 +153,7 @@ int main() //replace_invalid char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z"; - vector replace_invalid_result(50); + vector replace_invalid_result; replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), replace_invalid_result.begin(), '?'); bvalid = is_valid(replace_invalid_result.begin(), replace_invalid_result.end()); assert (bvalid); From 3723b0cc6ebd5b3fdb6ebaed056e726d9be911c6 Mon Sep 17 00:00:00 2001 From: Alex Merry Date: Wed, 7 Mar 2018 16:43:54 +0000 Subject: [PATCH 13/18] Fix smoke test on MSVC The MSVC-generated code in debug mode was (quite rightly) complaining about iterating past the start of an empty vector, and aborting the test. --- test_drivers/smoke_test/test.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test_drivers/smoke_test/test.cpp b/test_drivers/smoke_test/test.cpp index d7bc4268e..4f9fb0485 100644 --- a/test_drivers/smoke_test/test.cpp +++ b/test_drivers/smoke_test/test.cpp @@ -154,10 +154,11 @@ int main() //replace_invalid char invalid_sequence[] = "a\x80\xe0\xa0\xc0\xaf\xed\xa0\x80z"; vector replace_invalid_result; - replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), replace_invalid_result.begin(), '?'); + replace_invalid (invalid_sequence, invalid_sequence + sizeof(invalid_sequence), std::back_inserter(replace_invalid_result), '?'); bvalid = is_valid(replace_invalid_result.begin(), replace_invalid_result.end()); assert (bvalid); - const char* fixed_invalid_sequence = "a????z"; + const char fixed_invalid_sequence[] = "a????z"; + assert (sizeof(fixed_invalid_sequence) == replace_invalid_result.size()); assert (std::equal(replace_invalid_result.begin(), replace_invalid_result.begin() + sizeof(fixed_invalid_sequence), fixed_invalid_sequence)); // iterator From 3866386b6d7c60572d13de5e3ce6b984fa044a9c Mon Sep 17 00:00:00 2001 From: Aaron Bishop Date: Thu, 2 Aug 2018 10:35:39 -0400 Subject: [PATCH 14/18] Modernize cmake * Able to use as subfolder * Able to install (and import again in cmake) * Able to disable tests * Able to disable samples --- CMakeLists.txt | 49 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 667d2881d..8cac0a1f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,13 +1,42 @@ -cmake_minimum_required (VERSION 2.8.0) -project (utf8cpp) -include_directories ("${PROJECT_SOURCE_DIR}/source") +cmake_minimum_required (VERSION 3.0.2) +project (utf8cpp VERSION 2.3.5 LANGUAGES CXX) -add_executable(smoke ${PROJECT_SOURCE_DIR}/test_drivers/smoke_test/test.cpp) -add_executable(negative ${PROJECT_SOURCE_DIR}/test_drivers/negative/negative.cpp) -add_executable(utf8reader ${PROJECT_SOURCE_DIR}/test_drivers/utf8reader/utf8reader.cpp) +option(UTF8_TESTS "Enable tests for UTF8-CPP" On) +option(UTF8_SAMPLES "Enable building samples for UTF8-CPP" On) -add_executable(docsample ${PROJECT_SOURCE_DIR}/samples/docsample.cpp) +add_library(utf8cpp INTERFACE) +target_include_directories(utf8cpp INTERFACE + "$" + $ +) +add_library(utf8::cpp ALIAS utf8cpp) -enable_testing() -add_test(smoke_test smoke) -add_test(negative_test negative ${PROJECT_SOURCE_DIR}/test_data/negative/utf8_invalid.txt) +if(WIN32 AND NOT CYGWIN) + set(DEF_INSTALL_CMAKE_DIR CMake) +else() + set(DEF_INSTALL_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/utf8cpp) +endif() + +install(DIRECTORY source/ DESTINATION include/utf8cpp) +install(TARGETS utf8cpp EXPORT utf8cppConfig) +install(EXPORT utf8cppConfig DESTINATION ${DEF_INSTALL_CMAKE_DIR}) + +if(UTF8_SAMPLES) + add_executable(utf8reader ${PROJECT_SOURCE_DIR}/test_drivers/utf8reader/utf8reader.cpp) + add_executable(docsample ${PROJECT_SOURCE_DIR}/samples/docsample.cpp) + + target_link_libraries(utf8reader PRIVATE utf8::cpp) + target_link_libraries(docsample PRIVATE utf8::cpp) +endif() + +if(UTF8_TESTS) + add_executable(smoke ${PROJECT_SOURCE_DIR}/test_drivers/smoke_test/test.cpp) + add_executable(negative ${PROJECT_SOURCE_DIR}/test_drivers/negative/negative.cpp) + + target_link_libraries(smoke PRIVATE utf8::cpp) + target_link_libraries(negative PRIVATE utf8::cpp) + + enable_testing() + add_test(smoke_test smoke) + add_test(negative_test negative ${PROJECT_SOURCE_DIR}/test_data/negative/utf8_invalid.txt) +endif() From fd39f7efb1337d57ad1411d527abec75adc7f50e Mon Sep 17 00:00:00 2001 From: Oleg Artenii Date: Fri, 14 Sep 2018 09:24:40 +0300 Subject: [PATCH 15/18] cmake: fixed undefined ${CMAKE_INSTALL_LIBDIR} --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8cac0a1f5..9f5ca4c0d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,6 +14,7 @@ add_library(utf8::cpp ALIAS utf8cpp) if(WIN32 AND NOT CYGWIN) set(DEF_INSTALL_CMAKE_DIR CMake) else() + include(GNUInstallDirs) # define CMAKE_INSTALL_* set(DEF_INSTALL_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/utf8cpp) endif() From 60c490b89fadc8f4e8dc0497500348572aee4b18 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Mon, 24 Sep 2018 19:49:14 -0400 Subject: [PATCH 16/18] Release v2.3.6 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f5ca4c0d..55073cdaa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required (VERSION 3.0.2) -project (utf8cpp VERSION 2.3.5 LANGUAGES CXX) +project (utf8cpp VERSION 2.3.6 LANGUAGES CXX) option(UTF8_TESTS "Enable tests for UTF8-CPP" On) option(UTF8_SAMPLES "Enable building samples for UTF8-CPP" On) From 0a238813416e0ac8ea998b8814f00611a00f0735 Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 13 Oct 2018 20:48:56 -0400 Subject: [PATCH 17/18] Create .gitignore Ignore: - .vscode - build --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..488d51dd9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +# VS Code: +.vscode/ +# Often used by CMake +build/ \ No newline at end of file From ef7bf0f783b3b9dbdf1e15094e3fbff77d7c3177 Mon Sep 17 00:00:00 2001 From: "Alexander A. Klimov" Date: Fri, 15 Mar 2019 10:11:42 +0100 Subject: [PATCH 18/18] Show license more prominently --- LICENSE | 23 +++++++++++++++++++++++ README.md | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..36b7cd93c --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index d4369e85d..09996abc8 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Many 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. -In 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. +In 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](./LICENSE). 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. The 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.