authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-06-24 14:15:53-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-06-24 14:16:50-07:00
log243192c60ec4e1f09042ff3cfd0542972c639566
tree5d2985dab3fa6657c3025e811c12c96c97108496
parent745a029b9e3f1b0dc045067cc3ce5c3883bc430d

std.mem.Allocator: add unit tests for print and printSentinel


1 files changed, 22 insertions(+), 2 deletions(-)

lib/std/mem/Allocator.zig+22-2
......@@ -1,11 +1,12 @@
11//! The standard memory allocation interface.
2const Allocator = @This();
3
4const builtin = @import("builtin");
25
36const std = @import("../std.zig");
47const assert = std.debug.assert;
58const math = std.math;
69const mem = std.mem;
7const Allocator = @This();
8const builtin = @import("builtin");
910const Alignment = std.mem.Alignment;
1011
1112pub const Error = error{OutOfMemory};
......@@ -487,6 +488,15 @@ pub fn print(a: Allocator, comptime format: []const u8, args: anytype) Error![]u
487488 return aw.toOwnedSlice();
488489}
489490
491test print {
492 const x: i32 = -1;
493 const y: []const u8 = "hi";
494 const a = std.testing.allocator;
495 const s = try print(a, "{d}={s}", .{ x, y });
496 defer free(a, s);
497 try std.testing.expectEqualStrings("-1=hi", s);
498}
499
490500/// Like `print` but returned slice has the provided sentinel.
491501///
492502/// Returned slice can be deallocated with `free`. If an arena-style allocator
......@@ -507,6 +517,16 @@ pub fn printSentinel(
507517 return aw.toOwnedSliceSentinel(sentinel);
508518}
509519
520test printSentinel {
521 const x: i32 = -1;
522 const y: []const u8 = "hi";
523 const a = std.testing.allocator;
524 const s = try printSentinel(a, "{d}={s}", .{ x, y }, 0);
525 defer free(a, s);
526 try std.testing.expectEqualStrings("-1=hi", s);
527 try std.testing.expectEqual(0, s[s.len]);
528}
529
510530/// An allocator that always fails to allocate.
511531pub const failing: Allocator = .{
512532 .ptr = undefined,