Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use std.Buffer even less #4665

Closed
wants to merge 7 commits into from
8 changes: 4 additions & 4 deletions doc/docgen.zig
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
var last_action = Action.Open;
var last_columns: ?u8 = null;

var toc_buf = try std.Buffer.initSize(allocator, 0);
var toc_buf = std.ArrayList(u8).init(allocator);
defer toc_buf.deinit();

var toc = toc_buf.outStream();
Expand Down Expand Up @@ -607,7 +607,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
}

fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
var buf = try std.Buffer.initSize(allocator, 0);
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();

const out = buf.outStream();
Expand All @@ -626,7 +626,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
}

fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
var buf = try std.Buffer.initSize(allocator, 0);
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();

const out = buf.outStream();
Expand Down Expand Up @@ -672,7 +672,7 @@ test "term color" {
}

fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
var buf = try std.Buffer.initSize(allocator, 0);
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();

var out = buf.outStream();
Expand Down
27 changes: 27 additions & 0 deletions lib/std/array_list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,22 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
self.len += items.len;
}

pub usingnamespace if (T == u8)
struct {
/// Same as `append` except it returns the number of bytes written, which is always the same
/// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
fn appendWrite(self: *Self, m: []const u8) !usize {
try self.appendSlice(m);
return m.len;
}

pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) {
return .{ .context = self };
}
Comment on lines +196 to +203
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's nice addition!
But maybe add a new structure with all necessary functions?
Something like std.io.MemoryStream.

}
else
struct {};

/// Append a value to the list `n` times. Allocates more memory
/// as necessary.
pub fn appendNTimes(self: *Self, value: T, n: usize) !void {
Expand Down Expand Up @@ -479,3 +495,14 @@ test "std.ArrayList: ArrayList(T) of struct T" {
try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(testing.allocator) });
testing.expect(root.sub_items.items[0].integer == 42);
}

