sortOrder<T> function

List<int> sortOrder<T>(
  1. List<T> rows,
  2. List<SortSpec> sorts,
  3. Map<String, GridColumn<T>> columns
)

The permutation sortRows applies: positions in rows, in sorted order.

Exposed because a caller that keeps a sorted list wants to know where each row came from - a data source maintaining an ordered result alongside the source positions it was built from, so that an edit can be patched into it instead of re-sorting everything.

Implementation

List<int> sortOrder<T>(
  List<T> rows,
  List<SortSpec> sorts,
  Map<String, GridColumn<T>> columns,
) {
  if (sorts.isEmpty || rows.length < 2) {
    return List<int>.generate(rows.length, (i) => i, growable: false);
  }

  // Read every sort key once per row rather than on every comparison. A
  // comparison sort makes O(n log n) comparisons, so calling the accessors
  // inside the comparator reads each row's value ~log n times - about 16x
  // over at 50k rows, and more when the accessor computes something.
  final levels = [
    for (final sort in sorts)
      if (columns[sort.field] != null) sort,
  ];
  if (levels.isEmpty) {
    return List<int>.generate(rows.length, (i) => i, growable: false);
  }

  final count = rows.length;
  final depth = levels.length;
  final keys = List<Object?>.filled(count * depth, null);
  for (var level = 0; level < depth; level++) {
    final read = columns[levels[level].field]!.sortValue;
    final base = level * count;
    for (var i = 0; i < count; i++) {
      keys[base + i] = read(rows[i]);
    }
  }

  final comparators = [
    for (final level in levels) columns[level.field]!.comparator,
  ];
  final ascending = [for (final level in levels) level.isAscending];
  final nullsFirst = [
    for (final level in levels) level.nulls == NullsPosition.first,
  ];

  // Two orderings cost more per comparison than they need to, and both can
  // be answered by a key computed once per row: a case- and accent-folded
  // text order, and a natural one. The raw key stays for the exact tiebreak
  // that keeps the order total.
  final folded = List<List<String>?>.filled(depth, null);
  final comparatorForLevel = List<Comparator<Object?>?>.of(comparators);
  // Levels whose key turned out to equal the value itself, so the plain
  // string comparison already gives the order the key would have.
  final plainString = List<bool>.filled(depth, false);
  for (var level = 0; level < depth; level++) {
    final column = columns[levels[level].field]!;
    final comparator = comparators[level];
    final natural = comparator == compareValuesNatural;
    if (comparator != null && !natural) continue;
    if (!natural && column.type != ColumnType.text) continue;
    final base = level * count;
    if (_keyKind(keys, base, count) != _kindString) continue;
    final keysForLevel = List<String>.filled(count, '');
    // A column that is already lower case and unaccented folds to itself, and
    // then the folded comparison is pure overhead: two string compares where
    // one would do, on a column where ties are common. Detecting that keeps
    // the folded default as cheap as the code-unit order it replaced.
    var changed = false;
    for (var i = 0; i < count; i++) {
      final value = keys[base + i];
      if (value == null) continue;
      final raw = value as String;
      final key = natural ? naturalSortKey(raw) : foldText(raw);
      keysForLevel[i] = key;
      if (!changed && key != raw) changed = true;
    }
    // The key answers what the comparator was for.
    if (natural) comparatorForLevel[level] = null;
    if (changed) {
      folded[level] = keysForLevel;
    } else {
      // Every key came back identical to its value - a column that is
      // already lower case and unaccented, or has no digits to read as
      // numbers - so comparing the values directly is the same order for a
      // fraction of the work. This is what keeps a natural sort over
      // digit-free text, and the folded default over ordinary data, as cheap
      // as the plain comparison.
      plainString[level] = true;
    }
  }

  final order = List<int>.generate(count, (i) => i, growable: false);

  // One sort column is the overwhelmingly common case - it is what a header
  // click produces - so it gets a comparison with no type tests and no
  // closure indirection in the inner loop.
  if (depth == 1 && comparatorForLevel[0] == null) {
    final ascendingOnly = ascending[0];
    final nullsFirstOnly = nullsFirst[0];
    final kind = _keyKind(keys, 0, count);

    int? nullOrder(Object? va, Object? vb) {
      if (va == null && vb == null) return 0;
      if (va == null || vb == null) {
        return (va == null) == nullsFirstOnly ? -1 : 1;
      }
      return null;
    }

    final foldedOnly = folded[0];
    if (foldedOnly != null) {
      order.sort((a, b) {
        final va = keys[a];
        final vb = keys[b];
        final nulls = nullOrder(va, vb);
        if (nulls != null) return nulls == 0 ? a.compareTo(b) : nulls;
        var cmp = foldedOnly[a].compareTo(foldedOnly[b]);
        if (cmp == 0) cmp = (va! as String).compareTo(vb! as String);
        if (cmp != 0) return ascendingOnly ? cmp : -cmp;
        return a.compareTo(b);
      });
      return order;
    }
    if (kind == _kindNum) {
      order.sort((a, b) {
        final va = keys[a];
        final vb = keys[b];
        final nulls = nullOrder(va, vb);
        if (nulls != null) return nulls == 0 ? a.compareTo(b) : nulls;
        final cmp = (va! as num).compareTo(vb! as num);
        if (cmp != 0) return ascendingOnly ? cmp : -cmp;
        return a.compareTo(b);
      });
      return order;
    }
    if (kind == _kindString) {
      order.sort((a, b) {
        final va = keys[a];
        final vb = keys[b];
        final nulls = nullOrder(va, vb);
        if (nulls != null) return nulls == 0 ? a.compareTo(b) : nulls;
        final cmp = (va! as String).compareTo(vb! as String);
        if (cmp != 0) return ascendingOnly ? cmp : -cmp;
        return a.compareTo(b);
      });
      return order;
    }
  }

  // Whether a level needs the folding comparison at comparison time, which
  // is only so when its values are text that folding changes and no key was
  // precomputed for it.
  final foldsAtCompare = [
    for (var level = 0; level < depth; level++)
      comparatorForLevel[level] == null &&
          !plainString[level] &&
          folded[level] == null &&
          columns[levels[level].field]!.type == ColumnType.text,
  ];

  order.sort((a, b) {
    for (var level = 0; level < depth; level++) {
      final base = level * count;
      final va = keys[base + a];
      final vb = keys[base + b];
      if (va == null || vb == null) {
        if (va == null && vb == null) continue;
        // Null placement is absolute: it does not flip with the direction.
        return (va == null) == nullsFirst[level] ? -1 : 1;
      }
      final foldedLevel = folded[level];
      var cmp = 0;
      // Explicit branches rather than a comparator read out of a list: a
      // tear-off called per comparison per level cost half as much again as
      // the direct call over 50k rows and three levels.
      if (foldedLevel != null) {
        cmp = foldedLevel[a].compareTo(foldedLevel[b]);
        if (cmp == 0) cmp = (va as String).compareTo(vb as String);
      } else {
        final comparator = comparatorForLevel[level];
        if (comparator != null) {
          cmp = comparator(va, vb);
        } else if (foldsAtCompare[level]) {
          cmp = compareValuesCaseInsensitive(va, vb);
        } else {
          cmp = compareValues(va, vb);
        }
      }
      if (cmp != 0) return ascending[level] ? cmp : -cmp;
    }
    // Fall back to the input position, which keeps the sort stable.
    return a.compareTo(b);
  });

  return order;
}