authorgravatar for techatrix@mailbox.orgTechatrix <techatrix@mailbox.org> 2024-02-25 12:07:12+01:00
committergravatar for techatrix@mailbox.orgTechatrix <techatrix@mailbox.org> 2024-02-25 12:07:12+01:00
log9727931fda50ae412c47bfd40ad1d1dcd06aada0
tree61a4756890a3f39d21a6820adfc5f527bcbc440d
parent88b3c144265b0e22250f21809bbf9329ecfcfd6f

fix integer overflow in indexOfPosLinear when needle.len > haystack.len


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

lib/std/mem.zig+21
......@@ -1346,6 +1346,7 @@ pub fn lastIndexOfLinear(comptime T: type, haystack: []const T, needle: []const
13461346/// Consider using `indexOfPos` instead of this, which will automatically use a
13471347/// more sophisticated algorithm on larger inputs.
13481348pub fn indexOfPosLinear(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
1349 if (needle.len > haystack.len) return null;
13491350 var i: usize = start_index;
13501351 const end = haystack.len - needle.len;
13511352 while (i <= end) : (i += 1) {
......@@ -1354,6 +1355,26 @@ pub fn indexOfPosLinear(comptime T: type, haystack: []const T, start_index: usiz
13541355 return null;
13551356}
13561357
1358test indexOfPosLinear {
1359 try testing.expectEqual(0, indexOfPosLinear(u8, "", 0, ""));
1360 try testing.expectEqual(0, indexOfPosLinear(u8, "123", 0, ""));
1361
1362 try testing.expectEqual(null, indexOfPosLinear(u8, "", 0, "1"));
1363 try testing.expectEqual(0, indexOfPosLinear(u8, "1", 0, "1"));
1364 try testing.expectEqual(null, indexOfPosLinear(u8, "2", 0, "1"));
1365 try testing.expectEqual(1, indexOfPosLinear(u8, "21", 0, "1"));
1366 try testing.expectEqual(null, indexOfPosLinear(u8, "222", 0, "1"));
1367
1368 try testing.expectEqual(null, indexOfPosLinear(u8, "", 0, "12"));
1369 try testing.expectEqual(null, indexOfPosLinear(u8, "1", 0, "12"));
1370 try testing.expectEqual(null, indexOfPosLinear(u8, "2", 0, "12"));
1371 try testing.expectEqual(0, indexOfPosLinear(u8, "12", 0, "12"));
1372 try testing.expectEqual(null, indexOfPosLinear(u8, "21", 0, "12"));
1373 try testing.expectEqual(1, indexOfPosLinear(u8, "212", 0, "12"));
1374 try testing.expectEqual(0, indexOfPosLinear(u8, "122", 0, "12"));
1375 try testing.expectEqual(1, indexOfPosLinear(u8, "212112", 0, "12"));
1376}
1377
13571378fn boyerMooreHorspoolPreprocessReverse(pattern: []const u8, table: *[256]usize) void {
13581379 for (table) |*c| {
13591380 c.* = pattern.len;