fs/Path: add GetSuffix()

This commit is contained in:
Max Kellermann 2022-07-14 17:36:21 +02:00
parent f44bc19ce1
commit 458084d79b
4 changed files with 46 additions and 6 deletions

View File

@ -295,6 +295,15 @@ public:
return Traits::Relative(c_str(), other_fs.c_str());
}
/**
* Returns the filename suffix (including the dot) or nullptr
* if the path does not have one.
*/
[[gnu::pure]]
const_pointer GetSuffix() const noexcept {
return Path{*this}.GetSuffix();
}
/**
* Returns the filename extension (excluding the dot) or
* nullptr if the path does not have one.

View File

@ -37,7 +37,7 @@ Path::ToUTF8Throw() const
}
Path::const_pointer
Path::GetExtension() const noexcept
Path::GetSuffix() const noexcept
{
const auto *base = GetBase().c_str();
@ -46,9 +46,16 @@ Path::GetExtension() const noexcept
while (*base == '.')
++base;
const auto *dot = StringFindLast(base, '.');
if (dot == nullptr)
return nullptr;
return dot + 1;
return StringFindLast(base, '.');
}
Path::const_pointer
Path::GetExtension() const noexcept
{
const auto *result = GetSuffix();
if (result != nullptr)
/* skip the dot */
++result;
return result;
}

View File

@ -166,6 +166,13 @@ public:
return Traits::IsAbsolute(c_str());
}
/**
* Returns the filename suffix (including the dot) or nullptr
* if the path does not have one.
*/
[[gnu::pure]]
const_pointer GetSuffix() const noexcept;
/**
* Returns the filename extension (excluding the dot) or
* nullptr if the path does not have one.

View File

@ -79,3 +79,20 @@ TEST(Path, Extension)
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc")).GetExtension(), "abc");
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc.def")).GetExtension(), "def");
}
TEST(Path, Suffix)
{
EXPECT_EQ(Path::FromFS(PATH_LITERAL("foo")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/bar")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/./bar")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/.bar")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/.")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/..")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar")).GetSuffix(), nullptr);
EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo.abc/")).GetSuffix(), nullptr);
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def")).GetSuffix(), ".def");
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.")).GetSuffix(), ".");
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def.ghi")).GetSuffix(), ".ghi");
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc")).GetSuffix(), ".abc");
EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc.def")).GetSuffix(), ".def");
}