authorgravatar for samy2014@free.frsamy007 <samy2014@free.fr> 2025-03-24 22:08:05+01:00
committergravatar for samy2014@free.frsamy007 <samy2014@free.fr> 2025-03-24 22:08:05+01:00
log4595b1ee06972df7ad913acb5349a1c5e7b07451
treee7a45cc40e5318a94b8d26de8140eb100479b38e
parentbe483dabc8fade06ad21b1e45c2bc731c4c4dd4f

std.mem.bytesAsSlice: fix to support zero-bytes sized types

also added a test for json parsing of zero sized type

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

lib/std/json/static_test.zig+16
......@@ -925,3 +925,19 @@ test "parse at comptime" {
925925 };
926926 comptime testing.expectEqual(@as(u64, 9999), config.uptime) catch unreachable;
927927}
928
929test "parse with zero-bit field" {
930 const str =
931 \\{
932 \\ "a": ["a", "a"],
933 \\ "b": "a"
934 \\}
935 ;
936 const ZeroSizedEnum = enum { a };
937 try testing.expectEqual(0, @sizeOf(ZeroSizedEnum));
938
939 const Inner = struct { a: []const ZeroSizedEnum, b: ZeroSizedEnum };
940 const expected: Inner = .{ .a = &.{ .a, .a }, .b = .a };
941
942 try testAllParseFunctions(Inner, expected, str);
943}
lib/std/mem.zig+15-1
......@@ -4219,10 +4219,11 @@ fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type {
42194219
42204220/// Given a slice of bytes, returns a slice of the specified type
42214221/// backed by those bytes, preserving pointer attributes.
4222/// If `T` is zero-bytes sized, the returned slice has a len of zero.
42224223pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes)) {
42234224 // let's not give an undefined pointer to @ptrCast
42244225 // it may be equal to zero and fail a null check
4225 if (bytes.len == 0) {
4226 if (bytes.len == 0 or @sizeOf(T) == 0) {
42264227 return &[0]T{};
42274228 }
42284229
......@@ -4300,6 +4301,19 @@ test "bytesAsSlice preserves pointer attributes" {
43004301 try testing.expectEqual(in.alignment, out.alignment);
43014302}
43024303
4304test "bytesAsSlice with zero-bit element type" {
4305 {
4306 const bytes = [_]u8{};
4307 const slice = bytesAsSlice(void, &bytes);
4308 try testing.expectEqual(0, slice.len);
4309 }
4310 {
4311 const bytes = [_]u8{ 0x01, 0x02, 0x03, 0x04 };
4312 const slice = bytesAsSlice(u0, &bytes);
4313 try testing.expectEqual(0, slice.len);
4314 }
4315}
4316
43034317fn SliceAsBytesReturnType(comptime Slice: type) type {
43044318 return CopyPtrAttrs(Slice, .slice, u8);
43054319}