Sentinel-terminate file contents (#11738)

This commit is contained in:
Jarred Sumner
2024-06-09 19:37:57 -07:00
committed by GitHub
parent 4786c6139e
commit 99b9be7a34

View File

@@ -2958,7 +2958,7 @@ pub const File = struct {
/// 2. Open a file for reading
/// 2. Read the file to a buffer
/// 3. Return the File handle and the buffer
pub fn readFromUserInput(dir_fd: anytype, input_path: anytype, allocator: std.mem.Allocator) Maybe([]u8) {
pub fn readFromUserInput(dir_fd: anytype, input_path: anytype, allocator: std.mem.Allocator) Maybe([:0]u8) {
var buf: bun.PathBuffer = undefined;
const normalized = bun.path.joinAbsStringBufZ(
bun.fs.FileSystem.instance.top_level_dir,
@@ -2972,7 +2972,7 @@ pub const File = struct {
/// 1. Open a file for reading
/// 2. Read the file to a buffer
/// 3. Return the File handle and the buffer
pub fn readFileFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe(struct { File, []u8 }) {
pub fn readFileFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe(struct { File, [:0]u8 }) {
const ElementType = std.meta.Elem(@TypeOf(path));
const rc = brk: {
@@ -3000,14 +3000,22 @@ pub const File = struct {
return .{ .err = err };
}
return .{ .result = .{ this, result.bytes.items } };
if (result.bytes.items.len == 0) {
// Don't allocate an empty string.
// We won't be modifying an empty slice, anyway.
return .{ .result = .{ this, @ptrCast(@constCast("")) } };
}
result.bytes.append(0) catch bun.outOfMemory();
return .{ .result = .{ this, result.bytes.items[0 .. result.bytes.items.len - 1 :0] } };
}
/// 1. Open a file for reading relative to a directory
/// 2. Read the file to a buffer
/// 3. Close the file
/// 4. Return the buffer
pub fn readFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe([]u8) {
pub fn readFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe([:0]u8) {
const file, const bytes = switch (readFileFrom(dir_fd, path, allocator)) {
.err => |err| return .{ .err = err },
.result => |result| result,