| ... | @@ -1,11 +1,12 @@ | ... | @@ -1,11 +1,12 @@ |
| 1 | //! The standard memory allocation interface. | 1 | //! The standard memory allocation interface. |
| | 2 | const Allocator = @This(); |
| | 3 | |
| | 4 | const builtin = @import("builtin"); |
| 2 | | 5 | |
| 3 | const std = @import("../std.zig"); | 6 | const std = @import("../std.zig"); |
| 4 | const assert = std.debug.assert; | 7 | const assert = std.debug.assert; |
| 5 | const math = std.math; | 8 | const math = std.math; |
| 6 | const mem = std.mem; | 9 | const mem = std.mem; |
| 7 | const Allocator = @This(); | | |
| 8 | const builtin = @import("builtin"); | | |
| 9 | const Alignment = std.mem.Alignment; | 10 | const Alignment = std.mem.Alignment; |
| 10 | | 11 | |
| 11 | pub const Error = error{OutOfMemory}; | 12 | pub const Error = error{OutOfMemory}; |
| ... | @@ -487,6 +488,15 @@ pub fn print(a: Allocator, comptime format: []const u8, args: anytype) Error![]u | ... | @@ -487,6 +488,15 @@ pub fn print(a: Allocator, comptime format: []const u8, args: anytype) Error![]u |
| 487 | return aw.toOwnedSlice(); | 488 | return aw.toOwnedSlice(); |
| 488 | } | 489 | } |
| 489 | | 490 | |
| | 491 | test 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 | |
| 490 | /// Like `print` but returned slice has the provided sentinel. | 500 | /// Like `print` but returned slice has the provided sentinel. |
| 491 | /// | 501 | /// |
| 492 | /// Returned slice can be deallocated with `free`. If an arena-style allocator | 502 | /// Returned slice can be deallocated with `free`. If an arena-style allocator |
| ... | @@ -507,6 +517,16 @@ pub fn printSentinel( | ... | @@ -507,6 +517,16 @@ pub fn printSentinel( |
| 507 | return aw.toOwnedSliceSentinel(sentinel); | 517 | return aw.toOwnedSliceSentinel(sentinel); |
| 508 | } | 518 | } |
| 509 | | 519 | |
| | 520 | test 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 | |
| 510 | /// An allocator that always fails to allocate. | 530 | /// An allocator that always fails to allocate. |
| 511 | pub const failing: Allocator = .{ | 531 | pub const failing: Allocator = .{ |
| 512 | .ptr = undefined, | 532 | .ptr = undefined, |