| ... | ... | @@ -2914,6 +2914,45 @@ test "null terminated slice" { |
| 2914 | 2914 | |
| 2915 | 2915 | try expect(slice.len == 5); |
| 2916 | 2916 | try expect(slice[5] == 0); |
| 2917 | } |
| 2918 | {#code_end#} |
| 2919 | <p> |
| 2920 | Sentinel-terminated slices can also be created using a variation of the slice syntax |
| 2921 | {#syntax#}data[start..end :x]{#endsyntax#}, where {#syntax#}data{#endsyntax#} is a many-item pointer, |
| 2922 | array or slice and {#syntax#}x{#endsyntax#} is the sentinel value. |
| 2923 | </p> |
| 2924 | {#code_begin|test|null_terminated_slicing#} |
| 2925 | const std = @import("std"); |
| 2926 | const expect = std.testing.expect; |
| 2927 | |
| 2928 | test "null terminated slicing" { |
| 2929 | var array = [_]u8{ 3, 2, 1, 0, 3, 2, 1, 0 }; |
| 2930 | var runtime_length: usize = 3; |
| 2931 | const slice = array[0..runtime_length :0]; |
| 2932 | |
| 2933 | try expect(@TypeOf(slice) == [:0]u8); |
| 2934 | try expect(slice.len == 3); |
| 2935 | } |
| 2936 | {#code_end#} |
| 2937 | <p> |
| 2938 | Sentinel-terminated slicing asserts that the element in the sentinel position of the backing data is |
| 2939 | actually the sentinel value. If this is not the case, safety-protected {#link|Undefined Behavior#} results. |
| 2940 | </p> |
| 2941 | {#code_begin|test_safety|sentinel mismatch#} |
| 2942 | const std = @import("std"); |
| 2943 | const expect = std.testing.expect; |
| 2944 | |
| 2945 | test "sentinel mismatch" { |
| 2946 | var array = [_]u8{ 3, 2, 1, 0 }; |
| 2947 | |
| 2948 | // Creating a sentinel-terminated slice from the array with a length of 2 |
| 2949 | // will result in the value `1` occupying the sentinel element position. |
| 2950 | // This does not match the indicated sentinel value of `0` and will lead |
| 2951 | // to a runtime panic. |
| 2952 | var runtime_length: usize = 2; |
| 2953 | const slice = array[0..runtime_length :0]; |
| 2954 | |
| 2955 | _ = slice; |
| 2917 | 2956 | } |
| 2918 | 2957 | {#code_end#} |
| 2919 | 2958 | {#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Arrays#} |