Add starts_with()/ends_with() to zeek::util namespace

This commit is contained in:
Jon Siwek 2021-02-26 14:43:55 -08:00
parent b8ec65ccf7
commit 9ced370b48
2 changed files with 32 additions and 30 deletions

View file

@ -78,36 +78,6 @@ static bool can_read(const string& path)
return access(path.c_str(), R_OK) == 0; return access(path.c_str(), R_OK) == 0;
} }
static bool starts_with(std::string_view s, std::string_view beginning)
{
if ( beginning.size() > s.size() )
return false;
return std::equal(beginning.begin(), beginning.end(), s.begin());
}
TEST_CASE("util starts_with")
{
CHECK(starts_with("abcde", "ab") == true);
CHECK(starts_with("abcde", "de") == false);
CHECK(starts_with("abcde", "abcedf") == false);
}
static bool ends_with(std::string_view s, std::string_view ending)
{
if ( ending.size() > s.size() )
return false;
return std::equal(ending.rbegin(), ending.rend(), s.rbegin());
}
TEST_CASE("util ends_with")
{
CHECK(ends_with("abcde", "de") == true);
CHECK(ends_with("abcde", "fg") == false);
CHECK(ends_with("abcde", "abcedf") == false);
}
static string zeek_path_value; static string zeek_path_value;
namespace zeek::util { namespace zeek::util {
@ -1157,6 +1127,36 @@ int streq(const char* s1, const char* s2)
return ! strcmp(s1, s2); return ! strcmp(s1, s2);
} }
bool starts_with(std::string_view s, std::string_view beginning)
{
if ( beginning.size() > s.size() )
return false;
return std::equal(beginning.begin(), beginning.end(), s.begin());
}
TEST_CASE("util starts_with")
{
CHECK(starts_with("abcde", "ab") == true);
CHECK(starts_with("abcde", "de") == false);
CHECK(starts_with("abcde", "abcedf") == false);
}
bool ends_with(std::string_view s, std::string_view ending)
{
if ( ending.size() > s.size() )
return false;
return std::equal(ending.rbegin(), ending.rend(), s.rbegin());
}
TEST_CASE("util ends_with")
{
CHECK(ends_with("abcde", "de") == true);
CHECK(ends_with("abcde", "fg") == false);
CHECK(ends_with("abcde", "abcedf") == false);
}
char* skip_whitespace(char* s) char* skip_whitespace(char* s)
{ {
while ( *s == ' ' || *s == '\t' ) while ( *s == ' ' || *s == '\t' )

View file

@ -311,6 +311,8 @@ std::vector<std::string_view> tokenize_string(std::string_view input, const char
extern char* copy_string(const char* s); extern char* copy_string(const char* s);
extern int streq(const char* s1, const char* s2); extern int streq(const char* s1, const char* s2);
extern bool starts_with(std::string_view s, std::string_view beginning);
extern bool ends_with(std::string_view s, std::string_view ending);
extern char* skip_whitespace(char* s); extern char* skip_whitespace(char* s);
extern const char* skip_whitespace(const char* s); extern const char* skip_whitespace(const char* s);