addInput method

LZW addInput (
  1. String input
)

feeds a String into the encoder. This can be done as many times as needed. To finalize, the method finalizeEncoding() has to be called.

Implementation

LZW addInput(String input) {
  if (_isDecoding) {
    throw new IllegalStateException(
        "cannot start encoding while decoding is done");
  }
  _isEncoding = true;

  for (int i = 0; i < input.length; i++) {
    if (debugEncoding) print("");

    if (!alphabet.contains(input[i])) {
      throw new FormatException(
          "character '${input[i]}' not contained in defined alphabet!");
    }

    _symbol = input[i];

    if (_isPatternContainedInCodebook(_praefix + _symbol)) {
      if (debugEncoding) {
        print("$i: '${_praefix + _symbol}' in codebook");
      }
      _praefix += _symbol;
      continue;
    } else {
      if (debugEncoding) print("$i: '${_praefix + _symbol}' not in codebook");

      int code = getCodeWord(_praefix);
      _result.add(code);
      if (debugEncoding) print("$i: out <- $code");

      _addCodeWord(_praefix + _symbol, _nextCodeWord++);
      _praefix = _symbol;

      if (_isCodebookFull()) {
        if (debugEncoding) print("$i: book is full: $_praefix + $_symbol");
        _result.add(blank);
        _reset();
      }

      if (debugEncoding) print(_codebook);
    }
  }

  return this;
}