Merge pull request #23700 from sorairolake/rename-trims

chore(std.mem): Rename `trimLeft` and `trimRight` to `trimStart` and `trimEnd`
This commit is contained in:
Alex Rønne Petersen 2025-05-12 17:11:52 +02:00 committed by GitHub
commit bc3c50c21e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 59 additions and 47 deletions

View file

@ -3274,7 +3274,7 @@ pub const StringTable = struct {
// Note: This is only the case for STRINGTABLE strings
const trimmed = trimToDoubleNUL(u16, utf16_string);
// We also want to trim any trailing NUL characters
break :trim std.mem.trimRight(u16, trimmed, &[_]u16{0});
break :trim std.mem.trimEnd(u16, trimmed, &[_]u16{0});
};
// String literals are limited to maxInt(u15) codepoints, so these UTF-16 encoded

View file

@ -140,7 +140,7 @@ const Block = struct {
/// (e.g. for a blockquote, this would be everything except the leading
/// `>`). If unsuccessful, returns null.
fn match(b: Block, line: []const u8) ?[]const u8 {
const unindented = mem.trimLeft(u8, line, " \t");
const unindented = mem.trimStart(u8, line, " \t");
const indent = line.len - unindented.len;
return switch (b.tag) {
.list => line,
@ -156,7 +156,7 @@ const Block = struct {
.table_row => null,
.heading => null,
.code_block => code_block: {
const trimmed = mem.trimRight(u8, unindented, " \t");
const trimmed = mem.trimEnd(u8, unindented, " \t");
if (mem.indexOfNone(u8, trimmed, "`") != null or trimmed.len != b.data.code_block.fence_len) {
const effective_indent = @min(indent, b.data.code_block.indent);
break :code_block line[effective_indent..];
@ -225,7 +225,7 @@ pub fn feedLine(p: *Parser, line: []const u8) Allocator.Error!void {
p.pending_blocks.items.len > 0 and
p.pending_blocks.getLast().tag == .paragraph)
{
try p.addScratchStringLine(mem.trimLeft(u8, rest_line, " \t"));
try p.addScratchStringLine(mem.trimStart(u8, rest_line, " \t"));
return;
}
@ -261,7 +261,7 @@ pub fn feedLine(p: *Parser, line: []const u8) Allocator.Error!void {
last_pending_block.canAccept()
else
.blocks;
const rest_line_trimmed = mem.trimLeft(u8, rest_line, " \t");
const rest_line_trimmed = mem.trimStart(u8, rest_line, " \t");
switch (can_accept) {
.blocks => {
// If we're inside a list item and the rest of the line is blank, it
@ -500,7 +500,7 @@ fn appendBlockStart(p: *Parser, block_start: BlockStart) !void {
}
fn startBlock(p: *Parser, line: []const u8) !?BlockStart {
const unindented = mem.trimLeft(u8, line, " \t");
const unindented = mem.trimStart(u8, line, " \t");
const indent = line.len - unindented.len;
if (isThematicBreak(line)) {
// Thematic breaks take precedence over list items.

View file

@ -364,7 +364,7 @@ pub fn init(stream: anytype, options: Options) InitError(@TypeOf(stream))!Client
};
P.AEAD.decrypt(cleartext, ciphertext, auth_tag, record_header, nonce, pv.server_handshake_key) catch
return error.TlsBadRecordMac;
cleartext_fragment_end += std.mem.trimRight(u8, cleartext, "\x00").len;
cleartext_fragment_end += std.mem.trimEnd(u8, cleartext, "\x00").len;
},
}
read_seq += 1;
@ -1353,7 +1353,7 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove
const cleartext = cleartext_buf[0..ciphertext.len];
P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, pv.server_key) catch
return error.TlsBadRecordMac;
const msg = mem.trimRight(u8, cleartext, "\x00");
const msg = mem.trimEnd(u8, cleartext, "\x00");
break :cleartext .{ msg[0 .. msg.len - 1], @enumFromInt(msg[msg.len - 1]) };
},
.tls_1_2 => {

View file

@ -2330,12 +2330,12 @@ pub const ar_hdr = extern struct {
ar_fmag: [2]u8,
pub fn date(self: ar_hdr) std.fmt.ParseIntError!u64 {
const value = mem.trimRight(u8, &self.ar_date, &[_]u8{0x20});
const value = mem.trimEnd(u8, &self.ar_date, &[_]u8{0x20});
return std.fmt.parseInt(u64, value, 10);
}
pub fn size(self: ar_hdr) std.fmt.ParseIntError!u32 {
const value = mem.trimRight(u8, &self.ar_size, &[_]u8{0x20});
const value = mem.trimEnd(u8, &self.ar_size, &[_]u8{0x20});
return std.fmt.parseInt(u32, value, 10);
}
@ -2369,7 +2369,7 @@ pub const ar_hdr = extern struct {
pub fn nameOffset(self: ar_hdr) std.fmt.ParseIntError!?u32 {
const value = &self.ar_name;
if (value[0] != '/') return null;
const trimmed = mem.trimRight(u8, value, &[_]u8{0x20});
const trimmed = mem.trimEnd(u8, value, &[_]u8{0x20});
return try std.fmt.parseInt(u32, trimmed[1..], 10);
}
};

View file

@ -1162,7 +1162,7 @@ pub fn formatFloatHexadecimal(
try writer.writeAll("0x");
try writer.writeByte(buf[0]);
const trimmed = mem.trimRight(u8, buf[1..], "0");
const trimmed = mem.trimEnd(u8, buf[1..], "0");
if (options.precision) |precision| {
if (precision > 0) try writer.writeAll(".");
} else if (trimmed.len > 0) {

View file

@ -473,7 +473,7 @@ pub const Response = struct {
};
if (first_line[8] != ' ') return error.HttpHeadersInvalid;
const status: http.Status = @enumFromInt(parseInt3(first_line[9..12]));
const reason = mem.trimLeft(u8, first_line[12..], " ");
const reason = mem.trimStart(u8, first_line[12..], " ");
res.version = version;
res.status = status;

View file

@ -1200,19 +1200,33 @@ pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {
}
/// Remove a set of values from the beginning of a slice.
pub fn trimLeft(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
pub fn trimStart(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
while (begin < slice.len and indexOfScalar(T, values_to_strip, slice[begin]) != null) : (begin += 1) {}
return slice[begin..];
}
test trimStart {
try testing.expectEqualSlices(u8, "foo\n ", trimStart(u8, " foo\n ", " \n"));
}
/// Deprecated: use `trimStart` instead.
pub const trimLeft = trimStart;
/// Remove a set of values from the end of a slice.
pub fn trimRight(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
pub fn trimEnd(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var end: usize = slice.len;
while (end > 0 and indexOfScalar(T, values_to_strip, slice[end - 1]) != null) : (end -= 1) {}
return slice[0..end];
}
test trimEnd {
try testing.expectEqualSlices(u8, " foo", trimEnd(u8, " foo\n ", " \n"));
}
/// Deprecated: use `trimEnd` instead.
pub const trimRight = trimEnd;
/// Remove a set of values from the beginning and end of a slice.
pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
@ -1223,8 +1237,6 @@ pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []co
}
test trim {
try testing.expectEqualSlices(u8, "foo\n ", trimLeft(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, " foo", trimRight(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, "foo", " \n"));
}

View file

@ -250,8 +250,8 @@ const Header = struct {
const raw = header.bytes[start..][0..len];
// Zero-filled octal number in ASCII. Each numeric field of width w
// contains w minus 1 digits, and a null
const ltrimmed = std.mem.trimLeft(u8, raw, "0 ");
const rtrimmed = std.mem.trimRight(u8, ltrimmed, " \x00");
const ltrimmed = std.mem.trimStart(u8, raw, "0 ");
const rtrimmed = std.mem.trimEnd(u8, ltrimmed, " \x00");
if (rtrimmed.len == 0) return 0;
return std.fmt.parseInt(u64, rtrimmed, 8) catch return error.TarHeader;
}

View file

@ -317,7 +317,7 @@ fn findNativeIncludeDirPosix(self: *LibCInstallation, args: FindNativeOptions) F
while (path_i < search_paths.items.len) : (path_i += 1) {
// search in reverse order
const search_path_untrimmed = search_paths.items[search_paths.items.len - path_i - 1];
const search_path = std.mem.trimLeft(u8, search_path_untrimmed, " ");
const search_path = std.mem.trimStart(u8, search_path_untrimmed, " ");
var search_dir = fs.cwd().openDir(search_path, .{}) catch |err| switch (err) {
error.FileNotFound,
error.NotDir,

View file

@ -1849,7 +1849,7 @@ fn parseTypeExpr(p: *Parse) Error!?Node.Index {
var sentinel: ?Node.Index = null;
if (p.eatToken(.identifier)) |ident| {
const ident_slice = p.source[p.tokenStart(ident)..p.tokenStart(ident + 1)];
if (!std.mem.eql(u8, std.mem.trimRight(u8, ident_slice, &std.ascii.whitespace), "c")) {
if (!std.mem.eql(u8, std.mem.trimEnd(u8, ident_slice, &std.ascii.whitespace), "c")) {
p.tok_i -= 1;
}
} else if (p.eatToken(.colon)) |_| {

View file

@ -2955,7 +2955,7 @@ fn renderComments(r: *Render, start: usize, end: usize) Error!bool {
const newline = if (newline_index) |i| comment_start + i else null;
const untrimmed_comment = tree.source[comment_start .. newline orelse tree.source.len];
const trimmed_comment = mem.trimRight(u8, untrimmed_comment, &std.ascii.whitespace);
const trimmed_comment = mem.trimEnd(u8, untrimmed_comment, &std.ascii.whitespace);
// Don't leave any whitespace at the start of the file
if (index != 0) {
@ -2976,7 +2976,7 @@ fn renderComments(r: *Render, start: usize, end: usize) Error!bool {
index = 1 + (newline orelse end - 1);
const comment_content = mem.trimLeft(u8, trimmed_comment["//".len..], &std.ascii.whitespace);
const comment_content = mem.trimStart(u8, trimmed_comment["//".len..], &std.ascii.whitespace);
if (ais.disabled_offset != null and mem.eql(u8, comment_content, "zig fmt: on")) {
// Write the source for which formatting was disabled directly
// to the underlying writer, fixing up invalid whitespace.
@ -3103,7 +3103,7 @@ fn tokenSliceForRender(tree: Ast, token_index: Ast.TokenIndex) []const u8 {
var ret = tree.tokenSlice(token_index);
switch (tree.tokenTag(token_index)) {
.container_doc_comment, .doc_comment => {
ret = mem.trimRight(u8, ret, &std.ascii.whitespace);
ret = mem.trimEnd(u8, ret, &std.ascii.whitespace);
},
else => {},
}

View file

@ -1182,13 +1182,13 @@ fn detectAbiAndDynamicLinker(
// We detected shebang, now parse entire line.
// Trim leading "#!", spaces and tabs.
const trimmed_line = mem.trimLeft(u8, content[2..], &.{ ' ', '\t' });
const trimmed_line = mem.trimStart(u8, content[2..], &.{ ' ', '\t' });
// This line can have:
// * Interpreter path only,
// * Interpreter path and arguments, all separated by space, tab or NUL character.
// And optionally newline at the end.
const path_maybe_args = mem.trimRight(u8, trimmed_line, "\n");
const path_maybe_args = mem.trimEnd(u8, trimmed_line, "\n");
// Separate path and args.
const path_end = mem.indexOfAny(u8, path_maybe_args, &.{ ' ', '\t', 0 }) orelse path_maybe_args.len;

View file

@ -59,7 +59,7 @@ pub fn getSdk(allocator: Allocator, target: Target) ?[]const u8 {
.Exited => |code| if (code != 0) return null,
else => return null,
}
return allocator.dupe(u8, mem.trimRight(u8, result.stdout, "\r\n")) catch null;
return allocator.dupe(u8, mem.trimEnd(u8, result.stdout, "\r\n")) catch null;
}
test {

View file

@ -362,8 +362,8 @@ fn CpuinfoParser(comptime impl: anytype) type {
while (true) {
const line = (try reader.readUntilDelimiterOrEof(&line_buf, '\n')) orelse break;
const colon_pos = mem.indexOfScalar(u8, line, ':') orelse continue;
const key = mem.trimRight(u8, line[0..colon_pos], " \t");
const value = mem.trimLeft(u8, line[colon_pos + 1 ..], " \t");
const key = mem.trimEnd(u8, line[0..colon_pos], " \t");
const value = mem.trimStart(u8, line[colon_pos + 1 ..], " \t");
if (!try obj.line_hook(key, value))
break;

View file

@ -192,7 +192,7 @@ pub const Diags = struct {
current_err.?.* = .{ .msg = duped_msg };
} else if (current_err != null) {
const context_prefix = ">>> ";
var trimmed = mem.trimRight(u8, line, &std.ascii.whitespace);
var trimmed = mem.trimEnd(u8, line, &std.ascii.whitespace);
if (mem.startsWith(u8, trimmed, context_prefix)) {
trimmed = trimmed[context_prefix.len..];
}

View file

@ -159,12 +159,12 @@ pub const ar_hdr = extern struct {
ar_fmag: [2]u8,
fn date(self: ar_hdr) !u64 {
const value = mem.trimRight(u8, &self.ar_date, &[_]u8{@as(u8, 0x20)});
const value = mem.trimEnd(u8, &self.ar_date, &[_]u8{@as(u8, 0x20)});
return std.fmt.parseInt(u64, value, 10);
}
fn size(self: ar_hdr) !u32 {
const value = mem.trimRight(u8, &self.ar_size, &[_]u8{@as(u8, 0x20)});
const value = mem.trimEnd(u8, &self.ar_size, &[_]u8{@as(u8, 0x20)});
return std.fmt.parseInt(u32, value, 10);
}
@ -178,7 +178,7 @@ pub const ar_hdr = extern struct {
fn nameLength(self: ar_hdr) !?u32 {
const value = &self.ar_name;
if (!mem.startsWith(u8, value, "#1/")) return null;
const trimmed = mem.trimRight(u8, self.ar_name["#1/".len..], &[_]u8{0x20});
const trimmed = mem.trimEnd(u8, self.ar_name["#1/".len..], &[_]u8{0x20});
return try std.fmt.parseInt(u32, trimmed, 10);
}
};

View file

@ -64,7 +64,7 @@ const Header = extern struct {
}
fn getValue(raw: []const u8) []const u8 {
return mem.trimRight(u8, raw, &[_]u8{@as(u8, 0x20)});
return mem.trimEnd(u8, raw, &[_]u8{@as(u8, 0x20)});
}
};
@ -162,7 +162,7 @@ pub fn parseObject(
.index => |index| n: {
const long_file_names = file_contents[archive.long_file_names.off..][0..archive.long_file_names.len];
const name = mem.sliceTo(long_file_names[index..], 0x0a);
break :n mem.trimRight(u8, name, "/");
break :n mem.trimEnd(u8, name, "/");
},
};

View file

@ -856,7 +856,7 @@ const TestManifest = struct {
fn next(self: *TrailingIterator) ?[]const u8 {
const next_inner = self.inner.next() orelse return null;
return if (next_inner.len == 2) "" else std.mem.trimRight(u8, next_inner[3..], " \t");
return if (next_inner.len == 2) "" else std.mem.trimEnd(u8, next_inner[3..], " \t");
}
};

View file

@ -20,7 +20,7 @@ pub fn main() !void {
try stdout.print("Input too long.\n", .{});
continue;
}
const line = std.mem.trimRight(u8, line_buf[0..amt], "\r\n");
const line = std.mem.trimEnd(u8, line_buf[0..amt], "\r\n");
const guess = fmt.parseUnsigned(u8, line, 10) catch {
try stdout.print("Invalid number.\n", .{});

View file

@ -943,10 +943,10 @@ fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
var cmd_cont: bool = false;
var iter = std.mem.splitScalar(u8, trimmed_shell_content, '\n');
while (iter.next()) |orig_line| {
const line = mem.trimRight(u8, orig_line, " \r");
const line = mem.trimEnd(u8, orig_line, " \r");
if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] != '\\') {
try out.writeAll("$ <kbd>");
const s = std.mem.trimLeft(u8, line[1..], " ");
const s = std.mem.trimStart(u8, line[1..], " ");
if (escape) {
try writeEscaped(out, s);
} else {
@ -955,7 +955,7 @@ fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
try out.writeAll("</kbd>" ++ "\n");
} else if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] == '\\') {
try out.writeAll("$ <kbd>");
const s = std.mem.trimLeft(u8, line[1..], " ");
const s = std.mem.trimStart(u8, line[1..], " ");
if (escape) {
try writeEscaped(out, s);
} else {

View file

@ -1109,10 +1109,10 @@ fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
var cmd_cont: bool = false;
var iter = std.mem.splitScalar(u8, trimmed_shell_content, '\n');
while (iter.next()) |orig_line| {
const line = mem.trimRight(u8, orig_line, " \r");
const line = mem.trimEnd(u8, orig_line, " \r");
if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] != '\\') {
try out.writeAll("$ <kbd>");
const s = std.mem.trimLeft(u8, line[1..], " ");
const s = std.mem.trimStart(u8, line[1..], " ");
if (escape) {
try writeEscaped(out, s);
} else {
@ -1121,7 +1121,7 @@ fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
try out.writeAll("</kbd>" ++ "\n");
} else if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] == '\\') {
try out.writeAll("$ <kbd>");
const s = std.mem.trimLeft(u8, line[1..], " ");
const s = std.mem.trimStart(u8, line[1..], " ");
if (escape) {
try writeEscaped(out, s);
} else {

View file

@ -670,7 +670,7 @@ const Case = struct {
if (std.mem.startsWith(u8, line, "#")) {
var line_it = std.mem.splitScalar(u8, line, '=');
const key = line_it.first()[1..];
const val = std.mem.trimRight(u8, line_it.rest(), "\r"); // windows moment
const val = std.mem.trimEnd(u8, line_it.rest(), "\r"); // windows moment
if (val.len == 0) {
fatal("line {d}: missing value", .{line_n});
} else if (std.mem.eql(u8, key, "target")) {
@ -720,7 +720,7 @@ const Case = struct {
while (true) {
const next_line_raw = it.peek() orelse fatal("line {d}: unexpected EOF", .{line_n});
const next_line = std.mem.trimRight(u8, next_line_raw, "\r");
const next_line = std.mem.trimEnd(u8, next_line_raw, "\r");
if (std.mem.startsWith(u8, next_line, "#")) break;
_ = it.next();
@ -759,7 +759,7 @@ const Case = struct {
if (!std.mem.startsWith(u8, next_line, "#")) break;
var new_line_it = std.mem.splitScalar(u8, next_line, '=');
const new_key = new_line_it.first()[1..];
const new_val = std.mem.trimRight(u8, new_line_it.rest(), "\r");
const new_val = std.mem.trimEnd(u8, new_line_it.rest(), "\r");
if (new_val.len == 0) break;
if (!std.mem.eql(u8, new_key, "expect_error")) break;
@ -774,7 +774,7 @@ const Case = struct {
if (!std.mem.startsWith(u8, next_line, "#")) break;
var new_line_it = std.mem.splitScalar(u8, next_line, '=');
const new_key = new_line_it.first()[1..];
const new_val = std.mem.trimRight(u8, new_line_it.rest(), "\r");
const new_val = std.mem.trimEnd(u8, new_line_it.rest(), "\r");
if (new_val.len == 0) break;
if (!std.mem.eql(u8, new_key, "expect_compile_log")) break;