From b647b48bf4d980e26b4626e94f1207ad66fc324e Mon Sep 17 00:00:00 2001 From: Steve Reinhardt Date: Mon, 6 Aug 2012 16:52:49 -0700 Subject: str: add an overloaded startswith() utility method for various string types and use it in a few places. --- src/base/hostinfo.cc | 3 ++- src/base/str.hh | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) (limited to 'src/base') diff --git a/src/base/hostinfo.cc b/src/base/hostinfo.cc index 857ccfa7f..15413de2a 100644 --- a/src/base/hostinfo.cc +++ b/src/base/hostinfo.cc @@ -45,6 +45,7 @@ #include #include "base/misc.hh" +#include "base/str.hh" #include "base/types.hh" using namespace std; @@ -77,7 +78,7 @@ procInfo(const char *filename, const char *target) while (fp && !feof(fp) && !done) { if (fgets(line, 80, fp)) { - if (strncmp(line, target, strlen(target)) == 0) { + if (startswith(line, target)) { snprintf(format, sizeof(format), "%s %%ld", target); sscanf(line, format, &usage); diff --git a/src/base/str.hh b/src/base/str.hh index 6d617df72..b3f3153ec 100644 --- a/src/base/str.hh +++ b/src/base/str.hh @@ -33,6 +33,7 @@ #define __STR_HH__ #include +#include #include #include #include @@ -140,4 +141,35 @@ quote(const std::string &s) return ret; } + +/** + * Return true if 's' starts with the prefix string 'prefix'. + */ +inline bool +startswith(const char *s, const char *prefix) +{ + return (strncmp(s, prefix, strlen(prefix)) == 0); +} + + +/** + * Return true if 's' starts with the prefix string 'prefix'. + */ +inline bool +startswith(const std::string &s, const char *prefix) +{ + return (s.compare(0, strlen(prefix), prefix) == 0); +} + + +/** + * Return true if 's' starts with the prefix string 'prefix'. + */ +inline bool +startswith(const std::string &s, const std::string &prefix) +{ + return (s.compare(0, prefix.size(), prefix) == 0); +} + + #endif //__STR_HH__ -- cgit v1.2.3