From 0f524121f19b62fe52e50ea562d32eeec33c2e85 Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Thu, 2 Oct 2014 11:43:22 -0700 Subject: [PATCH] Add SpyReader methods for inserting/removing by char index --- spec/runtime/helpers/spy_reader.cc | 32 ++++++++++++++++++++++++++++++ spec/runtime/helpers/spy_reader.h | 2 ++ tests.gyp | 1 + 3 files changed, 35 insertions(+) diff --git a/spec/runtime/helpers/spy_reader.cc b/spec/runtime/helpers/spy_reader.cc index d9b14fdf..e56133cc 100644 --- a/spec/runtime/helpers/spy_reader.cc +++ b/spec/runtime/helpers/spy_reader.cc @@ -1,6 +1,7 @@ #include "runtime/helpers/spy_reader.h" #include #include +#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; } diff --git a/spec/runtime/helpers/spy_reader.h b/spec/runtime/helpers/spy_reader.h index b583ab56..f8a8fd29 100644 --- a/spec/runtime/helpers/spy_reader.h +++ b/spec/runtime/helpers/spy_reader.h @@ -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; diff --git a/tests.gyp b/tests.gyp index dad8dec6..00915d1f 100644 --- a/tests.gyp +++ b/tests.gyp @@ -28,6 +28,7 @@ 'examples', 'spec', 'externals/bandit', + 'externals/utf8proc', ], 'sources': [ '