Skip to content

Commit

Permalink
libsupport: URI prefix checking
Browse files Browse the repository at this point in the history
Add methods to URI to check if one URI is a prefix of another.
  • Loading branch information
simon committed Mar 11, 2022
1 parent 1cd6985 commit 056f20d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
10 changes: 10 additions & 0 deletions libsupport/include/katana/URI.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class KATANA_EXPORT URI {
/// 3. KATANA_TMPDIR
/// The contents of the "most senior" set variable from this list will be used
/// if any are set.
// TODO (scober): Add a signal handler to clear this directory
static Result<URI> MakeTempDir();

static std::string JoinPath(const std::string& dir, const std::string& file);
Expand Down Expand Up @@ -72,6 +73,15 @@ class KATANA_EXPORT URI {
/// An overload of RandFile provided for clarity at call sites
URI RandSubdir(std::string_view prefix) const { return RandFile(prefix); }

bool IsPrefixOf(const URI& other) const {
return scheme_ == other.scheme_ &&
other.path_.compare(0, path_.size(), path_) == 0;
}
bool HasAsPrefix(const URI& other) const {
return scheme_ == other.scheme_ &&
path_.compare(0, other.path_.size(), other.path_) == 0;
}

URI operator+(char rhs) const;
URI operator+(const std::string& rhs) const;

Expand Down
4 changes: 3 additions & 1 deletion libsupport/src/URI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,9 @@ katana::URI::MakeTempDir() {
GetEnv("TMPDIR", &tmp_dir);
GetEnv("KATANA_TMPDIR", &tmp_dir);

return KATANA_CHECKED(Make(tmp_dir));
auto tmp_uri = KATANA_CHECKED(Make(tmp_dir));

return tmp_uri.Join("katana-tmp");
}

std::string
Expand Down
18 changes: 18 additions & 0 deletions libsupport/test/uri.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@ TestDecode() {
katana::URI::Decode("host%3A8020/path") == "host:8020/path");
}

void
TestPrefix() {
katana::URI full = Str2Uri("abc/def/ghi");
katana::URI prefix = Str2Uri("abc/d");
katana::URI not_prefix = Str2Uri("jkl/mn");
katana::URI other_not_prefix = Str2Uri("s3://abc/def");

KATANA_LOG_ASSERT(prefix.IsPrefixOf(full));
KATANA_LOG_ASSERT(full.HasAsPrefix(prefix));

KATANA_LOG_ASSERT(!not_prefix.IsPrefixOf(full));
KATANA_LOG_ASSERT(!full.HasAsPrefix(not_prefix));
KATANA_LOG_ASSERT(!other_not_prefix.IsPrefixOf(full));
KATANA_LOG_ASSERT(!full.HasAsPrefix(other_not_prefix));
}

} // namespace

int
Expand All @@ -87,5 +103,7 @@ main() {

TestDecode();

TestPrefix();

return 0;
}

0 comments on commit 056f20d

Please sign in to comment.