Skip to content

Commit

Permalink
Implement MISC::ends_with(haystack, needle) (#1244)
Browse files Browse the repository at this point in the history
haystackの末尾がneedleと一致するかチェックする文字列の操作を
実装します。合わせてテストケースを追加し動作を確認します。

新しい規格のC++20には同等の操作を行うメンバー関数
`std::string::ends_with()`や`std::string_view::ends_with()`が
ありますがJDimが利用する規格はC++17であるため自前で実装します。
  • Loading branch information
ma8ma committed Sep 9, 2023
1 parent 31fca3d commit d86261e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/jdlib/miscutil.h
Expand Up @@ -273,6 +273,19 @@ namespace MISC
// Unicode正規化は行わなずバイト列として比較する
bool starts_with( const char* self, const char* starts );

/** @brief haystackの末尾がneedleと一致するか
*
* @param[in] haystack 末尾をチェックする
* @param[in] needle haystackの末尾と一致するか
* @retval true 末尾が一致した、またはneedleが空文字列の場合
* @retval false 末尾が不一致、またはhaystackがneedleより短い場合
*/
constexpr bool ends_with( std::string_view haystack, std::string_view needle )
{
return haystack.size() >= needle.size()
&& haystack.compare( haystack.size() - needle.size(), needle.size(), needle ) == 0;
}

// HTMLからform要素を解析してinput,textarea要素の名前と値を返す
std::vector<FormDatum> parse_html_form_data( const std::string& html );

Expand Down
33 changes: 33 additions & 0 deletions test/gtest_jdlib_miscutil.cpp
Expand Up @@ -1404,6 +1404,39 @@ TEST_F(MISC_StartsWith, null_terminated_string)
}


class MISC_EndsWith : public ::testing::Test {};

TEST_F(MISC_EndsWith, empty_haystack_and_needle)
{
EXPECT_TRUE( MISC::ends_with( "", "" ) );
}

TEST_F(MISC_EndsWith, empty_haystack)
{
EXPECT_FALSE( MISC::ends_with( "", "needle" ) );
}

TEST_F(MISC_EndsWith, empty_needle)
{
EXPECT_TRUE( MISC::ends_with( "haystack", "" ) );
}

TEST_F(MISC_EndsWith, hello_world)
{
EXPECT_TRUE( MISC::ends_with( "Hello World", "World" ) );
}

TEST_F(MISC_EndsWith, too_long_needle)
{
EXPECT_FALSE( MISC::ends_with( "World", "Hello World" ) );
}

TEST_F(MISC_EndsWith, not_match)
{
EXPECT_FALSE( MISC::ends_with( "quick brown fox", "dogs" ) );
}


class MISC_ParseHtmlFormData : public ::testing::Test {};

TEST_F(MISC_ParseHtmlFormData, empty_html)
Expand Down

0 comments on commit d86261e

Please sign in to comment.