Skip to content

Commit

Permalink
A small optimization of COOKED_READ_DATA::_erase (#15879)
Browse files Browse the repository at this point in the history
This is a small optimization that makes COOKED_READ_DATA erase short
runs of text more quickly. It's not really necessary to do this as
this code is not a hotpath, but I felt like it's neater this way.
It requires no heap allocations even for long runs of text.

## Validation Steps Performed
* Deleting text anywhere in a prompt erases it ✅
  • Loading branch information
lhecker committed Aug 28, 2023
1 parent 821ae3a commit c443615
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
24 changes: 19 additions & 5 deletions src/host/readDataCooked.cpp
Expand Up @@ -766,14 +766,28 @@ void COOKED_READ_DATA::_flushBuffer()
}

// This is just a small helper to fill the next N cells starting at the current cursor position with whitespace.
// The implementation is inefficient for `count`s larger than 7, but such calls are uncommon to happen (namely only when resizing the window).
void COOKED_READ_DATA::_erase(const til::CoordType distance)
void COOKED_READ_DATA::_erase(const til::CoordType distance) const
{
if (distance > 0)
if (distance <= 0)
{
const std::wstring str(gsl::narrow_cast<size_t>(distance), L' ');
std::ignore = _writeChars(str);
return;
}

std::array<wchar_t, 128> whitespace;
auto remaining = gsl::narrow_cast<size_t>(distance);
auto nextWriteSize = std::min(remaining, whitespace.size());

// If we only need to erase 1 character worth of whitespace,
// we don't need to initialize 256 bytes worth of a whitespace array.
// nextWriteSize can only ever shrink past this point if anything.
std::fill_n(whitespace.begin(), nextWriteSize, L' ');

do
{
std::ignore = _writeChars({ whitespace.data(), nextWriteSize });
remaining -= nextWriteSize;
nextWriteSize = std::min(remaining, whitespace.size());
} while (remaining != 0);
}

// A helper to write text and calculate the number of cells we've written.
Expand Down
2 changes: 1 addition & 1 deletion src/host/readDataCooked.hpp
Expand Up @@ -113,7 +113,7 @@ class COOKED_READ_DATA final : public ReadData
void _handlePostCharInputLoop(bool isUnicode, size_t& numBytes, ULONG& controlKeyState);
void _markAsDirty();
void _flushBuffer();
void _erase(til::CoordType distance);
void _erase(til::CoordType distance) const;
til::CoordType _writeChars(const std::wstring_view& text) const;
til::point _offsetPosition(til::point pos, til::CoordType distance) const;
void _unwindCursorPosition(til::CoordType distance) const;
Expand Down

0 comments on commit c443615

Please sign in to comment.