authorgravatar for michael@michaelbyrne.ioMichael Byrne <michael@michaelbyrne.io> 2021-12-04 12:37:48+11:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-12-03 20:37:48-05:00
log7e2fae10c9ce320d7a407856cbb935f9a95c5443
tree70801d3a5436eea5c13390556d60c2a7f510b27d
parent2a0adef583d96d87fdca1bc536269931486e4349
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Add documentation for sentinel-terminated slicing (#10010)

closes #9680

1 files changed, 39 insertions(+), 0 deletions(-)

doc/langref.html.in+39
......@@ -2914,6 +2914,45 @@ test "null terminated slice" {
29142914
29152915 try expect(slice.len == 5);
29162916 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#}
2925const std = @import("std");
2926const expect = std.testing.expect;
2927
2928test "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#}
2942const std = @import("std");
2943const expect = std.testing.expect;
2944
2945test "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;
29172956}
29182957 {#code_end#}
29192958 {#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Arrays#}