From 8e9f827117ab1418578b692a2325754cc3ee692d Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Tue, 27 Jul 2021 23:48:27 -0700 Subject: [PATCH] add optional max parameter to short circuit long string detection --- README.md | 2 +- src/lib.zig | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e8c53d2e9209c7d4118366258d444e120d21b209..f0e134bbf67b1c49d978cc4f053444fe8311cd7b 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ zigmod aq add 1/nektro/leven ``` ## Usage -`pub fn leven(comptime T: type, alloc: *std.mem.Allocator, a: []const T, b: []const T) !usize` +`pub fn leven(comptime T: type, alloc: *std.mem.Allocator, a: []const T, b: []const T, max: ?usize) !usize` ## Future TODO Unicode support for strings diff --git a/src/lib.zig b/src/lib.zig index e45925436de7d27dfa14f0c65c8b19f1c9b6d3fa..c8fbb3196563e17ad8b7b11e27397db9a93b2dbf 100644 --- a/src/lib.zig +++ b/src/lib.zig @@ -15,7 +15,7 @@ const range = @import("range").range; // ); // } -pub fn leven(comptime T: type, alloc: *std.mem.Allocator, a: []const T, b: []const T) !usize { +pub fn leven(comptime T: type, alloc: *std.mem.Allocator, a: []const T, b: []const T, max: ?usize) !usize { if (std.mem.eql(T, a, b)) return 0; var left = a; @@ -29,6 +29,10 @@ pub fn leven(comptime T: type, alloc: *std.mem.Allocator, a: []const T, b: []con var ll = left.len; var rl = right.len; + if (max != null and rl - ll >= max.?) { + return max.?; + } + { const sl = suffixLen(T, a, b); ll -= sl; @@ -67,6 +71,7 @@ pub fn leven(comptime T: type, alloc: *std.mem.Allocator, a: []const T, b: []con } } + if (max != null and result >= max.?) return max.?; return result; } -- 2.54.0