Remove the suboptimal .canPeek() and .peek() methods

This commit is contained in:
Rangi42
2024-03-28 14:49:36 -04:00
parent 83c0634f15
commit 6f74e4fb9c
2 changed files with 8 additions and 15 deletions

View File

@@ -34,8 +34,6 @@ struct Expansion {
size_t offset; // Cursor into `contents`
size_t size() const { return contents->size(); }
bool canPeek(uint8_t distance) const { return offset + distance < contents->size(); }
uint8_t peek(uint8_t distance) const { return (*contents)[offset + distance]; }
bool advance(); // Increment `offset`; return whether it then exceeds `contents`
};
@@ -51,9 +49,6 @@ struct ViewedContent {
ViewedContent(ContentSpan const &span_) : span(span_) {}
ViewedContent(std::shared_ptr<char[]> ptr, size_t size) : span({.ptr = ptr, .size = size}) {}
bool canPeek(uint8_t distance) const { return offset + distance < span.size; }
uint8_t peek(uint8_t distance) const { return span.ptr[offset + distance]; }
std::shared_ptr<char[]> makeSharedContentPtr() const {
return std::shared_ptr<char[]>(span.ptr, &span.ptr[offset]);
}
@@ -68,8 +63,6 @@ struct BufferedContent {
BufferedContent(int fd_) : fd(fd_) {}
~BufferedContent();
bool canPeek(uint8_t distance) const { return size > distance; }
uint8_t peek(uint8_t distance) const { return buf[(offset + distance) % LEXER_BUF_SIZE]; }
void advance(); // Increment `offset` circularly, decrement `size`
void refill(); // Read from `fd` to fill `buf`

View File

@@ -692,25 +692,25 @@ int LexerState::peek(uint8_t distance) {
assert(distance == 0 || distance == 1);
for (Expansion &exp : expansions) {
// An expansion that has reached its end will have `exp->offset` == `exp->size()`,
// An expansion that has reached its end will have `exp.offset` == `exp.size()`,
// and `.peek()` will continue with its parent
assert(exp.offset <= exp.size());
if (exp.canPeek(distance))
return exp.peek(distance);
if (exp.offset + distance < exp.size())
return (uint8_t)(*exp.contents)[exp.offset + distance];
distance -= exp.size() - exp.offset;
}
if (auto *view = std::get_if<ViewedContent>(&content); view) {
if (view->canPeek(distance))
return view->peek(distance);
if (view->offset + distance < view->span.size)
return (uint8_t)view->span.ptr[view->offset + distance];
} else {
assert(std::holds_alternative<BufferedContent>(content));
auto &cbuf = std::get<BufferedContent>(content);
assert(distance < LEXER_BUF_SIZE);
if (!cbuf.canPeek(distance))
if (cbuf.size <= distance)
cbuf.refill(); // Buffer isn't full enough, read some chars in
if (cbuf.canPeek(distance))
return cbuf.peek(distance);
if (cbuf.size > distance)
return (uint8_t)cbuf.buf[(cbuf.offset + distance) % LEXER_BUF_SIZE];
}
// If there aren't enough chars, give up
return EOF;