Boost.Locale和isprint

aki*_*kim 6 c++ boost utf-8 c++11

我正在寻找一种方法来显示UTF-8字符串及其非打印/无效字符转义.在ASCII时代,我习惯用来isprint决定一个角色是按原样打印还是转义.使用UTF-8,迭代更加困难,但Boost.Locale做得很好.但是我没有找到任何内容来决定某些字符是否可打印,甚至实际上是否有效.

在以下源代码中,字符串"Hello ??? ? ? \x02\x01\b \xff\xff\xff "包含一些不可打印的坏人(\b例如),而其他人则是普通的无效序列(\xff\xff\xff).我应该进行什么测试才能确定角色是否可打印?

// Based on an example of Boost.Locale.
#include <boost/locale.hpp>
#include <iostream>
#include <iomanip>

int main()
{
  using namespace boost::locale;
  using namespace std;

  generator gen;
  std::locale loc = gen("");
  locale::global(loc); 
  cout.imbue(loc);

  string text = "Hello ??? ?  ? \x02\x01\b \xff\xff\xff ";

  cout << text << endl;

  boundary::ssegment_index index(boundary::character, text.begin(), text.end());

  for (auto p: index)
    {
      cout << '['  << p << '|';
      for (uint8_t c: p)
        cout << std::hex << std::setw(2) << std::setfill('0') << int(c);
      cout << "] ";
    }
  cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)

运行时,它给出了

[H|48] [e|65] [l|6c] [l|6c] [o|6f] [ |20] [?|e38182] [?|e381ab] [?|e381be]
[ |20] [?|e29ea6] [ |20] [|f09f9199] [ |20] [|f09d95ab]
[?|e28a86] [|f09d95a2] [ |20] [|02] [|01] |08] [ |20] [??? |ffffff20]
Run Code Online (Sandbox Code Playgroud)

我该如何判断它[|01]是不可打印的,也不是[??? |ffffff20],但是,[o|6f]是,等等[|f09f9199]?粗略地说,测试应该允许我决定是否打印[|]对的左侧成员,或者是否打印右侧成员isprint.

谢谢

小智 3

Unicode 具有每个代码点的属性,其中包括一般类别,技术报告列出了正则表达式分类(字母、图形等)。unicodeprint分类包括制表符,而std::isprint(使用 C 语言环境)则不包括制表符。print确实包括字母、标记、数字、标点符号、符号、空格和格式代码点。格式化代码点不包含CRLF,但包含影响外观的代码点外观的我相信这正是您想要的(选项卡除外);该规范经过精心设计以支持这些字符属性。

\n\n

大多数分类函数(例如std::isprint)一次只能给出一个标量值,因此 UTF32 是明显的编码选择。不幸的是,我们不能保证您的系统支持 UTF32 语言环境,也不能保证是wchar_t保存所有 unicode 代码点所需的 20 位。因此,boost::spirit::char_encoding::unicode如果可以的话,我会考虑用于分类。它有一个包含所有 unicode 类别的内部表,并实现了正则表达式技术报告中列出的分类。看起来它使用的是较旧的 Unicode 5.2 数据库,但提供了用于生成表的 C++,并且可以应用于较新的文件。

\n\n

多字节 UTF8 序列仍然需要转换为单独的代码点 (UTF32),并且您特别提到了跳过无效 UTF8 序列的能力。由于我是一名 C++ 程序员,我决定不必要地向您的屏幕发送垃圾邮件,并实现 constexpr UTF8->UTF32 函数:

