libpcre2 代码单元宽度

libpcre2 Code Unit Width

我一直在查看 pcre2 的手册页,并试图准确找出哪些情况需要 PCRE2_CODE_UNIT_WIDTH 的哪些定义。

The source code for PCRE2 can be compiled to support 8-bit, 16-bit, or 32-bit code units, which means that up to three separate libraries may be installed.

问题一:PCRE2的代码单元到底是什么?这是否意味着我需要使用 PCRE2_CODE_UNIT_WIDTH 8 来处理 char*PCRE2_CODE_UNIT_WIDTH 32 用于 wchar * ?如果我平台的 wchar 是 16 位的怎么办?是否需要有条件地使用 PCRE2_CODE_UNIT_WIDTH 16?如果这是真的,根据 How big is wchar_t with GCC? 看来我需要使用 PCRE2_CODE_UNIT_WIDTH = 8 * __SIZEOF_WCHAR_T__

关于 Unicode 的话题:

In all three cases, strings can be interpreted either as one character per code unit, or as UTF-encoded Unicode, with support for Unicode general category properties. Unicode support is optional at build time (but is the default). However, processing strings as UTF code units must be enabled explicitly at run time.

问题 2:当启用 Unicode 时,PCRE2_CODE_UNIT_WIDTH 到底是什么意思? PCRE2_CODE_UNIT_WIDTH 8 是否采用 UTF-8,我需要设置 PCRE2_CODE_UNIT_WIDTH 16 来处理 UTF-16 字符串?

What exactly is PCRE2's code unit?

以下是 PCRE2 用于其代码单元定义的内容(在 pcre2.h 中):

/* Types for code units in patterns and subject strings. */

typedef uint8_t  PCRE2_UCHAR8;
typedef uint16_t PCRE2_UCHAR16;
typedef uint32_t PCRE2_UCHAR32;

typedef const PCRE2_UCHAR8  *PCRE2_SPTR8;
typedef const PCRE2_UCHAR16 *PCRE2_SPTR16;
typedef const PCRE2_UCHAR32 *PCRE2_SPTR32;

因此您可以看到 PCRE2 在底层使用 uintX_t 而不是 char/wchar_t

请注意,当您将 PCRE2_CODE_UNIT_WIDTH 定义为 8、16 或 32 时,PCRE2_UCHARPCRE2_SPTR 将被#defined 为正确的变量。

所以是的,PCRE2_CODE_UNIT_WIDTH = 8 * __SIZEOF_WCHAR_T__乍一看似乎很合理,但是wchar_t is not meant to handle Unicode data。如果您想编写可移植代码,请避免使用它,只需对 UTF-8 使用 char/uint8_t,对 UTF-16 使用 uint16_t,对 UTF-32 使用 uint32_t

不要将 代码单元 代码点 混淆,因为对一个代码点进行编码可能需要多个代码单元。

What exactly does PCRE2_CODE_UNIT_WIDTH mean when Unicode is enabled? Does PCRE2_CODE_UNIT_WIDTH 8 take UTF-8, and I need to set PCRE2_CODE_UNIT_WIDTH 16 to handle a UTF-16 string?

是的。如果您需要在程序中处理多种编码,也可以将 PCRE2_CODE_UNIT_WIDTH 设置为 0。您将丢失 pcre2_match 等别名,并且您必须调用 pcre2_match_8pcre2_match_16 例如。