diff options
| author | Andrew Kelley <andrew@ziglang.org> | 2020-03-13 15:17:53 -0400 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2020-03-13 15:17:53 -0400 |
| commit | 656ba530d80e67bc7bb9c40e5c2db26a40743a15 (patch) | |
| tree | 767f4d57000922cf122ae965dc825f87c62ec64e /lib/std/mem.zig | |
| parent | 96c07674fc2293fa040212ab797c05436dc515b1 (diff) | |
| parent | 3eff77bfb52accbc16eb831753ff4917fc2b4873 (diff) | |
| download | zig-656ba530d80e67bc7bb9c40e5c2db26a40743a15.tar.gz zig-656ba530d80e67bc7bb9c40e5c2db26a40743a15.zip | |
Merge remote-tracking branch 'origin/master' into llvm10
Diffstat (limited to 'lib/std/mem.zig')
| -rw-r--r-- | lib/std/mem.zig | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 4da7829570..c767765652 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -105,6 +105,20 @@ pub const Allocator = struct { return self.alignedAlloc(T, null, n); } + /// Allocates an array of `n + 1` items of type `T` and sets the first `n` + /// items to `undefined` and the last item to `sentinel`. Depending on the + /// Allocator implementation, it may be required to call `free` once the + /// memory is no longer needed, to avoid a resource leak. If the + /// `Allocator` implementation is unknown, then correct code will + /// call `free` when done. + /// + /// For allocating a single item, see `create`. + pub fn allocSentinel(self: *Allocator, comptime Elem: type, n: usize, comptime sentinel: Elem) Error![:sentinel]Elem { + var ptr = try self.alloc(Elem, n + 1); + ptr[n] = sentinel; + return ptr[0 .. n :sentinel]; + } + pub fn alignedAlloc( self: *Allocator, comptime T: type, @@ -921,6 +935,9 @@ pub fn writeInt(comptime T: type, buffer: *[@divExact(T.bit_count, 8)]u8, value: pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void { assert(buffer.len >= @divExact(T.bit_count, 8)); + if (T.bit_count == 0) + return set(u8, buffer, 0); + // TODO I want to call writeIntLittle here but comptime eval facilities aren't good enough const uint = std.meta.IntType(false, T.bit_count); var bits = @truncate(uint, value); @@ -938,6 +955,9 @@ pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void { pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void { assert(buffer.len >= @divExact(T.bit_count, 8)); + if (T.bit_count == 0) + return set(u8, buffer, 0); + // TODO I want to call writeIntBig here but comptime eval facilities aren't good enough const uint = std.meta.IntType(false, T.bit_count); var bits = @truncate(uint, value); @@ -1807,7 +1827,7 @@ test "sliceAsBytes" { } test "sliceAsBytes with sentinel slice" { - const empty_string:[:0]const u8 = ""; + const empty_string: [:0]const u8 = ""; const bytes = sliceAsBytes(empty_string); testing.expect(bytes.len == 0); } |
