Squeeze a bit more performance out of the ends_with bif

This commit is contained in:
Tim Wojtulewicz 2024-01-12 16:07:27 -07:00 committed by Tim Wojtulewicz
parent 378f380b71
commit b962bd30ce
3 changed files with 12 additions and 4 deletions

View file

@ -1366,9 +1366,15 @@ function ends_with%(str: string, sub: string%) : bool
if ( sub->Len() > str->Len() )
return zeek::val_mgr->Bool(false);
string s = str->ToStdString();
string sub_s = sub->ToStdString();
return zeek::val_mgr->Bool(s.rfind(sub_s) == (s.size() - sub_s.size()));
auto sub_s = sub->ToStdStringView();
auto s = str->ToStdStringView();
// Create a string_view that only looks at the end of the string being searched
// with the same number of characters as the search string. This avoids possible
// pathological searches of big strings if the search string doesn't exist.
auto end_s = std::string_view{s.data() + s.size() - sub_s.size(), sub_s.size()};
return zeek::val_mgr->Bool(end_s == sub_s);
%}
## Returns whether a string consists entirely of digits.

View file

@ -41,6 +41,7 @@ starts_with bro: 1
starts_with ids: 0
ends_with ids: 1
ends_with bro: 0
ends_with containing null: 1
Transformations
---------------

View file

@ -1,4 +1,4 @@
# @TEST-EXEC: zeek -b %INPUT >out
# @TEST-EXEC: zeek -b %INPUT >out 2>&1
# @TEST-EXEC: btest-diff out
event zeek_init()
@ -51,6 +51,7 @@ event zeek_init()
print fmt("starts_with ids: %d", starts_with(s3, "ghi"));
print fmt("ends_with ids: %d", ends_with(s3, "ghi"));
print fmt("ends_with bro: %d", ends_with(s3, "abc"));
print fmt("ends_with containing null: %d", ends_with("a\x00\x00b", "\x00b"));
print "";
print "Transformations";