| ... | @@ -4219,10 +4219,11 @@ fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type { | ... | @@ -4219,10 +4219,11 @@ fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type { |
| 4219 | | 4219 | |
| 4220 | /// Given a slice of bytes, returns a slice of the specified type | 4220 | /// Given a slice of bytes, returns a slice of the specified type |
| 4221 | /// backed by those bytes, preserving pointer attributes. | 4221 | /// backed by those bytes, preserving pointer attributes. |
| | 4222 | /// If `T` is zero-bytes sized, the returned slice has a len of zero. |
| 4222 | pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes)) { | 4223 | pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes)) { |
| 4223 | // let's not give an undefined pointer to @ptrCast | 4224 | // let's not give an undefined pointer to @ptrCast |
| 4224 | // it may be equal to zero and fail a null check | 4225 | // 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) { |
| 4226 | return &[0]T{}; | 4227 | return &[0]T{}; |
| 4227 | } | 4228 | } |
| 4228 | | 4229 | |
| ... | @@ -4300,6 +4301,19 @@ test "bytesAsSlice preserves pointer attributes" { | ... | @@ -4300,6 +4301,19 @@ test "bytesAsSlice preserves pointer attributes" { |
| 4300 | try testing.expectEqual(in.alignment, out.alignment); | 4301 | try testing.expectEqual(in.alignment, out.alignment); |
| 4301 | } | 4302 | } |
| 4302 | | 4303 | |
| | 4304 | test "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 | |
| 4303 | fn SliceAsBytesReturnType(comptime Slice: type) type { | 4317 | fn SliceAsBytesReturnType(comptime Slice: type) type { |
| 4304 | return CopyPtrAttrs(Slice, .slice, u8); | 4318 | return CopyPtrAttrs(Slice, .slice, u8); |
| 4305 | } | 4319 | } |