File tree Expand file tree Collapse file tree 3 files changed +51
-0
lines changed Expand file tree Collapse file tree 3 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -1522,6 +1522,29 @@ class SOURCEMETA_CORE_JSON_EXPORT JSON {
15221522 // / ```
15231523 auto merge (const JSON::Object &other) -> void;
15241524
1525+ // / Return a trimmed version of the string. For example:
1526+ // /
1527+ // / ```cpp
1528+ // / #include <sourcemeta/core/json.h>
1529+ // / #include <cassert>
1530+ // /
1531+ // / const sourcemeta::core::JSON document{" \r\t Hello World\n\v \f"};
1532+ // / assert(document.trim() == "Hello World");
1533+ // / ```
1534+ [[nodiscard]] auto trim () const -> JSON::String;
1535+
1536+ // / Trim the string in-place. For example:
1537+ // /
1538+ // / ```cpp
1539+ // / #include <sourcemeta/core/json.h>
1540+ // / #include <cassert>
1541+ // /
1542+ // / sourcemeta::core::JSON document{" \r\t Hello World\n\v \f"};
1543+ // / document.trim();
1544+ // / assert(document.to_string() == "Hello World");
1545+ // / ```
1546+ auto trim () -> const JSON::String &;
1547+
15251548 /*
15261549 * Transform operations
15271550 */
Original file line number Diff line number Diff line change @@ -867,6 +867,21 @@ auto JSON::merge(const JSON::Object &other) -> void {
867867 }
868868}
869869
870+ [[nodiscard]] auto JSON::trim () const -> JSON::String {
871+ assert (this ->is_string ());
872+ auto copy = *this ;
873+ copy.trim ();
874+ return copy.to_string ();
875+ }
876+
877+ auto JSON::trim () -> const JSON::String & {
878+ assert (this ->is_string ());
879+ constexpr auto WHITESPACE = " \t\n\r\v\f " ;
880+ this ->data_string .erase (this ->data_string .find_last_not_of (WHITESPACE) + 1 );
881+ this ->data_string .erase (0 , this ->data_string .find_first_not_of (WHITESPACE));
882+ return this ->to_string ();
883+ }
884+
870885auto JSON::rename (const JSON::String &key, JSON::String &&to) -> void {
871886 assert (this ->is_object ());
872887 auto &object{this ->data_object };
Original file line number Diff line number Diff line change @@ -108,3 +108,16 @@ TEST(JSON_string, contains_character_false) {
108108 const sourcemeta::core::JSON document{" foo" };
109109 EXPECT_FALSE (document.contains (' b' ));
110110}
111+
112+ TEST (JSON_string, trim_const) {
113+ const sourcemeta::core::JSON document{" \r\t foo bar\n\v \f " };
114+ EXPECT_EQ (document.trim (), " foo bar" );
115+ EXPECT_EQ (document.to_string (), " \r\t foo bar\n\v \f " );
116+ }
117+
118+ TEST (JSON_string, trim_in_place) {
119+ sourcemeta::core::JSON document{" \r\t foo bar\n\v \f " };
120+ const auto &result{document.trim ()};
121+ EXPECT_EQ (result, " foo bar" );
122+ EXPECT_EQ (document.to_string (), " foo bar" );
123+ }
You can’t perform that action at this time.
0 commit comments