Разработчики C ++ по -прежнему пропускают легкий и портативный способ обработки кодированных строк Unicode. Оригинальный стандарт C ++ (известный как C ++ 98 или C ++ 03) является агностиком Unicode. Некоторый прогресс был достигнут в более поздних изданиях стандарта, но все еще трудно работать с Unicode, используя только стандартные средства.
Я придумал небольшую совместимую общую библиотеку C ++ 98, чтобы обрабатывать кодированные utf-8 строки. Для любого, кто работал с алгоритмами STL и итераторами, это должно быть легко и естественным в использовании. Код свободно доступен для любых целей - проверьте лицензию. Библиотека много использовалась с момента первого выпуска в 2006 году как в коммерческих, так и в проектах с открытым исходным кодом, и оказалась стабильной и полезной.
Это библиотека только для заголовков, и поддерживаемый способ развертывания есть:
Файл cmakelist.txt был изначально создан только для целей тестирования, но, к сожалению, со временем я принял взносы, которые добавили цель установки. Это не поддерживаемый способ установки библиотеки UTFCPP , и я рассматриваю возможность удаления cmakelist.txt в будущем.
Чтобы проиллюстрировать использование библиотеки, давайте начнем с небольшой, но полной программы, которая открывает файл, содержащий текст UTF-8, считывает его по строке, проверяет каждую строку на наличие недействительных последовательностей UTF-8 и преобразует его в кодирование UTF-16 и обратно в UTF-8:
# include < fstream >
# include < iostream >
# include < string >
# include < vector >
# include " utf8.h "
using namespace std ;
int main ( int argc, char ** argv)
{
if (argc != 2 ) {
cout << " n Usage: 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)
# if __cplusplus >= 201103L // C++ 11 or later
auto end_it = utf8::find_invalid (line. begin (), line. end ());
# else
string::iterator end_it = utf8::find_invalid (line. begin (), line. end ());
# endif // C++ 11
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
# if __cplusplus >= 201103L // C++ 11 or later
u16string utf16line = utf8::utf8to16 (line);
# else
vector< unsigned short > utf16line;
utf8::utf8to16 (line. begin (), end_it, back_inserter (utf16line));
# endif // C++ 11
// And back to utf-8;
# if __cplusplus >= 201103L // C++ 11 or later
string utf8line = utf8::utf16to8 (utf16line);
# else
string utf8line;
utf8::utf16to8 (utf16line. begin (), utf16line. end (), back_inserter (utf8line));
# endif // C++ 11
// 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 ;
} В предыдущем примере кода, для каждой строки мы выполняли обнаружение неверных последовательностей UTF-8 с find_invalid ; Количество символов (точнее - количество точек кода Unicode, включая конец строки и даже BOM, если есть один) в каждой строке было определено с использованием utf8::distance ; Наконец, мы преобразовали каждую строку в кодировку UTF-16 с utf8to16 и обратно в UTF-8 с utf16to8 .
Обратите внимание на другой шаблон использования для старых компиляторов. Например, именно так мы преобразуем кодируемую строку UTF-8 в кодированный UTF-16 с компилятором Pre-C ++ 11:
vector< unsigned short > utf16line;
utf8::utf8to16 (line.begin(), end_it, back_inserter(utf16line));С более современным компилятором такая же операция будет выглядеть как:
u16string utf16line = utf8::utf8to16(line); Если макрос __cplusplus указывает на C ++ 11 или позже, библиотека раскрывает API, который учитывает стандартные строки Unicode C ++ и перемещает семантику. С более старым компилятором все еще возможно использовать одну и ту же функциональность, лишь немного менее удобно
Если вы не доверяете макросу __cplusplus или, например, не хотите включать функции C ++ 11, даже с современным компилятором, определите макрос UTF_CPP_CPLUSPLUS до того, как включать utf8.h и назначить его значение для стандарта, который вы хотите использовать - значения одинаковы для макроса __cplusplus . Это также может быть полезно с компиляторами, которые являются консервативными в установке макроса __cplusplus , даже если они имеют хорошую поддержку для недавнего стандартного издания - Visual C ++ Microsoft является одним из примеров.
Вот функция, которая проверяет, является ли содержимое файла допустимым текстом UTF-8 без чтения контента в память:
bool valid_utf8_file ( const 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);
} Поскольку функция utf8::is_valid() работает с входными итераторами, мы смогли передать it istreambuf_iterator и прямо прочитать содержимое файла, не загружая его в память сначала.
Обратите внимание, что другие функции, которые принимают аргументы входного итератора, могут использоваться аналогичным образом. Например, чтобы прочитать содержимое текстового файла, закодированного UTF-8 и преобразовать текст в UTF-16, просто сделайте что-то вроде:
utf8::utf8to16 (it, eos, back_inserter(u16string));Если у нас есть какой-то текст, который «вероятно» содержит текст, закодированный UTF-8, и мы хотим заменить любую неверную последовательность UTF-8 на замену символов, можно использовать что-то вроде следующей функции:
void fix_utf8_string (std::string& str)
{
std::string temp;
utf8::replace_invalid (str. begin (), str. end (), back_inserter (temp));
str = temp;
}Функция заменит любую неверную последовательность UTF-8 на замену Unicode. Существует перегруженная функция, которая позволяет вызывающему абоненту предоставлять свой собственный запасной символ.
Библиотека была разработана, чтобы быть:
Для альтернатив и сравнений я рекомендую следующую статью: удивительно ужасный мир API, кодирующих C и C ++ (с некоторой ржавчиной), Джанхейд Менеид. В статье эта библиотека сравнивается с:
В статье представлено представление автора на качество дизайна API, а также некоторые тесты скорости.
Доступно в версии 1.0 и позже.
Кодирует 32-битную кодовую точку как последовательность OTF-8 OTF-8 и добавляет последовательность к строке UTF-8.
template < typename octet_iterator>
octet_iterator append ( utfchar32_t cp, octet_iterator result); octet_iterator : выходной итератор.
cp : 32 -битное целое число, представляющее кодовую точку для добавления в последовательность.
result : выходной итератор в место в последовательности, где добавить кодовую точку.
Возвращение значения: итератор, указывающий на место после недавно добавленной последовательности.
Пример использования:
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 ); Обратите внимание, что append не выделяет память - это бремя вызывающего абонента, чтобы убедиться, что для операции выделена достаточно памяти. Чтобы сделать вещи более интересными, append может добавить от 1 до 4 октетов к последовательности. На практике вы чаще всего захотите использовать std::back_inserter , чтобы убедиться, что необходимая память распределяется.
В случае неверной кодовой точки, исключение utf8::invalid_code_point .
Доступно в версии 3.0 и позже. До 4.0 потребовалось компилятор C ++ 11; Требование поднимается с 4.0.
Кодирует 32-битную кодовую точку как последовательность OTF-8 OTF-8 и добавляет последовательность к строке UTF-8.
void append ( utfchar32_t cp, std::string& s); cp : Кодовая точка для добавления к строке.
s : кодированная строка UTF-8 для добавления кодовой точки.
Пример использования:
std::string u;
append ( 0x0448 , u);
assert (u[ 0 ] == char ( 0xd1 ) && u[1] == char( 0x88 ) && u.length() == 2); В случае неверной кодовой точки, исключение utf8::invalid_code_point .
Доступно в версии 4.0 и позже.
Кодирует 32-битную кодовую точку как последовательность слов UTF-16 и добавляет последовательность в строку UTF-16.
template < typename word_iterator>
word_iterator append16 ( utfchar32_t cp, word_iterator result); word_iterator : выходной итератор.
cp : 32 -битное целое число, представляющее кодовую точку для добавления в последовательность.
result : выходной итератор в место в последовательности, где добавить кодовую точку.
Возвращение значения: итератор, указывающий на место после недавно добавленной последовательности.
Пример использования:
unsigned short u[ 2 ] = { 0 , 0 };
unsigned short * end = append16( 0x0448 , u);
assert (u[ 0 ] == 0x0448 && u[ 1 ] == 0 ); Обратите внимание, что append16 не выделяет память - это бремя вызывающего абонента, чтобы убедиться, что для операции выделено достаточно памяти. Чтобы сделать вещи более интересными, append16 может добавить одно или два слова в последовательность. На практике вы чаще всего захотите использовать std::back_inserter , чтобы убедиться, что необходимая память распределяется.
В случае неверной кодовой точки, исключение utf8::invalid_code_point .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 11.
Кодирует 32-битную кодовую точку как последовательность слов UTF-16 и добавляет последовательность в строку UTF-16.
void append ( utfchar32_t cp, std::u16string& s); cp : Кодовая точка для добавления к строке.
s : Кодированная строка UTF-16 для добавления кодовой точки.
Пример использования:
std::u16string u;
append ( 0x0448 , u);
assert (u[ 0 ] == 0x0448 && u.length() == 1); В случае неверной кодовой точки, исключение utf8::invalid_code_point .
Доступно в версии 1.0 и позже.
Учитывая итератор в начало последовательности UTF-8, он возвращает кодовую точку и перемещает итератор на следующую позицию.
template < typename octet_iterator>
utfchar32_t next (octet_iterator& it, octet_iterator end); octet_iterator : входной итератор.
it : ссылка на итератор, указывающий на начало кодируемой точки кодирования UTF-8. После возвращения функции она увеличивается, чтобы указывать на начало следующей кодовой точки.
end : конец последовательности UTF-8 для обработки. Если it становится равным к end во время извлечения кодовой точки, исключение utf8::not_enough_room .
Возвращение значения: 32-битное представление обработанной точки кода UTF-8.
Пример использования:
char * twochars = " xe6x97xa5xd1x88 " ;
char * w = twochars;
int cp = next(w, twochars + 6 );
assert (cp == 0x65e5 );
assert (w == twochars + 3 );Эта функция обычно используется для итерации через строку, кодируемую UTF-8.
В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 4.0 и позже.
Учитывая итератор в начало последовательности UTF-16, он возвращает кодовую точку и перемещает итератор на следующую позицию.
template < typename word_iterator>
utfchar32_t next16 (word_iterator& it, word_iterator end); word_iterator : входной итератор.
it : ссылка на итератор, указывающий на начало кодируемой точки кодирования UTF-16. После возвращения функции она увеличивается, чтобы указывать на начало следующей кодовой точки.
end : конец последовательности UTF-16 для обработки. Если it становится равным к end во время извлечения кодовой точки, исключение utf8::not_enough_room .
Возвращение значения: 32-битное представление обработанной точки кода UTF-16.
Пример использования:
const unsigned short u[ 3 ] = { 0x65e5 , 0xd800 , 0xdf46 };
const unsigned short * w = u;
int cp = next16(w, w + 3 );
assert (cp, 0x65e5 );
assert (w, u + 1 );Эта функция обычно используется для итерации через кодируемую строку UTF-16.
В случае неверной последовательности UTF-16, исключение utf8::invalid_utf8 .
Доступно в версии 2.1 и позже.
Учитывая итератор в начало последовательности UTF-8, он возвращает кодовую точку для следующей последовательности без изменения значения итератора.
template < typename octet_iterator>
utfchar32_t peek_next (octet_iterator it, octet_iterator end); octet_iterator : входной итератор.
it : итератор, указывающий на начало кодируемой точки кода UTF-8.
end : конец последовательности UTF-8 для обработки. Если it становится равным к end во время извлечения кодовой точки, исключение utf8::not_enough_room .
Возвращение значения: 32-битное представление обработанной точки кода UTF-8.
Пример использования:
char * twochars = " xe6x97xa5xd1x88 " ;
char * w = twochars;
int cp = peek_next(w, twochars + 6 );
assert (cp == 0x65e5 );
assert (w == twochars); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 1.02 и позже.
Учитывая ссылку на итератор, указывающий на октет в последовательности UTF-8, он уменьшает итератор до тех пор, пока не достигнет начала предыдущей кодовой точки, кодируемой UTF-8, и возвращает 32 бит представления кодовой точки.
template < typename octet_iterator>
utfchar32_t prior (octet_iterator& it, octet_iterator start); octet_iterator : двунаправленный итератор.
it : ссылка, указывающая на октет в строке, кодированной UTF-8. После возвращения функции она уменьшается, чтобы указывать на начало предыдущей кодовой точки.
start : итератор в начале последовательности, где выполняется поиск начала кодовой точки. Это мера безопасности, чтобы предотвратить передачу начала строки в поиске свинцового октета UTF-8.
Возвращение значения: 32 -битное представление предыдущей точки кода.
Пример использования:
char * twochars = " xe6x97xa5xd1x88 " ;
unsigned char * w = twochars + 3 ;
int cp = prior (w, twochars);
assert (cp == 0x65e5 );
assert (w == twochars); Эта функция имеет две цели: одна представляет собой две итерации назад через строку, закодированную UTF-8. Обратите внимание, что, как правило, лучшая идея, чтобы итерация вперед, так как utf8::next быстрее. Вторая цель-найти начало последовательности UTF-8, если у нас есть случайная позиция в строке. Обратите внимание, что в этом случае utf8::prior не может обнаружить неверную последовательность UTF-8 в некоторых сценариях: например, если есть лишние октеты тропы, это просто пропустит их.
Обычно it будет указывать на начало кодовой точки, и start будет указывать на начало строки, чтобы мы не заходили назад слишком далеко. it уменьшается до тех пор, пока он не укажет на свинцовый OTF-8 Octet, а затем последовательность UTF-8, начиная с этого октета, декодируется до 32-битного представления и возвращается.
В случае, если start достигнут до того, как ведущий октет UTF-8 ведут, или если неверная последовательность UTF-8 запускается ведущим октетом, исключение invalid_utf8 брошено.
В случае, если start равняется it , исключение not_enough_room брошено.
Доступно в версии 1.0 и позже.
Продвигает итератор по указанному количеству кодовых точек в последовательности UTF-8.
template < typename octet_iterator, typename distance_type>
void advance (octet_iterator& it, distance_type n, octet_iterator end); octet_iterator : входной итератор.
distance_type : интегральный тип, конвертируемый в тип разницы octet_iterator .
it : ссылка на итератор, указывающий на начало кодируемой точки кодирования UTF-8. После возвращения функции она увеличивается, чтобы указывать на NTH следующую точку кода.
n : Количество кодовых точек it быть продвинуто. Отрицательное значение означает уменьшение.
end : Предел обработки последовательности UTF-8. Если n положительный, и it становится равным к end во время извлечения кодовой точки, исключение utf8::not_enough_room брошен. Если n отрицательный, и it достигает end , пока it указывает на байт TA TRAIL последовательности UTF-8, исключение utf8::invalid_code_point .
Пример использования:
char * twochars = " xe6x97xa5xd1x88 " ;
unsigned char * w = twochars;
advance (w, 2 , twochars + 6 );
assert (w == twochars + 5 );
advance (w, - 2 , twochars);
assert (w == twochars); В случае неверной кодовой точки, исключение utf8::invalid_code_point .
Доступно в версии 1.0 и позже.
Учитывая итераторы в две кодируемые кодовые точки UTF-8 в последовательности, возвращает количество кодовых точек между ними.
template < typename octet_iterator>
typename std::iterator_traits<octet_iterator>::difference_type distance (octet_iterator first, octet_iterator last); octet_iterator : входной итератор.
first : итератор для начала кодируемой кодовой точки UTF-8.
last : итератор для «пост-конца» последней кодовой точки, закодированной UTF-8, в последовательности, которую мы пытаемся определить длину. Это может быть начало новой кодовой точки или нет.
Возврат значения расстояние между итераторами, в кодовых точках.
Пример использования:
char * twochars = " xe6x97xa5xd1x88 " ;
size_t dist = utf8::distance(twochars, twochars + 5 );
assert (dist == 2 ); Эта функция используется для поиска длины (в кодовых точках) строки, кодируемой UTF-8. Причина, по которой он называется расстоянием , а не, скажем, длиной , в основном потому, что разработчики используются, эта длина является функцией O (1). Вычисление длины строки UTF-8 является линейной операцией, и было лучше моделировать ее после алгоритма std::distance .
В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 . Если last не указывает на прошлое последовательности UTF-8, исключение utf8::not_enough_room добавлено.
Доступно в версии 1.0 и позже.
Преобразует кодируемую строку UTF-16 в UTF-8.
template < typename u16bit_iterator, typename octet_iterator>
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result); u16bit_iterator : входной итератор.
octet_iterator : выходной итератор.
start : итератор, указывающий на начало кодируемой строки UTF-16 для преобразования.
end : итератор, указывающий на проход на конец строки, кодируемой UTF-16 для преобразования.
result : выходной итератор в место в строке UTF-8, где добавить результат конверсии.
Возвращаемое значение: итератор, указывающий на место после добавленной строки UTF-8.
Пример использования:
unsigned short utf16string[] = { 0x41 , 0x0448 , 0x65e5 , 0xd834 , 0xdd1e };
vector< unsigned char > utf8result;
utf16to8 (utf16string, utf16string + 5 , back_inserter(utf8result));
assert (utf8result.size() == 10); В случае неверной последовательности UTF-16, исключение utf8::invalid_utf16 .
Доступно в версии 3.0 и позже. Требуется компилятор C ++ 11.
Преобразует кодируемую строку UTF-16 в UTF-8.
std::string utf16to8 ( const std::u16string& s); s : кодированная строка UTF-16. Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u16string utf16string = { 0x41 , 0x0448 , 0x65e5 , 0xd834 , 0xdd1e };
string u = utf16to8(utf16string);
assert (u.size() == 10); В случае неверной последовательности UTF-16, исключение utf8::invalid_utf16 .
Доступно в версии 3.2 и позже. Требует компилятора C ++ 17.
Преобразует кодируемую строку UTF-16 в UTF-8.
std::string utf16to8 (std::u16string_view s); s : кодированная строка UTF-16. Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u16string utf16string = { 0x41 , 0x0448 , 0x65e5 , 0xd834 , 0xdd1e };
u16string_view utf16stringview (u16string);
string u = utf16to8(utf16string);
assert (u.size() == 10); В случае неверной последовательности UTF-16, исключение utf8::invalid_utf16 .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодируемую строку UTF-16 в UTF-8.
std::u8string utf16tou8 ( const std::u16string& s); s : кодированная строка UTF-16. Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u16string utf16string = { 0x41 , 0x0448 , 0x65e5 , 0xd834 , 0xdd1e };
u8string u = utf16tou8(utf16string);
assert (u.size() == 10); В случае неверной последовательности UTF-16, исключение utf8::invalid_utf16 .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодируемую строку UTF-16 в UTF-8.
std::u8string utf16tou8 ( const std::u16string_view& s); s : кодированная строка UTF-16. Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u16string utf16string = { 0x41 , 0x0448 , 0x65e5 , 0xd834 , 0xdd1e };
u16string_view utf16stringview (u16string);
u8string u = utf16tou8(utf16string);
assert (u.size() == 10); В случае неверной последовательности UTF-16, исключение utf8::invalid_utf16 .
Доступно в версии 1.0 и позже.
Преобразует кодируемую строку UTF-8 в UTF-16
template < typename u16bit_iterator, typename octet_iterator>
u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result); octet_iterator : входной итератор.
u16bit_iterator : выходной итератор.
start : итератор, указывающий на начало строки, кодируемой UTF-8 для преобразования. end : итератор, указывающий на проход на конец строки, кодированной UTF-8 для преобразования.
result : выходной итератор на место в строке UTF-16, где добавить результат конверсии.
Возвращаемое значение: итератор, указывающий на место после добавленной строки UTF-16.
Пример использования:
char utf8_with_surrogates[] = " xe6x97xa5xd1x88xf0x9dx84x9e " ;
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 ); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 . Если end не указывает на прошлое последовательности UTF-8, исключение utf8::not_enough_room добавлено.
Доступно в версии 3.0 и позже. Требуется компилятор C ++ 11.
Преобразует кодируемую строку UTF-8 в UTF-16.
std::u16string utf8to16 ( const std::string& s); s : кодированная строка UTF-8 для преобразования.
Возвращаемое значение: кодированная строка UTF-16
Пример использования:
string utf8_with_surrogates = " xe6x97xa5xd1x88xf0x9dx84x9e " ;
u16string utf16result = utf8to16(utf8_with_surrogates);
assert (utf16result.length() == 4);
assert (utf16result[ 2 ] == 0xd834 );
assert (utf16result[ 3 ] == 0xdd1e ); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 3.2 и позже. Требует компилятора C ++ 17.
Преобразует кодируемую строку UTF-8 в UTF-16.
std::u16string utf8to16 (std::string_view s); s : кодированная строка UTF-8 для преобразования.
Возвращаемое значение: кодированная строка UTF-16
Пример использования:
string_view utf8_with_surrogates = " xe6x97xa5xd1x88xf0x9dx84x9e " ;
u16string utf16result = utf8to16(utf8_with_surrogates);
assert (utf16result.length() == 4);
assert (utf16result[ 2 ] == 0xd834 );
assert (utf16result[ 3 ] == 0xdd1e ); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодируемую строку UTF-8 в UTF-16.
std::u16string utf8to16 (std::u8string& s); s : кодированная строка UTF-8 для преобразования.
Возвращаемое значение: кодированная строка UTF-16
Пример использования:
std::u8string utf8_with_surrogates = " xe6x97xa5xd1x88xf0x9dx84x9e " ;
std::u16string utf16result = utf8to16(utf8_with_surrogates);
assert (utf16result.length() == 4);
assert (utf16result[ 2 ] == 0xd834 );
assert (utf16result[ 3 ] == 0xdd1e ); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодируемую строку UTF-8 в UTF-16.
std::u16string utf8to16 (std::u8string_view& s); s : кодированная строка UTF-8 для преобразования.
Возвращаемое значение: кодированная строка UTF-16
Пример использования:
std::u8string utf8_with_surrogates = " xe6x97xa5xd1x88xf0x9dx84x9e " ;
std::u8string_view utf8stringview {utf8_with_surrogates}
std::u16string utf16result = utf8to16(utf8stringview);
assert (utf16result.length() == 4);
assert (utf16result[ 2 ] == 0xd834 );
assert (utf16result[ 3 ] == 0xdd1e ); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 1.0 и позже.
Преобразует кодированную строку UTF-32 в UTF-8.
template < typename octet_iterator, typename u32bit_iterator>
octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result); octet_iterator : выходной итератор.
u32bit_iterator : входной итератор.
start : итератор, указывающий на начало кодированной строки UTF-32 для преобразования.
end : итератор, указывающий на проход в конце кодированной строки UTF-32 для преобразования.
result : выходной итератор в место в строке UTF-8, где добавить результат конверсии.
Возвращаемое значение: итератор, указывающий на место после добавленной строки UTF-8.
Пример использования:
int utf32string[] = { 0x448 , 0x65E5 , 0x10346 , 0 };
vector< unsigned char > utf8result;
utf32to8 (utf32string, utf32string + 3 , back_inserter(utf8result));
assert (utf8result.size() == 9); В случае неверной строки UTF-32, исключение utf8::invalid_code_point .
Доступно в версии 3.0 и позже. Требуется компилятор C ++ 11.
Преобразует кодированную строку UTF-32 в UTF-8.
std::string utf32to8 ( const std::u32string& s); s : кодированная строка UTF-32.
Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u32string utf32string = { 0x448 , 0x65E5 , 0x10346 };
string utf8result = utf32to8(utf32string);
assert (utf8result.size() == 9); В случае неверной строки UTF-32, исключение utf8::invalid_code_point .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодированную строку UTF-32 в UTF-8.
std::u8string utf32to8 ( const std::u32string& s); s : кодированная строка UTF-32.
Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u32string utf32string = { 0x448 , 0x65E5 , 0x10346 };
u8string utf8result = utf32to8(utf32string);
assert (utf8result.size() == 9); В случае неверной строки UTF-32, исключение utf8::invalid_code_point .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодированную строку UTF-32 в UTF-8.
std::u8string utf32to8 ( const std::u32string_view& s); s : кодированная строка UTF-32.
Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u32string utf32string = { 0x448 , 0x65E5 , 0x10346 };
u32string_view utf32stringview (utf32string);
u8string utf8result = utf32to8(utf32stringview);
assert (utf8result.size() == 9); В случае неверной строки UTF-32, исключение utf8::invalid_code_point .
Доступно в версии 3.0 и позже. Требуется компилятор C ++ 11.
Преобразует кодированную строку UTF-32 в UTF-8.
std::string utf32to8 ( const std::u32string& s); s : кодированная строка UTF-32.
Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u32string utf32string = { 0x448 , 0x65E5 , 0x10346 };
string utf8result = utf32to8(utf32string);
assert (utf8result.size() == 9); В случае неверной строки UTF-32, исключение utf8::invalid_code_point .
Доступно в версии 3.2 и позже. Требует компилятора C ++ 17.
Преобразует кодированную строку UTF-32 в UTF-8.
std::string utf32to8 (std::u32string_view s); s : кодированная строка UTF-32.
Возвращаемое значение: кодированная строка UTF-8.
Пример использования:
u32string utf32string = { 0x448 , 0x65E5 , 0x10346 };
u32string_view utf32stringview (utf32string);
string utf8result = utf32to8(utf32stringview);
assert (utf8result.size() == 9); В случае неверной строки UTF-32, исключение utf8::invalid_code_point .
Доступно в версии 1.0 и позже.
Преобразует кодируемую строку UTF-8 в UTF-32.
template < typename octet_iterator, typename u32bit_iterator>
u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result); octet_iterator : входной итератор.
u32bit_iterator : выходной итератор.
start : итератор, указывающий на начало строки, кодируемой UTF-8 для преобразования.
end : итератор, указывающий на проход на конец строки, кодированной UTF-8 для преобразования.
result : выходной итератор на место в строке UTF-32, где добавить результат конверсии.
Возвращаемое значение: итератор, указывающий на место после добавленной строки UTF-32.
Пример использования:
char * twochars = " xe6x97xa5xd1x88 " ;
vector< int > utf32result;
utf8to32 (twochars, twochars + 5 , back_inserter(utf32result));
assert (utf32result.size() == 2); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 . Если end не указывает на прошлое последовательности UTF-8, исключение utf8::not_enough_room добавлено.
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодируемую строку UTF-8 в UTF-32.
std::u32string utf8to32 ( const std::u8string& s); s : кодированная строка UTF-8. Возвратное значение: кодированная строка UTF-32.
Пример использования:
const std::u8string* twochars = u8" xe6x97xa5xd1x88 " ;
u32string utf32result = utf8to32(twochars);
assert (utf32result.size() == 2); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 4.0 и позже. Требуется компилятор C ++ 20.
Преобразует кодируемую строку UTF-8 в UTF-32.
std::u32string utf8to32 ( const std::u8string_view& s); s : кодированная строка UTF-8. Возвратное значение: кодированная строка UTF-32.
Пример использования:
const u8string* twochars = u8" xe6x97xa5xd1x88 " ;
const u8string_view stringview{twochars};
u32string utf32result = utf8to32(stringview);
assert (utf32result.size() == 2); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 3.0 и позже. Требуется компилятор C ++ 11.
Преобразует кодируемую строку UTF-8 в UTF-32.
std::u32string utf8to32 ( const std::string& s); s : кодированная строка UTF-8. Возвратное значение: кодированная строка UTF-32.
Пример использования:
const char * twochars = " xe6x97xa5xd1x88 " ;
u32string utf32result = utf8to32(twochars);
assert (utf32result.size() == 2); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 3.2 и позже. Требует компилятора C ++ 17.
Преобразует кодируемую строку UTF-8 в UTF-32.
std::u32string utf8to32 (std::string_view s); s : кодированная строка UTF-8. Возвратное значение: кодированная строка UTF-32.
Пример использования:
string_view twochars = " xe6x97xa5xd1x88 " ;
u32string utf32result = utf8to32(twochars);
assert (utf32result.size() == 2); В случае неверной последовательности UTF-8, исключение utf8::invalid_utf8 .
Доступно в версии 1.0 и позже.
Обнаружает неверную последовательность в строке UTF-8.
template < typename octet_iterator>
octet_iterator find_invalid (octet_iterator start, octet_iterator end); octet_iterator : входной итератор.
start : итератор, указывающий на начало строки UTF-8 для проверки на достоверность.
end : итератор, указывающий на прохождение строки UTF-8 для проверки на обоснованность.
Возвращение значения: итератор, указывающий на первый неверный октет в строке UTF-8. В случае, если никто не был найден, равным end .
Пример использования:
char utf_invalid[] = " xe6x97xa5xd1x88xfa " ;
char * invalid = find_invalid(utf_invalid, utf_invalid + 6 );
assert (invalid == utf_invalid + 5 );Эта функция обычно используется, чтобы убедиться, что строка UTF-8 действительна перед обработкой ее с другими функциями. Особенно важно назвать это, если перед тем, как выполнять какие -либо неконтролируемые операции.
Доступно в версии 4.0 и позже.
Обнаружение неверной последовательности в строке UTF-8 в стиле C.
const char * find_invalid ( const char * str); str : кодированная строка UTF-8. Возвращаемое значение: указатель на первый неверный октет в строке UTF-8. В случае, если никто не был найден, указывают на следующий нулевой байт.
Пример использования:
const char * utf_invalid = " xe6x97xa5xd1x88xfa " ;
const char * invalid = find_invalid(utf_invalid);
assert ((invalid - utf_invalid) == 5);Эта функция обычно используется, чтобы убедиться, что строка UTF-8 действительна перед обработкой ее с другими функциями. Особенно важно назвать это, если перед тем, как выполнять какие -либо неконтролируемые операции.
Доступно в версии 3.0 и позже. До 4.0 потребовалось компилятор C ++ 11; Требование поднято с 4.0
Обнаружает неверную последовательность в строке UTF-8.
std:: size_t find_invalid ( const std::string& s); s : кодированная строка UTF-8. Возвращение значения: индекс первого неверного октета в строке UTF-8. Если никто не был найден, равна std::string::npos .
Пример использования:
string utf_invalid = " xe6x97xa5xd1x88xfa " ;
auto invalid = find_invalid(utf_invalid);
assert (invalid == 5 );Эта функция обычно используется, чтобы убедиться, что строка UTF-8 действительна перед обработкой ее с другими функциями. Особенно важно назвать это, если перед тем, как выполнять какие -либо неконтролируемые операции.
Доступно в версии 3.2 и позже. Требует компилятора C ++ 17.
Обнаружает неверную последовательность в строке UTF-8.
std:: size_t find_invalid (std::string_view s); s : кодированная строка UTF-8. Возвращение значения: индекс первого неверного октета в строке UTF-8. Если никто не был найден, равна std::string_view::npos .
Пример использования:
string_view utf_invalid = " xe6x97xa5xd1x88xfa " ;
auto invalid = find_invalid(utf_invalid);
assert (invalid == 5 );Эта функция обычно используется, чтобы убедиться, что строка UTF-8 действительна перед обработкой ее с другими функциями. Особенно важно назвать это, если перед тем, как выполнять какие -либо неконтролируемые операции.
Доступно в версии 1.0 и позже.
Проверяет, является ли последовательность октетов действительной строкой UTF-8.
template < typename octet_iterator>
bool is_valid (octet_iterator start, octet_iterator end); octet_iterator : входной итератор.
start : итератор, указывающий на начало строки UTF-8 для проверки на достоверность.
end : итератор, указывающий на прохождение строки UTF-8 для проверки на обоснованность.
Возвращаемое значение: true , если последовательность является действительной строкой UTF-8; false если нет.
Пример использования:
char utf_invalid[] = " xe6x97xa5xd1x88xfa " ;
bool bvalid = is_valid(utf_invalid, utf_invalid + 6 );
assert (bvalid == false ); is_valid - это сокращение для find_invalid(start, end) == end; Полем Вы можете использовать его, чтобы убедиться, что байтовая последовательность представляет собой действительную строку UTF-8 без необходимости знать, где она не удается, если она недопустима.
Доступно в версии 4.0 и позже.
Проверяет, содержит ли строка C-стиля допустимый текст UTF-8.
bool is_valid ( const char * str); str : кодированная строка UTF-8.
Возвращаемое значение: true , если строка содержит допустимый кодированный текст UTF-8; false если нет.
Пример использования:
char utf_invalid[] = " xe6x97xa5xd1x88xfa " ;
bool bvalid = is_valid(utf_invalid);
assert (bvalid == false ); Вы можете использовать is_valid , чтобы убедиться, что строка содержит допустимый текст UTF-8 без необходимости знать, где она не удается, если она недопустима.
Доступно в версии 3.0 и позже. До 4.0 потребовалось компилятор C ++ 11; Требование поднято с 4.0
Проверяет, содержит ли строковый объект допустимый текст UTF-8.
bool is_valid ( const std::string& s); s : кодированная строка UTF-8.
Возвращаемое значение: true , если строка содержит допустимый кодированный текст UTF-8; false если нет.
Пример использования:
char utf_invalid[] = " xe6x97xa5xd1x88xfa " ;
bool bvalid = is_valid(utf_invalid);
assert (bvalid == false ); Вы можете использовать is_valid , чтобы убедиться, что строка содержит допустимый текст UTF-8 без необходимости знать, где она не удается, если она недопустима.
Доступно в версии 3.2 и позже. Требует компилятора C ++ 17.
Проверяет, содержит ли строковый объект допустимый текст UTF-8.
bool is_valid (std::string_view s); s : кодированная строка UTF-8.
Возвращаемое значение: true , если строка содержит допустимый кодированный текст UTF-8; false если нет.
Пример использования:
string_view utf_invalid = " xe6x97xa5xd1x88xfa " ;
bool bvalid = is_valid(utf_invalid);
assert (bvalid == false ); Вы можете использовать is_valid , чтобы убедиться, что строка содержит допустимый текст UTF-8 без необходимости знать, где она не удается, если она недопустима.
Доступно в версии 2.0 и позже.
Заменяет все неверные последовательности UTF-8 в строке с маркером замены.
template < typename octet_iterator, typename output_iterator>
output_iterator replace_invalid (octet_iterator start, octet_iterator end, output_iterator out, utfchar32_t replacement);
template < typename octet_iterator, typename output_iterator>
output_iterator replace_invalid (octet_iterator start, octet_iterator end, output_iterator out); octet_iterator : входной итератор.
output_iterator : выходной итератор.
start : итератор, указывающий на начало строки UTF-8 для поиска недействительных последовательностей UTF-8.
end : итератор, указывающий на проход на часть строки UTF-8, чтобы найти неверные последовательности UTF-8.
out : выходной итератор в диапазон, где хранится результат замены.
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 x80xe0xa0xc0xafxedxa0x80 z " ;
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.
Available in version 3.0 and later. Prior to 4.0 it required a C++ 11 compiler; the requirement is lifted with 4.0
Replaces all invalid UTF-8 sequences within a string with a replacement marker.
std::string replace_invalid ( const std::string& s, utfchar32_t replacement);
std::string replace_invalid ( const std::string& s); s : a UTF-8 encoded string.
replacement : A Unicode code point for the replacement marker. The version without this parameter assumes the value 0xfffd
Return value: A UTF-8 encoded string with replaced invalid sequences.
Example of use:
string invalid_sequence = " a x80xe0xa0xc0xafxedxa0x80 z " ;
string replace_invalid_result = replace_invalid(invalid_sequence, ' ? ' );
bvalid = is_valid(replace_invalid_result);
assert (bvalid);
const string fixed_invalid_sequence = " a????z " ;
assert (fixed_invalid_sequence == replace_invalid_result);Available in version 3.2 and later. Requires a C++ 17 compliant compiler.
Replaces all invalid UTF-8 sequences within a string with a replacement marker.
std::string replace_invalid (std::string_view s, char32_t replacement);
std::string replace_invalid (std::string_view s); s : a UTF-8 encoded string.
replacement : A Unicode code point for the replacement marker. The version without this parameter assumes the value 0xfffd
Return value: A UTF-8 encoded string with replaced invalid sequences.
Example of use:
string_view invalid_sequence = " a x80xe0xa0xc0xafxedxa0x80 z " ;
string replace_invalid_result = replace_invalid(invalid_sequence, ' ? ' );
bool bvalid = is_valid(replace_invalid_result);
assert (bvalid);
const string fixed_invalid_sequence = " a????z " ;
assert (fixed_invalid_sequence, replace_invalid_result);Available in version 2.3 and later.
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.
Available in version 3.0 and later. Prior to 4.0 it required a C++ 11 compiler; the requirement is lifted with 4.0
Checks whether a string starts with a UTF-8 byte order mark (BOM)
bool starts_with_bom ( const std::string& s); s : a UTF-8 encoded string. Return value: true if the string starts with a UTF-8 byte order mark; false if not.
Example of use:
string byte_order_mark = { char ( 0xef ), char ( 0xbb ), char ( 0xbf )};
bool bbom = starts_with_bom(byte_order_mark);
assert (bbom == true );
string threechars = " xf0x90x8dx86xe6x97xa5xd1x88 " ;
bool no_bbom = starts_with_bom(threechars);
assert (no_bbom == false );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.
Available in version 3.2 and later. Requires a C++ 17 compliant compiler.
Checks whether a string starts with a UTF-8 byte order mark (BOM)
bool starts_with_bom (std::string_view s); s : a UTF-8 encoded string. Return value: true if the string starts with a UTF-8 byte order mark; false if not.
Example of use:
string byte_order_mark = { char ( 0xef ), char ( 0xbb ), char ( 0xbf )};
string_view byte_order_mark_view (byte_order_mark);
bool bbom = starts_with_bom(byte_order_mark_view);
assert (bbom);
string_view threechars = " xf0x90x8dx86xe6x97xa5xd1x88 " ;
bool no_bbom = starts_with_bom(threechars);
assert (!no_bbom);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.
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 ();
}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:
utfchar32_t code_point () const ;
}; Member function code_point() can be used to determine the invalid code point that caused the exception to be thrown.
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:
utfchar8_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.
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:
utfchar16_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.
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 {};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 ; iterator(); the default 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.
utfchar32_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 underlying iterators are equal.
bool operator != (const iterator& rhs) const; returns true if the two underlying 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 = " xf0x90x8dx86xe6x97xa5xd1x88 " ;
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 , ie:
std::string s = " example " ;
utf8::iterator i (s.begin(), s.begin(), s.end());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 ( utfchar32_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.
Available in version 4.0 and later.
Encodes a 32 bit code point as a UTF-16 sequence of words and appends the sequence to a UTF-16 string.
template < typename word_iterator>
word_iterator append16 ( utfchar32_t cp, word_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 short u[ 5 ] = { 0 , 0 };
utf8::unchecked::append16 ( 0x0448 , u);
assert (u[ 0 ], 0x0448 );
assert (u[ 1 ], 0x0000 ); 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.
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>
utfchar32_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 = " xe6x97xa5xd1x88 " ;
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.
Available in version 4.0 and later.
Given the iterator to the beginning of the UTF-16 sequence, it returns the code point and moves the iterator to the next position.
template < typename word_iterator>
utfchar32_t next16 (word_iterator& it); word_iterator : an input iterator.
it : a reference to an iterator pointing to the beginning of an UTF-16 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-16 code point.
Example of use:
const unsigned short u[ 3 ] = { 0x65e5 , 0xd800 , 0xdf46 };
const unsigned short * w = u;
int cp = unchecked::next16(w);
assert (cp, 0x65e5 );
assert (w, u + 1 );This function is typically used to iterate through a UTF-16 encoded string.
This is a faster but less safe version of utf8::next16 . It does not check for validity of the supplied UTF-8 sequence.
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>
utfchar32_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 = " xe6x97xa5xd1x88 " ;
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.
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>
utfchar32_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 = " xe6x97xa5xd1x88 " ;
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.
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 : number of code points it should be advanced. A negative value means decrement.
Example of use:
char * twochars = " xe6x97xa5xd1x88 " ;
char * w = twochars;
unchecked::advance (w, 2 );
assert (w == twochars + 5 ); 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.
Available in version 1.0 and later.
Given the iterators to two UTF-8 encoded code points in a sequence, returns the number of code points between them.
template < typename octet_iterator>
typename std::iterator_traits<octet_iterator>::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 = " xe6x97xa5xd1x88 " ;
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.
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.
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. 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[] = " xe6x97xa5xd1x88xf0x9dx84x9e " ;
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.
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.
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 = " xe6x97xa5xd1x88 " ;
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.
Available in version 3.1 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, utfchar32_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 x80xe0xa0xc0xafxedxa0x80 z " ;
vector< char > replace_invalid_result;
unchecked::replace_invalid (invalid_sequence, invalid_sequence + sizeof (invalid_sequence), back_inserter(replace_invalid_result), '?');
bvalid = utf8::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.
Unlike utf8::replace_invalid , this function does not verify validity of the replacement marker.
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 ; iterator(); the default 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.
utfchar32_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 underlying iterators are equal.
bool operator != (const iterator& rhs) const; returns true if the two underlying 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 = " xf0x90x8dx86xe6x97xa5xd1x88 " ;
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.