七位 ASCII 字符编码标准。
不要与八位 扩展 ASCII 字符编码混淆。
虽然此模块处理的是七位 ASCII,
但为便于使用和兼容性,函数采用 u8,而非 u7。
超出七位范围的字符会得到妥善处理,例如返回 false。
另请参见:https://en.wikipedia.org/wiki/ASCII#Character_set
stdlowercaseuppercaseletterscontrol_codeisAlphanumericisAlphabeticisControlisDigitisLowerisPrintisGraphicalisPunctuationisWhitespacewhitespaceisUpperisHexisAsciitoUppertoLowerlowerStringallocLowerStringupperStringallocUpperStringeqlIgnoreCasestartsWithIgnoreCaseendsWithIgnoreCasefindIgnoreCasefindIgnoreCasePosfindIgnoreCasePosLinearboyerMooreHorspoolPreprocessIgnoreCaseorderIgnoreCaseorderIgnoreCaseZboundedOrderIgnoreCaseZlessThanIgnoreCaseHexEscapehexEscape
std.ascii.allocLowerString
函数
分配 ascii_string 的小写副本。
调用方拥有返回的字符串,必须使用 allocator 释放。
pub fn allocLowerString(allocator: std.mem.Allocator, ascii_string: []const u8) ![]u8
参数
用法示例
test allocLowerString {
const result = try allocLowerString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result);
}
std.ascii.allocUpperString
函数
分配 ascii_string 的大写副本。
调用方拥有返回的字符串,必须使用 allocator 释放。
pub fn allocUpperString(allocator: std.mem.Allocator, ascii_string: []const u8) ![]u8
参数
用法示例
test allocUpperString {
const result = try allocUpperString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result);
}
std.ascii.boundedOrderIgnoreCaseZ
函数
在指定上界内,返回两个以空字符终止的多项指针的字典序关系。O(n)。
pub fn boundedOrderIgnoreCaseZ(lhs: [*:0]const u8, rhs: [*:0]const u8, bound: usize) std.math.Order
参数
lhs: [*:0]const u8
rhs: [*:0]const u8
bound: usize
std.ascii.boyerMooreHorspoolPreprocessIgnoreCase
函数
fn boyerMooreHorspoolPreprocessIgnoreCase(pattern: []const u8, table: *[256]usize) void
参数
pattern: []const u8
table: *[256]usize
std.ascii.control_code
命名空间
ASCII 编码中的 C0 控制码。
另请参见:https://en.wikipedia.org/wiki/C0_and_C1_control_codes 和 isControl
std.ascii.control_code.ack
常量
确认。
std.ascii.control_code.bel
常量
响铃,警报。
std.ascii.control_code.bs
常量
退格符。
std.ascii.control_code.can
常量
取消。
std.ascii.control_code.cr
常量
回车符('\r')。
std.ascii.control_code.dc1
常量
设备控制一(XON)。
std.ascii.control_code.dc2
常量
设备控制二。
std.ascii.control_code.dc3
常量
设备控制三(XOFF)。
std.ascii.control_code.dc4
常量
设备控制四。
std.ascii.control_code.del
常量
删除。
std.ascii.control_code.dle
常量
数据链路转义。
std.ascii.control_code.em
常量
介质结束。
std.ascii.control_code.enq
常量
询问符。
std.ascii.control_code.eot
常量
传输结束。
std.ascii.control_code.esc
常量
转义符。
std.ascii.control_code.etb
常量
传输块结束
std.ascii.control_code.etx
常量
文本结束。
std.ascii.control_code.ff
常量
换页符。
std.ascii.control_code.fs
常量
文件分隔符。
std.ascii.control_code.gs
常量
组分隔符。
std.ascii.control_code.ht
常量
水平制表符,Tab('\t')。
std.ascii.control_code.lf
常量
换行符('\n')。
std.ascii.control_code.nak
常量
否定确认。
std.ascii.control_code.nul
常量
空值。
std.ascii.control_code.rs
常量
记录分隔符。
std.ascii.control_code.si
常量
移入。
std.ascii.control_code.so
常量
移出。
std.ascii.control_code.soh
常量
标题开始。
std.ascii.control_code.stx
常量
正文开始。
std.ascii.control_code.sub
常量
替换。
std.ascii.control_code.syn
常量
同步空闲。
std.ascii.control_code.us
常量
单元分隔符。
std.ascii.control_code.vt
常量
垂直制表符。
std.ascii.control_code.xoff
别名
dc3 的别名。
std.ascii.control_code.xon
别名
dc1 的别名。
std.ascii.endsWithIgnoreCase
函数
pub fn endsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool
参数
haystack: []const u8
needle: []const u8
用法示例
test endsWithIgnoreCase {
try std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack"));
try std.testing.expect(!endsWithIgnoreCase("BoB", "Bo"));
}
std.ascii.eqlIgnoreCase
函数
忽略大小写比较字符串 a 和 b,并返回它们是否相等。
pub fn eqlIgnoreCase(a: []const u8, b: []const u8) bool
参数
a: []const u8
b: []const u8
用法示例
test eqlIgnoreCase {
try std.testing.expect(eqlIgnoreCase("HEl💩Lo!", "hel💩lo!"));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "hello! "));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!"));
}
std.ascii.findIgnoreCase
函数
从索引 0 开始,在 haystack 中忽略大小写查找 needle。
pub fn findIgnoreCase(haystack: []const u8, needle: []const u8) ?usize
参数
haystack: []const u8
needle: []const u8
用法示例
test findIgnoreCase {
try std.testing.expect(findIgnoreCase("one Two Three Four", "foUr").? == 14);
try std.testing.expect(findIgnoreCase("one two three FouR", "gOur") == null);
try std.testing.expect(findIgnoreCase("foO", "Foo").? == 0);
try std.testing.expect(findIgnoreCase("foo", "fool") == null);
try std.testing.expect(findIgnoreCase("FOO foo", "fOo").? == 0);
try std.testing.expect(findIgnoreCase("one two three four five six seven eight nine ten eleven", "ThReE fOUr").? == 8);
try std.testing.expect(findIgnoreCase("one two three four five six seven eight nine ten eleven", "Two tWo") == null);
}
std.ascii.findIgnoreCasePos
函数
从 start_index 开始,不区分大小写地在 haystack 中查找 needle。
大输入使用 Boyer-Moore-Horspool 算法;小输入使用 findIgnoreCasePosLinear。
pub fn findIgnoreCasePos(haystack: []const u8, start_index: usize, needle: []const u8) ?usize
参数
haystack: []const u8
start_index: usize
needle: []const u8
std.ascii.findIgnoreCasePosLinear
函数
可考虑改用 findIgnoreCasePos,它会对较大的输入
自动使用更精细的算法。
pub fn findIgnoreCasePosLinear(haystack: []const u8, start_index: usize, needle: []const u8) ?usize
参数
haystack: []const u8
start_index: usize
needle: []const u8
std.ascii.hexEscape
函数
将非 ASCII 字节替换为十六进制转义。
pub fn hexEscape(bytes: []const u8, case: std.fmt.Case) HexEscape
参数
用法示例
test hexEscape {
try std.testing.expectFmt("abc 123", "{f}", .{hexEscape("abc 123", .lower)});
try std.testing.expectFmt("ab\\xffc", "{f}", .{hexEscape("ab\xffc", .lower)});
try std.testing.expectFmt("abc 123", "{f}", .{hexEscape("abc 123", .upper)});
try std.testing.expectFmt("ab\\xFFc", "{f}", .{hexEscape("ab\xffc", .upper)});
}
std.ascii.HexEscape
容器
字段
bytes: []const u8
charset: *const [16]u8
std.ascii.HexEscape.format
函数
pub fn format(se: HexEscape, w: *std.Io.Writer) std.Io.Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.ascii.HexEscape.lower_charset
常量
std.ascii.HexEscape.upper_charset
常量
std.ascii.isAlphabetic
函数
返回字符是否为英文字母:A-Z 或 a-z。
pub fn isAlphabetic(c: u8) bool
参数
c: u8
std.ascii.isAlphanumeric
函数
返回字符是否为英文字母或数字:A-Z、a-z 或 0-9。
pub fn isAlphanumeric(c: u8) bool
参数
c: u8
std.ascii.isAscii
函数
返回字符是否为 7 位 ASCII 字符。
pub fn isAscii(c: u8) bool
参数
c: u8
std.ascii.isControl
函数
返回字符是否为控制字符。
另请参见:control_code
pub fn isControl(c: u8) bool
参数
c: u8
std.ascii.isDigit
函数
返回该字符是否为数字。
pub fn isDigit(c: u8) bool
参数
c: u8
std.ascii.isGraphical
函数
返回字符是否具有某种图形表示。
pub fn isGraphical(c: u8) bool
参数
c: u8
std.ascii.isHex
函数
返回字符是否为十六进制数字:A-F、a-f 或 0-9。
pub fn isHex(c: u8) bool
参数
c: u8
std.ascii.isLower
函数
返回字符是否为小写字母。
pub fn isLower(c: u8) bool
参数
c: u8
std.ascii.isPrint
函数
返回字符是否可打印且具有图形表示, 包括空格字符。
pub fn isPrint(c: u8) bool
参数
c: u8
std.ascii.isPunctuation
函数
返回字符是否为标点字符。
pub fn isPunctuation(c: u8) bool
参数
c: u8
std.ascii.isUpper
函数
返回字符是否为大写字母。
pub fn isUpper(c: u8) bool
参数
c: u8
std.ascii.isWhitespace
函数
返回此字符是否包含在 whitespace 中。
pub fn isWhitespace(c: u8) bool
参数
c: u8
std.ascii.lessThanIgnoreCase
函数
返回 lhs 的字典序是否小于 rhs。
pub fn lessThanIgnoreCase(lhs: []const u8, rhs: []const u8) bool
参数
lhs: []const u8
rhs: []const u8
std.ascii.letters
常量
std.ascii.lowercase
常量
std.ascii.lowerString
函数
将 ascii_string 的小写副本写入 output。
断言 output.len >= ascii_string.len。
pub fn lowerString(output: []u8, ascii_string: []const u8) []u8
参数
output: []u8
ascii_string: []const u8
用法示例
test lowerString {
var buf: [1024]u8 = undefined;
const result = lowerString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!");
try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result);
}
std.ascii.orderIgnoreCase
函数
返回两个切片的字典序。时间复杂度 O(n)。
pub fn orderIgnoreCase(lhs: []const u8, rhs: []const u8) std.math.Order
参数
lhs: []const u8
rhs: []const u8
std.ascii.orderIgnoreCaseZ
函数
返回两个以 NUL 结尾的多元素指针的字典序。时间复杂度 O(n)。
pub fn orderIgnoreCaseZ(lhs: [*:0]const u8, rhs: [*:0]const u8) std.math.Order
参数
lhs: [*:0]const u8
rhs: [*:0]const u8
用法示例
test orderIgnoreCaseZ {
try std.testing.expect(orderIgnoreCaseZ("aBcD", "Bee") == .lt);
try std.testing.expect(orderIgnoreCaseZ("AbC", "aBc") == .eq);
try std.testing.expect(orderIgnoreCaseZ("abC", "aBc0") == .lt);
try std.testing.expect(orderIgnoreCaseZ("", "") == .eq);
try std.testing.expect(orderIgnoreCaseZ("", "a") == .lt);
const s: [*:0]const u8 = "Abc";
try std.testing.expect(orderIgnoreCaseZ(s, s) == .eq);
}
std.ascii.startsWithIgnoreCase
函数
pub fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool
参数
haystack: []const u8
needle: []const u8
用法示例
test startsWithIgnoreCase {
try std.testing.expect(startsWithIgnoreCase("boB", "Bo"));
try std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack"));
}
std.ascii.std
别名
别名目标 std
std.ascii.toLower
函数
将字符转换为小写;若本来已是小写或不是字母,则原样返回。
pub fn toLower(c: u8) u8
参数
c: u8
std.ascii.toUpper
函数
将字符转换为大写;若已为大写或不是字母,则原样返回。
pub fn toUpper(c: u8) u8
参数
c: u8
std.ascii.uppercase
常量
std.ascii.upperString
函数
将 ascii_string 的大写副本写入 output。
断言 output.len >= ascii_string.len。
pub fn upperString(output: []u8, ascii_string: []const u8) []u8
参数
output: []u8
ascii_string: []const u8
用法示例
test upperString {
var buf: [1024]u8 = undefined;
const result = upperString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!");
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result);
}
std.ascii.whitespace
常量
通用空白字符。
例如可与 std.mem.trim 配合,用于裁剪空白。
另见:isWhitespace
源码
std/ascii.zig
//! 七位 [ASCII](https://en.wikipedia.org/wiki/ASCII) 字符编码标准。
//!
//! 不要与八位 [扩展 ASCII](https://en.wikipedia.org/wiki/Extended_ASCII) 字符编码混淆。
//!
//! 虽然此模块处理的是七位 ASCII,
//! 但为便于使用和兼容性,函数采用 `u8`,而非 `u7`。
//! 超出七位范围的字符会得到妥善处理,例如返回 `false`。
//!
//! 另请参见:https://en.wikipedia.org/wiki/ASCII#Character_set
const std = @import("std");
pub const lowercase = "abcdefghijklmnopqrstuvwxyz";
pub const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub const letters = lowercase ++ uppercase;
/// ASCII 编码中的 C0 控制码。
///
/// 另请参见:https://en.wikipedia.org/wiki/C0_and_C1_control_codes 和 `isControl`
pub const control_code = struct {
/// 空值。
pub const nul = 0x00;
/// 标题开始。
pub const soh = 0x01;
/// 正文开始。
pub const stx = 0x02;
/// 文本结束。
pub const etx = 0x03;
/// 传输结束。
pub const eot = 0x04;
/// 询问符。
pub const enq = 0x05;
/// 确认。
pub const ack = 0x06;
/// 响铃,警报。
pub const bel = 0x07;
/// 退格符。
pub const bs = 0x08;
/// 水平制表符,Tab('\t')。
pub const ht = 0x09;
/// 换行符('\n')。
pub const lf = 0x0A;
/// 垂直制表符。
pub const vt = 0x0B;
/// 换页符。
pub const ff = 0x0C;
/// 回车符('\r')。
pub const cr = 0x0D;
/// 移出。
pub const so = 0x0E;
/// 移入。
pub const si = 0x0F;
/// 数据链路转义。
pub const dle = 0x10;
/// 设备控制一(XON)。
pub const dc1 = 0x11;
/// 设备控制二。
pub const dc2 = 0x12;
/// 设备控制三(XOFF)。
pub const dc3 = 0x13;
/// 设备控制四。
pub const dc4 = 0x14;
/// 否定确认。
pub const nak = 0x15;
/// 同步空闲。
pub const syn = 0x16;
/// 传输块结束
pub const etb = 0x17;
/// 取消。
pub const can = 0x18;
/// 介质结束。
pub const em = 0x19;
/// 替换。
pub const sub = 0x1A;
/// 转义符。
pub const esc = 0x1B;
/// 文件分隔符。
pub const fs = 0x1C;
/// 组分隔符。
pub const gs = 0x1D;
/// 记录分隔符。
pub const rs = 0x1E;
/// 单元分隔符。
pub const us = 0x1F;
/// 删除。
pub const del = 0x7F;
/// `dc1` 的别名。
pub const xon = dc1;
/// `dc3` 的别名。
pub const xoff = dc3;
};
/// 返回字符是否为英文字母或数字:A-Z、a-z 或 0-9。
pub fn isAlphanumeric(c: u8) bool {
return switch (c) {
'0'...'9', 'A'...'Z', 'a'...'z' => true,
else => false,
};
}
/// 返回字符是否为英文字母:A-Z 或 a-z。
pub fn isAlphabetic(c: u8) bool {
return switch (c) {
'A'...'Z', 'a'...'z' => true,
else => false,
};
}
/// 返回字符是否为控制字符。
///
/// 另请参见:`control_code`
pub fn isControl(c: u8) bool {
return c <= control_code.us or c == control_code.del;
}
/// 返回该字符是否为数字。
pub fn isDigit(c: u8) bool {
return switch (c) {
'0'...'9' => true,
else => false,
};
}
/// 返回字符是否为小写字母。
pub fn isLower(c: u8) bool {
return switch (c) {
'a'...'z' => true,
else => false,
};
}
/// 返回字符是否可打印且具有图形表示,
/// 包括空格字符。
pub fn isPrint(c: u8) bool {
return isAscii(c) and !isControl(c);
}
/// 返回字符是否具有某种图形表示。
pub fn isGraphical(c: u8) bool {
return isPrint(c) and c != ' ';
}
/// 返回字符是否为标点字符。
pub fn isPunctuation(c: u8) bool {
return isGraphical(c) and !isAlphanumeric(c);
}
/// 返回此字符是否包含在 `whitespace` 中。
pub fn isWhitespace(c: u8) bool {
return switch (c) {
' ', '\t'...'\r' => true,
else => false,
};
}
/// 通用空白字符。
/// 例如可与 `std.mem.trim` 配合,用于裁剪空白。
///
/// 另见:`isWhitespace`
pub const whitespace = [_]u8{ ' ', '\t', '\n', '\r', control_code.vt, control_code.ff };
test whitespace {
for (whitespace) |char| try std.testing.expect(isWhitespace(char));
var i: u8 = 0;
while (isAscii(i)) : (i += 1) {
if (isWhitespace(i)) try std.testing.expect(std.mem.findScalar(u8, &whitespace, i) != null);
}
}
/// 返回字符是否为大写字母。
pub fn isUpper(c: u8) bool {
return switch (c) {
'A'...'Z' => true,
else => false,
};
}
/// 返回字符是否为十六进制数字:A-F、a-f 或 0-9。
pub fn isHex(c: u8) bool {
return switch (c) {
'0'...'9', 'A'...'F', 'a'...'f' => true,
else => false,
};
}
/// 返回字符是否为 7 位 ASCII 字符。
pub fn isAscii(c: u8) bool {
return c < 128;
}
/// 将字符转换为大写;若已为大写或不是字母,则原样返回。
pub fn toUpper(c: u8) u8 {
const mask = @as(u8, @intFromBool(isLower(c))) << 5;
return c ^ mask;
}
/// 将字符转换为小写;若本来已是小写或不是字母,则原样返回。
pub fn toLower(c: u8) u8 {
const mask = @as(u8, @intFromBool(isUpper(c))) << 5;
return c | mask;
}
test "ASCII character classes" {
const testing = std.testing;
try testing.expect(!isControl('a'));
try testing.expect(!isControl('z'));
try testing.expect(!isControl(' '));
try testing.expect(isControl(control_code.nul));
try testing.expect(isControl(control_code.ff));
try testing.expect(isControl(control_code.us));
try testing.expect(isControl(control_code.del));
try testing.expect(!isControl(0x80));
try testing.expect(!isControl(0xff));
try testing.expect('C' == toUpper('c'));
try testing.expect(':' == toUpper(':'));
try testing.expect('\xab' == toUpper('\xab'));
try testing.expect(!isUpper('z'));
try testing.expect(!isUpper(0x80));
try testing.expect(!isUpper(0xff));
try testing.expect('c' == toLower('C'));
try testing.expect(':' == toLower(':'));
try testing.expect('\xab' == toLower('\xab'));
try testing.expect(!isLower('Z'));
try testing.expect(!isLower(0x80));
try testing.expect(!isLower(0xff));
try testing.expect(isAlphanumeric('Z'));
try testing.expect(isAlphanumeric('z'));
try testing.expect(isAlphanumeric('5'));
try testing.expect(isAlphanumeric('a'));
try testing.expect(!isAlphanumeric('!'));
try testing.expect(!isAlphanumeric(0x80));
try testing.expect(!isAlphanumeric(0xff));
try testing.expect(!isAlphabetic('5'));
try testing.expect(isAlphabetic('c'));
try testing.expect(!isAlphabetic('@'));
try testing.expect(isAlphabetic('Z'));
try testing.expect(!isAlphabetic(0x80));
try testing.expect(!isAlphabetic(0xff));
try testing.expect(isWhitespace(' '));
try testing.expect(isWhitespace('\t'));
try testing.expect(isWhitespace('\r'));
try testing.expect(isWhitespace('\n'));
try testing.expect(isWhitespace(control_code.ff));
try testing.expect(!isWhitespace('.'));
try testing.expect(!isWhitespace(control_code.us));
try testing.expect(!isWhitespace(0x80));
try testing.expect(!isWhitespace(0xff));
try testing.expect(!isHex('g'));
try testing.expect(isHex('b'));
try testing.expect(isHex('F'));
try testing.expect(isHex('9'));
try testing.expect(!isHex(0x80));
try testing.expect(!isHex(0xff));
try testing.expect(!isDigit('~'));
try testing.expect(isDigit('0'));
try testing.expect(isDigit('9'));
try testing.expect(!isDigit(0x80));
try testing.expect(!isDigit(0xff));
try testing.expect(isPrint(' '));
try testing.expect(isPrint('@'));
try testing.expect(isPrint('~'));
try testing.expect(!isPrint(control_code.esc));
try testing.expect(!isPrint(0x80));
try testing.expect(!isPrint(0xff));
try testing.expect(isGraphical('@'));
try testing.expect(isGraphical('!'));
try testing.expect(!isGraphical(' '));
try testing.expect(isPunctuation('@'));
try testing.expect(isPunctuation('!'));
try testing.expect(isPunctuation(';'));
try testing.expect(isPunctuation(','));
try testing.expect(!isPunctuation('A'));
try testing.expect(!isPunctuation('8'));
}
/// 将 `ascii_string` 的小写副本写入 `output`。
/// 断言 `output.len >= ascii_string.len`。
pub fn lowerString(output: []u8, ascii_string: []const u8) []u8 {
std.debug.assert(output.len >= ascii_string.len);
for (ascii_string, 0..) |c, i| {
output[i] = toLower(c);
}
return output[0..ascii_string.len];
}
test lowerString {
var buf: [1024]u8 = undefined;
const result = lowerString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!");
try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result);
}
/// 分配 `ascii_string` 的小写副本。
/// 调用方拥有返回的字符串,必须使用 `allocator` 释放。
pub fn allocLowerString(allocator: std.mem.Allocator, ascii_string: []const u8) ![]u8 {
const result = try allocator.alloc(u8, ascii_string.len);
return lowerString(result, ascii_string);
}
test allocLowerString {
const result = try allocLowerString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result);
}
/// 将 `ascii_string` 的大写副本写入 `output`。
/// 断言 `output.len >= ascii_string.len`。
pub fn upperString(output: []u8, ascii_string: []const u8) []u8 {
std.debug.assert(output.len >= ascii_string.len);
for (ascii_string, 0..) |c, i| {
output[i] = toUpper(c);
}
return output[0..ascii_string.len];
}
test upperString {
var buf: [1024]u8 = undefined;
const result = upperString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!");
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result);
}
/// 分配 `ascii_string` 的大写副本。
/// 调用方拥有返回的字符串,必须使用 `allocator` 释放。
pub fn allocUpperString(allocator: std.mem.Allocator, ascii_string: []const u8) ![]u8 {
const result = try allocator.alloc(u8, ascii_string.len);
return upperString(result, ascii_string);
}
test allocUpperString {
const result = try allocUpperString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result);
}
/// 忽略大小写比较字符串 `a` 和 `b`,并返回它们是否相等。
pub fn eqlIgnoreCase(a: []const u8, b: []const u8) bool {
if (a.len != b.len) return false;
for (a, 0..) |a_c, i| {
if (toLower(a_c) != toLower(b[i])) return false;
}
return true;
}
test eqlIgnoreCase {
try std.testing.expect(eqlIgnoreCase("HEl💩Lo!", "hel💩lo!"));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "hello! "));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!"));
}
pub fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[0..needle.len], needle);
}
test startsWithIgnoreCase {
try std.testing.expect(startsWithIgnoreCase("boB", "Bo"));
try std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack"));
}
pub fn endsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[haystack.len - needle.len ..], needle);
}
test endsWithIgnoreCase {
try std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack"));
try std.testing.expect(!endsWithIgnoreCase("BoB", "Bo"));
}
/// 从索引 0 开始,在 `haystack` 中忽略大小写查找 `needle`。
pub fn findIgnoreCase(haystack: []const u8, needle: []const u8) ?usize {
return findIgnoreCasePos(haystack, 0, needle);
}
/// 从 `start_index` 开始,不区分大小写地在 `haystack` 中查找 `needle`。
/// 大输入使用 Boyer-Moore-Horspool 算法;小输入使用 `findIgnoreCasePosLinear`。
pub fn findIgnoreCasePos(haystack: []const u8, start_index: usize, needle: []const u8) ?usize {
if (needle.len > haystack.len) return null;
if (needle.len == 0) return start_index;
if (haystack.len < 52 or needle.len <= 4)
return findIgnoreCasePosLinear(haystack, start_index, needle);
var skip_table: [256]usize = undefined;
boyerMooreHorspoolPreprocessIgnoreCase(needle, skip_table[0..]);
var i: usize = start_index;
while (i <= haystack.len - needle.len) {
if (eqlIgnoreCase(haystack[i .. i + needle.len], needle)) return i;
i += skip_table[toLower(haystack[i + needle.len - 1])];
}
return null;
}
/// 可考虑改用 `findIgnoreCasePos`,它会对较大的输入
/// 自动使用更精细的算法。
pub fn findIgnoreCasePosLinear(haystack: []const u8, start_index: usize, needle: []const u8) ?usize {
var i: usize = start_index;
const end = haystack.len - needle.len;
while (i <= end) : (i += 1) {
if (eqlIgnoreCase(haystack[i .. i + needle.len], needle)) return i;
}
return null;
}
fn boyerMooreHorspoolPreprocessIgnoreCase(pattern: []const u8, table: *[256]usize) void {
for (table) |*c| {
c.* = pattern.len;
}
var i: usize = 0;
// 有意忽略最后一个元素,跳跃大小为 pattern.len。
// 这是 Boyer-Moore-Horspool 的标准实现方式。
while (i < pattern.len - 1) : (i += 1) {
table[toLower(pattern[i])] = pattern.len - 1 - i;
}
}
test findIgnoreCase {
try std.testing.expect(findIgnoreCase("one Two Three Four", "foUr").? == 14);
try std.testing.expect(findIgnoreCase("one two three FouR", "gOur") == null);
try std.testing.expect(findIgnoreCase("foO", "Foo").? == 0);
try std.testing.expect(findIgnoreCase("foo", "fool") == null);
try std.testing.expect(findIgnoreCase("FOO foo", "fOo").? == 0);
try std.testing.expect(findIgnoreCase("one two three four five six seven eight nine ten eleven", "ThReE fOUr").? == 8);
try std.testing.expect(findIgnoreCase("one two three four five six seven eight nine ten eleven", "Two tWo") == null);
}
/// 返回两个切片的字典序。时间复杂度 O(n)。
pub fn orderIgnoreCase(lhs: []const u8, rhs: []const u8) std.math.Order {
if (lhs.ptr != rhs.ptr) {
const n = @min(lhs.len, rhs.len);
var i: usize = 0;
while (i < n) : (i += 1) {
switch (std.math.order(toLower(lhs[i]), toLower(rhs[i]))) {
.eq => continue,
.lt => return .lt,
.gt => return .gt,
}
}
}
return std.math.order(lhs.len, rhs.len);
}
/// 返回两个以 NUL 结尾的多元素指针的字典序。时间复杂度 O(n)。
pub fn orderIgnoreCaseZ(lhs: [*:0]const u8, rhs: [*:0]const u8) std.math.Order {
return boundedOrderIgnoreCaseZ(lhs, rhs, std.math.maxInt(usize));
}
test orderIgnoreCaseZ {
try std.testing.expect(orderIgnoreCaseZ("aBcD", "Bee") == .lt);
try std.testing.expect(orderIgnoreCaseZ("AbC", "aBc") == .eq);
try std.testing.expect(orderIgnoreCaseZ("abC", "aBc0") == .lt);
try std.testing.expect(orderIgnoreCaseZ("", "") == .eq);
try std.testing.expect(orderIgnoreCaseZ("", "a") == .lt);
const s: [*:0]const u8 = "Abc";
try std.testing.expect(orderIgnoreCaseZ(s, s) == .eq);
}
/// 在指定上界内,返回两个以空字符终止的多项指针的字典序关系。O(n)。
pub fn boundedOrderIgnoreCaseZ(lhs: [*:0]const u8, rhs: [*:0]const u8, bound: usize) std.math.Order {
if (lhs == rhs) return .eq;
var i: usize = 0;
while (i < bound and toLower(lhs[i]) == toLower(rhs[i]) and lhs[i] != 0) : (i += 1) {}
return if (i < bound) std.math.order(toLower(lhs[i]), toLower(rhs[i])) else .eq;
}
/// 返回 `lhs` 的字典序是否小于 `rhs`。
pub fn lessThanIgnoreCase(lhs: []const u8, rhs: []const u8) bool {
return orderIgnoreCase(lhs, rhs) == .lt;
}
pub const HexEscape = struct {
bytes: []const u8,
charset: *const [16]u8,
pub const upper_charset = "0123456789ABCDEF";
pub const lower_charset = "0123456789abcdef";
pub fn format(se: HexEscape, w: *std.Io.Writer) std.Io.Writer.Error!void {
const charset = se.charset;
var buf: [4]u8 = undefined;
buf[0] = '\\';
buf[1] = 'x';
for (se.bytes) |c| {
if (std.ascii.isPrint(c)) {
try w.writeByte(c);
} else {
buf[2] = charset[c >> 4];
buf[3] = charset[c & 15];
try w.writeAll(&buf);
}
}
}
};
/// 将非 ASCII 字节替换为十六进制转义。
pub fn hexEscape(bytes: []const u8, case: std.fmt.Case) HexEscape {
return .{ .bytes = bytes, .charset = switch (case) {
.lower => HexEscape.lower_charset,
.upper => HexEscape.upper_charset,
} };
}
test hexEscape {
try std.testing.expectFmt("abc 123", "{f}", .{hexEscape("abc 123", .lower)});
try std.testing.expectFmt("ab\\xffc", "{f}", .{hexEscape("ab\xffc", .lower)});
try std.testing.expectFmt("abc 123", "{f}", .{hexEscape("abc 123", .upper)});
try std.testing.expectFmt("ab\\xFFc", "{f}", .{hexEscape("ab\xffc", .upper)});
}