Add SpyReader methods for inserting/removing by char index

This commit is contained in:
Max Brunsfeld 2014-10-02 11:43:22 -07:00
parent 5f313896c3
commit 0f524121f1
3 changed files with 35 additions and 0 deletions

View file

@ -1,6 +1,7 @@
#include "runtime/helpers/spy_reader.h"
#include <string.h>
#include <algorithm>
#include "utf8proc.h"
using std::string;
@ -41,6 +42,37 @@ TSInput SpyReader::input() {
return result;
}
long position_for_char_index(string str, size_t goal_index) {
size_t index = 0, position = 0;
int32_t dest_char;
while (index < goal_index) {
if (position >= str.size())
return -1;
position += utf8proc_iterate(
(uint8_t *)(str.data() + position),
str.size() - position,
&dest_char);
index++;
}
return position;
}
bool SpyReader::insert(size_t char_index, string text) {
long pos = position_for_char_index(content, char_index);
if (pos < 0) return false;
content.insert(pos, text);
return true;
}
bool SpyReader::erase(size_t char_index, size_t len) {
long pos = position_for_char_index(content, char_index);
if (pos < 0) return false;
content.erase(pos, len);
return true;
}
SpyReader::~SpyReader() {
delete buffer;
}

View file

@ -12,6 +12,8 @@ class SpyReader {
void clear();
TSInput input();
bool insert(size_t position, std::string text);
bool erase(size_t position, size_t len);
char *buffer;
std::string content;

View file

@ -28,6 +28,7 @@
'examples',
'spec',
'externals/bandit',
'externals/utf8proc',
],
'sources': [
'<!@(find spec/runtime -name "*.cc")',