\n\n
#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <boost/range/iterator_range.hpp>\n#include <boost/spirit/home/support/char_encoding/unicode.hpp>\n\nnamespace {\nstruct multi_byte_info {\n  std::uint8_t id_mask;\n  std::uint8_t id_matcher;\n  std::uint8_t data_mask;\n};\n\nconstexpr const std::uint8_t multi_byte_id_mask = 0xC0;\nconstexpr const std::uint8_t multi_byte_id_matcher = 0x80;\nconstexpr const std::uint8_t multi_byte_data_mask = 0x3F;\nconstexpr const std::uint8_t multi_byte_bits = 6;\nconstexpr const multi_byte_info multi_byte_infos[] = {\n    // skip 1 byte info\n    {0xE0, 0xC0, 0x1F},\n    {0xF0, 0xE0, 0x0F},\n    {0xF8, 0xF0, 0x07}};\nconstexpr const unsigned max_length =\n    (sizeof(multi_byte_infos) / sizeof(multi_byte_info));\n\nconstexpr const std::uint32_t overlong[] = {0x80, 0x800, 0x10000};\nconstexpr const std::uint32_t max_code_point = 0x10FFFF;\n}\n\nenum class extraction : std::uint8_t { success, failure };\n\nstruct extraction_attempt {\n  std::uint32_t code_point;\n  std::uint8_t bytes_processed;\n  extraction status;\n};\n\ntemplate <typename Iterator>\nconstexpr extraction_attempt next_code_point(Iterator position,\n                                             const Iterator &end) {\n  static_assert(\n      std::is_same<typename std::iterator_traits<Iterator>::iterator_category,\n                   std::random_access_iterator_tag>{},\n      "bad iterator type");\n\n  extraction_attempt result{0, 0, extraction::failure};\n\n  if (end - position) {\n    result.code_point = std::uint8_t(*position);\n    ++position;\n    ++result.bytes_processed;\n\n    if (0x7F < result.code_point) {\n      unsigned expected_length = 1;\n\n      for (const auto info : multi_byte_infos) {\n        if ((result.code_point & info.id_mask) == info.id_matcher) {\n          result.code_point &= info.data_mask;\n          break;\n        }\n        ++expected_length;\n      }\n\n      if (max_length < expected_length || (end - position) < expected_length) {\n        return result;\n      }\n\n      for (unsigned byte = 0; byte < expected_length; ++byte) {\n        const std::uint8_t next_byte = *(position + byte);\n        if ((next_byte & multi_byte_id_mask) != multi_byte_id_matcher) {\n          return result;\n        }\n\n        result.code_point <<= multi_byte_bits;\n        result.code_point |= (next_byte & multi_byte_data_mask);\n        ++result.bytes_processed;\n      }\n\n      if (max_code_point < result.code_point) {\n        return result;\n      }\n\n      if (overlong[expected_length - 1] > result.code_point) {\n        return result;\n      }\n    }\n\n    result.status = extraction::success;\n  } // end multi-byte processing\n\n  return result;\n}\n\ntemplate <typename Range>\nconstexpr extraction_attempt next_code_point(const Range &range) {\n  return next_code_point(std::begin(range), std::end(range));\n}\n\ntemplate <typename T>\nboost::iterator_range<T>\nnext_character_bytes(const boost::iterator_range<T> &range,\n                     const extraction_attempt result) {\n  return boost::make_iterator_range(range.begin(),\n                                    range.begin() + result.bytes_processed);\n}\n\ntemplate <std::size_t Length>\nconstexpr bool test(const char (&range)[Length],\n                    const extraction expected_status,\n                    const std::uint32_t expected_code_point,\n                    const std::uint8_t expected_bytes_processed) {\n  const extraction_attempt result =\n      next_code_point(std::begin(range), std::end(range) - 1);\n  switch (expected_status) {\n  case extraction::success:\n    return result.status == extraction::success &&\n           result.bytes_processed == expected_bytes_processed &&\n           result.code_point == expected_code_point;\n  case extraction::failure:\n    return result.status == extraction::failure &&\n           result.bytes_processed == expected_bytes_processed;\n  default:\n    return false;\n  }\n}\n\nint main() {\n  static_assert(test("F", extraction::success, \'F\', 1), "");\n  static_assert(test("\\0", extraction::success, 0, 1), "");\n  static_assert(test("\\x7F", extraction::success, 0x7F, 1), "");\n  static_assert(test("\\xFF\\xFF", extraction::failure, 0, 1), "");\n\n  static_assert(test("\\xDF", extraction::failure, 0, 1), "");\n  static_assert(test("\\xDF\\xFF", extraction::failure, 0, 1), "");\n  static_assert(test("\\xC1\\xBF", extraction::failure, 0, 2), "");\n  static_assert(test("\\xC2\\x80", extraction::success, 0x80, 2), "");\n  static_assert(test("\\xDF\\xBF", extraction::success, 0x07FF, 2), "");\n\n  static_assert(test("\\xEF\\xBF", extraction::failure, 0, 1), "");\n  static_assert(test("\\xEF\\xBF\\xFF", extraction::failure, 0, 2), "");\n  static_assert(test("\\xE0\\x9F\\xBF", extraction::failure, 0, 3), "");\n  static_assert(test("\\xE0\\xA0\\x80", extraction::success, 0x800, 3), "");\n  static_assert(test("\\xEF\\xBF\\xBF", extraction::success, 0xFFFF, 3), "");\n\n  static_assert(test("\\xF7\\xBF\\xBF", extraction::failure, 0, 1), "");\n  static_assert(test("\\xF7\\xBF\\xBF\\xFF", extraction::failure, 0, 3), "");\n  static_assert(test("\\xF0\\x8F\\xBF\\xBF", extraction::failure, 0, 4), "");\n  static_assert(test("\\xF0\\x90\\x80\\x80", extraction::success, 0x10000, 4), "");\n  static_assert(test("\\xF4\\x8F\\xBF\\xBF", extraction::success, 0x10FFFF, 4), "");\n  static_assert(test("\\xF7\\xBF\\xBF\\xBF", extraction::failure, 0, 4), "");\n\n  static_assert(test("", extraction::success, 0x1D56B, 4), "");\n\n  constexpr const static char text[] =\n      "Hello \xe3\x81\x82\xe3\x81\xab\xe3\x81\xbe \xe2\x9e\xa6  \xe2\x8a\x86 \\x02\\x01\\b \\xff\\xff\\xff ";\n\n  std::cout << text << std::endl;\n\n  auto data = boost::make_iterator_range(text);\n  while (!data.empty()) {\n    const extraction_attempt result = next_code_point(data);\n    switch (result.status) {\n    case extraction::success:\n      if (boost::spirit::char_encoding::unicode::isprint(result.code_point)) {\n        std::cout << next_character_bytes(data, result);\n        break;\n      }\n\n    default:\n    case extraction::failure:\n      std::cout << "[";\n      std::cout << std::hex << std::setw(2) << std::setfill(\'0\');\n      for (const auto byte : next_character_bytes(data, result)) {\n        std::cout << int(std::uint8_t(byte));\n      }\n      std::cout << "]";\n      break;\n    }\n\n    data.advance_begin(result.bytes_processed);\n  }\n\n  return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出:

