encodeMinimally static method

List<int> encodeMinimally(
  1. String stringToEncode,
  2. ECIEncoderSet encoderSet,
  3. int fnc1
)

Implementation

static List<int> encodeMinimally(
  String stringToEncode,
  ECIEncoderSet encoderSet,
  int fnc1,
) {
  final inputLength = stringToEncode.length;

  // Array that represents vertices. There is a vertex for every character and encoding.
  final List<List<InputEdge?>> edges = List.generate(
    inputLength + 1,
    (index) => List.filled(encoderSet.length, null),
  );
  addEdges(stringToEncode, encoderSet, edges, 0, null, fnc1);

  for (int i = 1; i <= inputLength; i++) {
    for (int j = 0; j < encoderSet.length; j++) {
      if (edges[i][j] != null && i < inputLength) {
        addEdges(stringToEncode, encoderSet, edges, i, edges[i][j], fnc1);
      }
    }
    //optimize memory by removing edges that have been passed.
    for (int j = 0; j < encoderSet.length; j++) {
      edges[i - 1][j] = null;
    }
  }
  int minimalJ = -1;
  int minimalSize = MathUtils.maxValue;
  for (int j = 0; j < encoderSet.length; j++) {
    if (edges[inputLength][j] != null) {
      final edge = edges[inputLength][j]!;
      if (edge.cachedTotalSize < minimalSize) {
        minimalSize = edge.cachedTotalSize;
        minimalJ = j;
      }
    }
  }
  if (minimalJ < 0) {
    // IllegalStateException
    throw StateError(
      'Failed to encode "$stringToEncode"',
    );
  }
  final intsAL = <int>[];
  InputEdge? current = edges[inputLength][minimalJ];
  while (current != null) {
    if (current.isFNC1) {
      intsAL.insert(0, 1000);
    } else {
      final bytes = encoderSet.encode(current.c, current.encoderIndex);
      for (int i = bytes.length - 1; i >= 0; i--) {
        intsAL.insert(0, bytes[i]);
      }
    }
    final previousEncoderIndex = current.previous?.encoderIndex ?? 0;
    if (previousEncoderIndex != current.encoderIndex) {
      intsAL.insert(0, 256 + encoderSet.getECIValue(current.encoderIndex));
    }
    current = current.previous;
  }

  return intsAL;
}