encode method

BitArray encode()

@return text represented by this encoder encoded as a BitArray

Implementation

BitArray encode() {
  State initialState = State.initialState;
  if (_charset != null) {
    final CharacterSetECI? eci =
        CharacterSetECI.getCharacterSetECI(_charset!);
    if (null == eci) {
      throw ArgumentError('No ECI code for character set ${_charset!.name}');
    }
    initialState = initialState.appendFLGn(eci.value);
  }
  List<State> states = [initialState];
  for (int index = 0; index < _text.length; index++) {
    int pairCode;
    final int nextChar = index + 1 < _text.length ? _text[index + 1] : 0;
    switch (_text[index]) {
      case 13: //'\r':
        pairCode = nextChar == 10 /*'\n'*/ ? 2 : 0;
        break;
      case 46: //'.':
        pairCode = nextChar == 32 /*' '*/ ? 3 : 0;
        break;
      case 44: //',':
        pairCode = nextChar == 32 ? 4 : 0;
        break;
      case 58: //':':
        pairCode = nextChar == 32 ? 5 : 0;
        break;
      default:
        pairCode = 0;
    }
    if (pairCode > 0) {
      // We have one of the four special PUNCT pairs.  Treat them specially.
      // Get a new set of states for the two new characters.
      states = _updateStateListForPair(states, index, pairCode);
      index++;
    } else {
      // Get a new set of states for the new character.
      states = _updateStateListForChar(states, index);
    }
  }
  final State minState = states.singleWhere((element) {
    return states.every((ele) => element.bitCount <= ele.bitCount);
  });
  // We are left with a set of states.  Find the shortest one.
  //State minState = Collections.min(states, Comparator<State>() {
  //  @override
  //  int compare(State a, State b) {
  //    return a.getBitCount() - b.getBitCount();
  //  }
  //});
  // Convert it to a bit array, and return.
  return minState.toBitArray(_text);
}