\n\n
Hello \xe3\x81\x82\xe3\x81\xab\xe3\x81\xbe \xe2\x9e\xa6  \xe2\x8a\x86  \xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd \nHello \xe3\x81\x82\xe3\x81\xab\xe3\x81\xbe \xe2\x9e\xa6  \xe2\x8a\x86 [02][01][08] [ff][ff][ff] [00]\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

如果我的 UTF8->UTF32 实现让您感到害怕,或者您需要对用户区域设置的支持:

\n\n
    \n
  • std::mbtoc32\n\n
      \n
    • 令人印象深刻,因为它是最明显的选择,但并未在 libstdc++ 或 libc++ 中实现(也许是 trunk 构建?)
    • \n
    • 不可重入(当前区域设置并突然在其他地方更改)
    • \n
  • \n
  • boost 提供的迭代器。\n\n
      \n
    • 抛出无效序列,使其无法使用(无法超越错误序列)。
    • \n
  • \n
  • boost::locale::conv和 C++11std::codecvt \n\n
      \n
    • 旨在转换编码范围。
    • \n
    • 需要将 UTF32 输出到控制台(更改区域设置),或者一次转换一个字符以将源字节与 UTF32 值匹配。
    • \n
  • \n
  • UTF8-CPP utf::next(和非抛出utf8::internal::validate_next)。\n\n
      \n
    • IMO 都不一致地更新迭代器位置。如果函数未通过某些健全性检查,则迭代器位置位于表示错误代码点的有效 utf8 序列的最后一个字节。文档说:
    • \n
  • \n
\n\n
\n

它:对指向 UTF-8 编码代码点开头的迭代器的引用。函数返回后,它会递增以指向下一个代码点的开头。

\n
\n\n

这并不表明异常的副作用(肯定有一些)。

\n