tree-sitter/spec/runtime/helpers/spy_reader.cc
Max Brunsfeld c576d7d4a0 In SpyReader, don't return pointers into main content string
This improves test coverage of the lexer. Before, a SpyReader's read function
would return pointers into a single string that contained the entire text. This
could have masked bugs where out-of-bounds characters were being read.
Now the chunks returned by the reader are copied into a separate buffer.
2014-09-26 16:12:52 -07:00

41 lines
1,016 B
C++

#include "runtime/helpers/spy_reader.h"
#include <algorithm>
using std::string;
static const char * spy_read(void *data, size_t *bytes_read) {
SpyReader *reader = static_cast<SpyReader *>(data);
string result = reader->content.substr(reader->position, reader->chunk_size);
reader->position += result.size();
reader->strings_read.back() += result;
*bytes_read = result.size();
memcpy(reader->buffer, result.data(), result.size());
return reader->buffer;
}
static int spy_seek(void *data, TSLength position) {
SpyReader *reader = static_cast<SpyReader *>(data);
reader->strings_read.push_back("");
reader->position = position.bytes;
return 0;
}
SpyReader::SpyReader(string content, size_t chunk_size) :
buffer(new char[chunk_size]),
content(content),
position(0),
chunk_size(chunk_size),
input({
this,
spy_read,
spy_seek,
nullptr,
}) {}
void SpyReader::clear() {
strings_read.clear();
}
SpyReader::~SpyReader() {
delete buffer;
}