| ... | @@ -1780,10 +1780,11 @@ fn SliceAsBytesReturnType(comptime sliceType: type) type { | ... | @@ -1780,10 +1780,11 @@ fn SliceAsBytesReturnType(comptime sliceType: type) type { |
| 1780 | | 1780 | |
| 1781 | pub fn sliceAsBytes(slice: var) SliceAsBytesReturnType(@TypeOf(slice)) { | 1781 | pub fn sliceAsBytes(slice: var) SliceAsBytesReturnType(@TypeOf(slice)) { |
| 1782 | const actualSlice = if (comptime trait.isPtrTo(.Array)(@TypeOf(slice))) slice[0..] else slice; | 1782 | const actualSlice = if (comptime trait.isPtrTo(.Array)(@TypeOf(slice))) slice[0..] else slice; |
| | 1783 | const actualSliceTypeInfo = @typeInfo(@TypeOf(actualSlice)).Pointer; |
| 1783 | | 1784 | |
| 1784 | // let's not give an undefined pointer to @ptrCast | 1785 | // let's not give an undefined pointer to @ptrCast |
| 1785 | // it may be equal to zero and fail a null check | 1786 | // it may be equal to zero and fail a null check |
| 1786 | if (actualSlice.len == 0) { | 1787 | if (actualSlice.len == 0 and actualSliceTypeInfo.sentinel == null) { |
| 1787 | return &[0]u8{}; | 1788 | return &[0]u8{}; |
| 1788 | } | 1789 | } |
| 1789 | | 1790 | |
| ... | @@ -1805,6 +1806,12 @@ test "sliceAsBytes" { | ... | @@ -1805,6 +1806,12 @@ test "sliceAsBytes" { |
| 1805 | })); | 1806 | })); |
| 1806 | } | 1807 | } |
| 1807 | | 1808 | |
| | 1809 | test "sliceAsBytes with sentinel slice" { |
| | 1810 | const empty_string:[:0]const u8 = ""; |
| | 1811 | const bytes = sliceAsBytes(empty_string); |
| | 1812 | testing.expect(bytes.len == 0); |
| | 1813 | } |
| | 1814 | |
| 1808 | test "sliceAsBytes packed struct at runtime and comptime" { | 1815 | test "sliceAsBytes packed struct at runtime and comptime" { |
| 1809 | const Foo = packed struct { | 1816 | const Foo = packed struct { |
| 1810 | a: u4, | 1817 | a: u4, |
| ... | @@ -1941,3 +1948,8 @@ test "isAligned" { | ... | @@ -1941,3 +1948,8 @@ test "isAligned" { |
| 1941 | testing.expect(!isAligned(4, 8)); | 1948 | testing.expect(!isAligned(4, 8)); |
| 1942 | testing.expect(!isAligned(4, 16)); | 1949 | testing.expect(!isAligned(4, 16)); |
| 1943 | } | 1950 | } |
| | 1951 | |
| | 1952 | test "freeing empty string with null-terminated sentinel" { |
| | 1953 | const empty_string = try dupeZ(testing.allocator, u8, ""); |
| | 1954 | testing.allocator.free(empty_string); |
| | 1955 | } |