@@ -48,14 +48,17 @@ class generic_iobuf_writer
4848
4949private:
5050 bool write_chunked_string (const iobuf& buf) {
51- const auto last_frag = [this ]() {
52- return std::prev (this ->os_ ->_impl .end ());
53- };
51+ const auto last_frag = [this ]() { return this ->os_ ->_impl .rbegin (); };
5452 using Ch = Base::Ch;
5553 this ->Prefix (rapidjson::kStringType );
5654 const auto beg = buf.begin ();
5755 const auto end = buf.end ();
58- const auto last = std::prev (end);
56+ if (beg == end) {
57+ if (!Base::WriteString (" " , 0 )) {
58+ return false ;
59+ }
60+ return this ->EndValue (true );
61+ }
5962 Ch stashed{};
6063 Ch* stash_pos{};
6164 // Base::WriteString is used to JSON encode the string, and requires a
@@ -73,31 +76,33 @@ class generic_iobuf_writer
7376 // 3. Drop the final character
7477 // For each encoded fragment that is written (except the first one):
7578 // 4. Restore the stashed character over the prefix-quote
76- for (auto i = beg; i != end; ++i ) {
79+ for (auto i = beg;; ) {
7780 if (!Base::WriteString (i->get (), i->size ())) {
7881 return false ;
7982 }
8083 if (i != beg) {
8184 // 4. Restore the stashed character over the prefix-quote
8285 *stash_pos = stashed;
8386 }
84- if (i != last) {
85- // 1. Trim the suffix quote
86- this ->os_ ->_impl .trim_back (1 );
87+ ++i;
88+ if (i == end) {
89+ break ;
90+ }
91+ // 1. Trim the suffix quote
92+ this ->os_ ->_impl .trim_back (1 );
8793
88- // 2. Stash the final character, ...
89- auto last = last_frag ();
90- stashed = *std::prev (last->get_current ());
91- // 3. Drop the final character
92- this ->os_ ->_impl .trim_back (1 );
94+ // 2. Stash the final character, ...
95+ auto last = last_frag ();
96+ stashed = *std::prev (last->get_current ());
97+ // 3. Drop the final character
98+ this ->os_ ->_impl .trim_back (1 );
9399
94- // Ensure a stable address to restore the stashed character
95- if (last != last_frag ()) {
96- this ->os_ ->_impl .reserve_memory (1 );
97- }
98- // 2. ...and where it is to be written.
99- stash_pos = last_frag ()->get_current ();
100+ // Ensure a stable address to restore the stashed character
101+ if (last != last_frag ()) {
102+ this ->os_ ->_impl .reserve_memory (1 );
100103 }
104+ // 2. ...and where it is to be written.
105+ stash_pos = last_frag ()->get_current ();
101106 }
102107 return this ->EndValue (true );
103108 }
0 commit comments