test "std.ArrayList(u8) implements outStream" {
var buffer = ArrayList(u8).init(std.testing.allocator);
defer buffer.deinit();

const x: i32 = 42;
const y: i32 = 1234;
try buffer.outStream().print("x: {}\ny: {}\n", .{ x, y });

testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.span());
}
21 changes: 11 additions & 10 deletions lib/std/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1139,7 +1139,7 @@ pub const LibExeObjStep = struct {
out_lib_filename: []const u8,
out_pdb_filename: []const u8,
packages: ArrayList(Pkg),
build_options_contents: std.Buffer,
build_options_contents: std.ArrayList(u8),
system_linker_hack: bool = false,

object_src: []const u8,
Expand Down Expand Up @@ -1274,7 +1274,7 @@ pub const LibExeObjStep = struct {
.lib_paths = ArrayList([]const u8).init(builder.allocator),
.framework_dirs = ArrayList([]const u8).init(builder.allocator),
.object_src = undefined,
.build_options_contents = std.Buffer.initSize(builder.allocator, 0) catch unreachable,
.build_options_contents = std.ArrayList(u8).init(builder.allocator),
.c_std = Builder.CStd.C99,
.override_lib_dir = null,
.main_pkg_path = null,
Expand Down Expand Up @@ -1847,7 +1847,7 @@ pub const LibExeObjStep = struct {
}
}

if (self.build_options_contents.len() > 0) {
if (self.build_options_contents.len > 0) {
const build_options_file = try fs.path.join(
builder.allocator,
&[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) },
Expand Down Expand Up @@ -1960,22 +1960,23 @@ pub const LibExeObjStep = struct {
try zig_args.append(cross.cpu.model.name);
}
} else {
var mcpu_buffer = try std.Buffer.init(builder.allocator, "-mcpu=");
try mcpu_buffer.append(cross.cpu.model.name);
var mcpu_buffer = std.ArrayList(u8).init(builder.allocator);
errdefer mcpu_buffer.deinit();

try mcpu_buffer.outStream().print("-mcpu={}", .{cross.cpu.model.name});

for (all_features) |feature, i_usize| {
const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize);
const in_cpu_set = populated_cpu_features.isEnabled(i);
const in_actual_set = cross.cpu.features.isEnabled(i);
if (in_cpu_set and !in_actual_set) {
try mcpu_buffer.appendByte('-');
try mcpu_buffer.append(feature.name);
try mcpu_buffer.outStream().print("-{}", .{feature.name});
} else if (!in_cpu_set and in_actual_set) {
try mcpu_buffer.appendByte('+');
try mcpu_buffer.append(feature.name);
try mcpu_buffer.outStream().print("+{}", .{feature.name});
}
}
try zig_args.append(mcpu_buffer.span());

try zig_args.append(mcpu_buffer.toOwnedSlice());
}

if (self.target.dynamic_linker.get()) |dynamic_linker| {
Expand Down
17 changes: 8 additions & 9 deletions lib/std/child_process.zig
Original file line number Diff line number Diff line change
Expand Up @@ -758,37 +758,36 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1

/// Caller must dealloc.
/// Guarantees a null byte at result[result.len].
fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![]u8 {
fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 {
var buf = try Buffer.initSize(allocator, 0);
defer buf.deinit();

var buf_stream = buf.outStream();
const buf_stream = buf.outStream();

for (argv) |arg, arg_i| {
if (arg_i != 0) try buf.appendByte(' ');
if (arg_i != 0) try buf_stream.writeByte(' ');
if (mem.indexOfAny(u8, arg, " \t\n\"") == null) {
try buf.append(arg);
try buf_stream.writeAll(arg);
continue;
}
try buf.appendByte('"');
try buf_stream.writeByte('"');
var backslash_count: usize = 0;
for (arg) |byte| {
switch (byte) {
'\\' => backslash_count += 1,
'"' => {
try buf_stream.writeByteNTimes('\\', backslash_count * 2 + 1);
try buf.appendByte('"');
try buf_stream.writeByte('"');
backslash_count = 0;
},
else => {
try buf_stream.writeByteNTimes('\\', backslash_count);
try buf.appendByte(byte);
try buf_stream.writeByte(byte);
backslash_count = 0;
},
}
}
try buf_stream.writeByteNTimes('\\', backslash_count * 2);
try buf.appendByte('"');
try buf_stream.writeByte('"');
}

return buf.toOwnedSlice();
Expand Down
8 changes: 4 additions & 4 deletions lib/std/target.zig
Original file line number Diff line number Diff line change
Expand Up @@ -967,15 +967,15 @@ pub const Target = struct {

pub const stack_align = 16;

pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 {
pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 These I agree to change

return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator);
}

pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![:0]u8 {
return std.fmt.allocPrint0(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });
pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 {
return std.fmt.allocPrint(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });
}

pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 {
pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi);
}

Expand Down
18 changes: 10 additions & 8 deletions lib/std/zig/cross_target.zig
Original file line number Diff line number Diff line change
Expand Up @@ -495,16 +495,18 @@ pub const CrossTarget = struct {
return self.isNativeCpu() and self.isNativeOs() and self.abi == null;
}

pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![:0]u8 {
pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![]u8 {
if (self.isNative()) {
return mem.dupeZ(allocator, u8, "native");
return mem.dupe(allocator, u8, "native");
}

const arch_name = if (self.cpu_arch) |arch| @tagName(arch) else "native";
const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native";

var result = try std.Buffer.allocPrint(allocator, "{}-{}", .{ arch_name, os_name });
defer result.deinit();
var result = std.ArrayList(u8).init(allocator);
errdefer result.deinit();

try result.outStream().print("{}-{}", .{ arch_name, os_name });

// The zig target syntax does not allow specifying a max os version with no min, so
// if either are present, we need the min.
Expand Down Expand Up @@ -532,13 +534,13 @@ pub const CrossTarget = struct {
return result.toOwnedSlice();
}

pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 {
pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
// TODO is there anything else worthy of the description that is not
// already captured in the triple?
return self.zigTriple(allocator);
}

pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 {
pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi());
}

Expand All @@ -549,7 +551,7 @@ pub const CrossTarget = struct {
pub const VcpkgLinkage = std.builtin.LinkMode;

/// Returned slice must be freed by the caller.
pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![:0]u8 {
pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![]u8 {
const arch = switch (self.getCpuArch()) {
.i386 => "x86",
.x86_64 => "x64",
Expand Down Expand Up @@ -580,7 +582,7 @@ pub const CrossTarget = struct {
.Dynamic => "",
};

return std.fmt.allocPrint0(allocator, "{}-{}{}", .{ arch, os, static_suffix });
return std.fmt.allocPrint(allocator, "{}-{}{}", .{ arch, os, static_suffix });
}

pub const Executor = union(enum) {
Expand Down
2 changes: 1 addition & 1 deletion lib/std/zig/parser_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2953,7 +2953,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
return error.ParseError;
}

var buffer = try std.Buffer.initSize(allocator, 0);
var buffer = std.ArrayList(u8).init(allocator);
errdefer buffer.deinit();

anything_changed.* = try std.zig.render(allocator, buffer.outStream(), tree);
Expand Down
4 changes: 2 additions & 2 deletions src-self-hosted/errmsg.zig
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ pub const Msg = struct {
parse_error: *const ast.Error,
) !*Msg {
const loc_token = parse_error.loc();
var text_buf = try std.Buffer.initSize(comp.gpa(), 0);
var text_buf = std.ArrayList(u8).init(comp.gpa());
defer text_buf.deinit();

const realpath_copy = try mem.dupe(comp.gpa(), u8, tree_scope.root().realpath);
Expand Down Expand Up @@ -197,7 +197,7 @@ pub const Msg = struct {
realpath: []const u8,
) !*Msg {
const loc_token = parse_error.loc();
var text_buf = try std.Buffer.initSize(allocator, 0);
var text_buf = std.ArrayList(u8).init(allocator);
defer text_buf.deinit();

const realpath_copy = try mem.dupe(allocator, u8, realpath);
Expand Down