flutterdartstringbuffer

Stringbuffer access by index or range


TLDR: I am looking for a datastructure with the properties of a string buffer that I can access by index in dart.

Long version: I need the properties of Stringbuffer (very efficient at adding characters/bytes) but with the added capability of accessing characters/bytes at specific indices or ranges. I am very surprised that something as simple as that does not seem to exist, neither in the dart core nor in custom libraries.

Fyi I am trying to build a piece table in dart. I do not think that simply calling stringbuffer.toString().substring(start, end) is an option, as this probably copies the whole string, which is the opposite of the efficiency I want.


Solution

  • To answer my own question: After playing around with the typed library and some custom data structures for a bit, it seems that a simple list of Strings is actually the fastest, assuming that I need half as many insertions as I need random read access.

    Of course still open to any suggestions from anyone who knows more about dart, microbenchmarking, etc.

    class IndexableStringBuffer {
      final List<String> _characters = List.empty(growable: true);
    
      int get length => _characters.length;
    
      void writeAll(String string) {
        _characters.addAll(string.characters);
      }
    
      String getRange(int start, int? end) {
        return _characters.sublist(start, end).join();
      }
    }