RawByteString 是一个AnsiString,默认情况下没有设置代码页。
当您将另一个string 分配给此RawByteString 变量时,您将复制源string 的代码页。这将包括转换。对不起。
但RawByteString还有另一种用途,即存储纯字节内容(例如,数据库的BLOB字段内容,就像array of byte一样)
总结一下:
-
RawByteString 应该用作方法或函数的“代码页不可知”参数;
-
RawByteString 可以作为变量类型来存储一些 BLOB 数据。
如果你想减少转换,并且宁愿在你的应用程序中使用 8 位字符 string,你应该更好:
- 不要使用通用的
AnsiString 类型,这将取决于当前系统代码页,并且会丢失数据;
- 依赖 UTF-8 编码,即一些 8 位代码页/字符集,在从
UnicodeString 转换或转换为 UnicodeString 时不会丢失任何数据;
- 不要让编译器显示关于隐式转换的警告:所有转换都应该是显式的;
- 使用您自己的专用函数集来处理您的 UTF-8 内容。
这正是我们为我们的框架所做的。我们想在其内核中使用 UTF-8,因为:
- 我们依靠 UTF-8 编码的 JSON 进行数据传输;
- 内存消耗会更小;
- 使用的 SQLite3 引擎会将文本作为 UTF-8 存储在其数据库文件中;
- 我们想要一种处理 Unicode 文本的方法,在所有版本的 Delphi(从 Delphi 6 到 XE)中不会丢失数据,而
WideString 不是一个选项,因为它非常慢而且你也遇到了同样的问题隐式转换。
但是,为了达到最佳速度,我们编写了一些优化的函数来处理我们的自定义字符串类型:
{{ RawUTF8 is an UTF-8 String stored in an AnsiString
- use this type instead of System.UTF8String, which behavior changed
between Delphi 2009 compiler and previous versions: our implementation
is consistent and compatible with all versions of Delphi compiler
- mimic Delphi 2009 UTF8String, without the charset conversion overhead
- all conversion to/from AnsiString or RawUnicode must be explicit }
{$ifdef UNICODE} RawUTF8 = type AnsiString(CP_UTF8); // Codepage for an UTF8string
{$else} RawUTF8 = type AnsiString; {$endif}
/// our fast RawUTF8 version of Trim(), for Unicode only compiler
// - this Trim() is seldom used, but this RawUTF8 specific version is needed
// by Delphi 2009/2010/XE, to avoid two unnecessary conversions into UnicodeString
function Trim(const S: RawUTF8): RawUTF8;
/// our fast RawUTF8 version of Pos(), for Unicode only compiler
// - this Pos() is seldom used, but this RawUTF8 specific version is needed
// by Delphi 2009/2010/XE, to avoid two unnecessary conversions into UnicodeString
function Pos(const substr, str: RawUTF8): Integer; overload; inline;
我们保留了 RawByteString 类型来处理 BLOB 数据:
{$ifndef UNICODE}
/// define RawByteString, as it does exist in Delphi 2009/2010/XE
// - to be used for byte storage into an AnsiString
// - use this type if you don't want the Delphi compiler not to do any
// code page conversions when you assign a typed AnsiString to a RawByteString,
// i.e. a RawUTF8 or a WinAnsiString
RawByteString = AnsiString;
/// pointer to a RawByteString
PRawByteString = ^RawByteString;
{$endif}
/// create a File from a string content
// - uses RawByteString for byte storage, thatever the codepage is
function FileFromString(const Content: RawByteString; const FileName: TFileName;
FlushOnDisk: boolean=false): boolean;
源代码可用in our repository。本单元对 UTF-8 相关函数进行了深度优化,同时提供了 pascal 和 asm 两种版本,以提高速度。我们有时会重载默认函数(如Pos)以避免转换,或者有关我们如何在框架中处理文本的更多信息是available here。
最后一句话:
如果您确定您的应用程序中只有 7 位内容(没有重音字符),您可以在程序中使用默认的 AnsiString 类型。但在这种情况下,您最好在您的uses 子句中添加AnsiStrings 单元,以使字符串函数重载,从而避免大多数不需要的转换。