Skip to content

Commit

Permalink
Add last() and undo to StrBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
tgtakaoka committed Sep 3, 2024
1 parent e2d292f commit ad50584
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/str_buffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ StrBuffer::StrBuffer(const StrBuffer &o)
setError(o.getError());
}

char StrBuffer::last() const {
return _str < _out ? *(_out - 1) : 0;
}

char StrBuffer::undo() {
if (_str < _out) {
const auto c = *--_out;
*_out = 0;
return c;
}
return 0;
}

StrBuffer &StrBuffer::reset() {
*(_out = _str) = 0;
resetError();
Expand Down
6 changes: 6 additions & 0 deletions src/str_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ struct StrBuffer : ErrorReporter {
/** Return the current output position */
char *mark() const { return _out; }

/** Peek last letter. */
char last() const;

/** Undo last letter. */
char undo();

/** Reset buffer to . */
StrBuffer &reset();

Expand Down
24 changes: 24 additions & 0 deletions test/unit/test_str_buffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,29 @@ void test_reset() {
EQ("reset", "", out.str());
}

void test_undo() {
char buffer[8];
StrBuffer out(buffer, sizeof(buffer));

out.text("ABCDEFx");
EQ("undo", 7, out.len());
EQ("undo", "ABCDEFx", out.str());
EQ("undo", 'x', out.last());
EQ("undo", 'x', out.undo());
EQ("undo", 6, out.len());
EQ("undo", "ABCDEF", out.str());

out.reset();
out.letter('A');
EQ("undo", "A", out.str());
EQ("undo", 'A', out.last());
EQ("undo", 'A', out.undo());
EQ("undo", "", out.str());
EQ("undo", 0, out.last());
EQ("undo", 0, out.undo());
EQ("undo", "", out.str());
}

void run_tests() {
RUN_TEST(test_letter);
RUN_TEST(test_text);
Expand All @@ -412,6 +435,7 @@ void run_tests() {
RUN_TEST(test_comma);
RUN_TEST(test_reverse);
RUN_TEST(test_reset);
RUN_TEST(test_undo);
}

} // namespace test
Expand Down

0 comments on commit ad50584

Please sign in to comment.