Skip to content

Commit a653e89

Browse files
Update to latest zig
1 parent 1e76096 commit a653e89

4 files changed

Lines changed: 71 additions & 2 deletions

File tree

src/bitap.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ test "bitap" {
5151
inline for (&[_]comptime_int{ 31, 63, 127, 59, 67 }) |max_pattern_length| {
5252
for (test_suites) |suite| {
5353
for (suite.cases) |case| {
54-
testing.expectEqual(case.expected, bitap(
54+
try testing.expectEqual(case.expected, bitap(
5555
[]const u8,
5656
max_pattern_length,
5757
case.text,

src/boyer_moore.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ test "boyer moore" {
134134
defer sf.deinit();
135135

136136
for (suite.cases) |case| {
137-
testing.expectEqual(case.expected, sf.next(case.text));
137+
try testing.expectEqual(case.expected, sf.next(case.text));
138138
}
139139
}
140140
}

src/knuth_morris_pratt.zig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
const std = @import("std");

src/rabin_karp.zig

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
const std = @import("std");
2+
const assert = std.debug.assert;
3+
const testing = std.testing;
4+
5+
const test_suites = @import("test_cases.zig").test_suites;
6+
7+
pub fn byteRabinKarp(text: []const u8, pattern: []const u8) ?usize {
8+
const hashFn = struct {
9+
pub fn f(str: []const u8) usize {
10+
return 0;
11+
}
12+
}.f;
13+
14+
const continueHashFn = struct {
15+
pub fn f(h: usize, x: u8) usize {
16+
return 0;
17+
}
18+
}.f;
19+
20+
return rabinKarp(
21+
[]const u8,
22+
usize,
23+
hashFn,
24+
continueHashFn,
25+
text,
26+
pattern,
27+
);
28+
}
29+
30+
pub fn rabinKarp(
31+
comptime T: type,
32+
comptime H: type,
33+
comptime hashFn: fn (str: T) H,
34+
comptime continueHashFn: fn (h: H, x: std.meta.Elem(T)) H,
35+
text: T,
36+
pattern: T,
37+
) ?usize {
38+
assert(std.meta.trait.isIndexable(T));
39+
const ElemType = std.meta.Elem(T);
40+
41+
const pattern_hash = hashFn(pattern);
42+
var hash = hashFn(pattern);
43+
44+
var i: usize = 0;
45+
while (i < text.len - pattern.len) : (i += 1) {
46+
if (i > 0) {
47+
hash = continueHashFn(hash, text[i + pattern.len - 1]);
48+
}
49+
50+
if (hash == pattern_hash) {
51+
if (std.mem.eql(ElemType, pattern, text[i .. i + pattern.len])) {
52+
return i;
53+
}
54+
}
55+
}
56+
57+
return null;
58+
}
59+
60+
test "rabin karp" {
61+
const allocator = testing.allocator;
62+
63+
for (test_suites) |suite| {
64+
for (suite.cases) |case| {
65+
try testing.expectEqual(case.expected, byteRabinKarp(case.text, suite.pattern));
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)