File tree 3 files changed +51
-0
lines changed 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 {
1522
1522
// / ```
1523
1523
auto merge (const JSON::Object &other) -> void;
1524
1524
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
+
1525
1548
/*
1526
1549
* Transform operations
1527
1550
*/
Original file line number Diff line number Diff line change @@ -867,6 +867,21 @@ auto JSON::merge(const JSON::Object &other) -> void {
867
867
}
868
868
}
869
869
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
+
870
885
auto JSON::rename (const JSON::String &key, JSON::String &&to) -> void {
871
886
assert (this ->is_object ());
872
887
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) {
108
108
const sourcemeta::core::JSON document{" foo" };
109
109
EXPECT_FALSE (document.contains (' b' ));
110
110
}
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