diff --git a/src/json/include/sourcemeta/jsontoolkit/json_value.h b/src/json/include/sourcemeta/jsontoolkit/json_value.h index fc5365b7f..b883f7b1c 100644 --- a/src/json/include/sourcemeta/jsontoolkit/json_value.h +++ b/src/json/include/sourcemeta/jsontoolkit/json_value.h @@ -1099,6 +1099,32 @@ class SOURCEMETA_JSONTOOLKIT_JSON_EXPORT JSON { /// ``` [[nodiscard]] auto contains(const JSON &element) const -> bool; + /// This method checks if an JSON string contains a given string. For + /// example: + /// + /// ```cpp + /// #include + /// #include + /// + /// const sourcemeta::jsontoolkit::JSON document{"foo bar baz"}; + /// assert(document.contains("bar")); + /// assert(!document.contains("baz")); + /// ``` + [[nodiscard]] auto contains(const String &input) const -> bool; + + /// This method checks if an JSON string contains a given character. For + /// example: + /// + /// ```cpp + /// #include + /// #include + /// + /// const sourcemeta::jsontoolkit::JSON document{"foo"}; + /// assert(document.contains('f')); + /// assert(!document.contains('b')); + /// ``` + [[nodiscard]] auto contains(const String::value_type input) const -> bool; + /// This method checks if an JSON array does not contain duplicated items. For /// example: /// diff --git a/src/json/json_value.cc b/src/json/json_value.cc index 68bee18ab..dbe3fa206 100644 --- a/src/json/json_value.cc +++ b/src/json/json_value.cc @@ -712,6 +712,17 @@ JSON::defines_any(std::initializer_list keys) const -> bool { element) != this->as_array().cend(); } +[[nodiscard]] auto JSON::contains(const JSON::String &input) const -> bool { + assert(this->is_string()); + return this->to_string().find(input) != JSON::String::npos; +} + +[[nodiscard]] auto JSON::contains(const JSON::String::value_type input) const + -> bool { + assert(this->is_string()); + return this->to_string().find(input) != JSON::String::npos; +} + [[nodiscard]] auto JSON::unique() const -> bool { assert(this->is_array()); const auto &items{this->data_array.data}; diff --git a/test/json/json_string_test.cc b/test/json/json_string_test.cc index 183a15055..2e61db7e2 100644 --- a/test/json/json_string_test.cc +++ b/test/json/json_string_test.cc @@ -87,3 +87,23 @@ TEST(JSON_string, unicode_length_1) { // https://unicodeplus.com/U+7EAF (UTF-8: 0xE7 0xBA 0xAF) EXPECT_EQ(document.at("name").byte_size(), 9); } + +TEST(JSON_string, contains_true) { + const sourcemeta::jsontoolkit::JSON document{"foo bar baz"}; + EXPECT_TRUE(document.contains("foo")); +} + +TEST(JSON_string, contains_false) { + const sourcemeta::jsontoolkit::JSON document{"foo bar baz"}; + EXPECT_FALSE(document.contains("fooo")); +} + +TEST(JSON_string, contains_character_true) { + const sourcemeta::jsontoolkit::JSON document{"foo"}; + EXPECT_TRUE(document.contains('f')); +} + +TEST(JSON_string, contains_character_false) { + const sourcemeta::jsontoolkit::JSON document{"foo"}; + EXPECT_FALSE(document.contains('b')); +}