parseVectorBatchText function
Parse a batch of vectors from '[[1,2,3], [4,5,6]]' — a JSON array
of arrays-of-numbers. A single-vector literal '[1,2,3]' is
accepted and wrapped in a singleton list. All inner vectors must
share the same dimension.
Implementation
List<Vector> parseVectorBatchText(String s) {
final trimmed = s.trim();
if (trimmed.isEmpty) {
throw const FormatException('empty vector batch literal');
}
final decoded = jsonDecode(trimmed);
if (decoded is! List) {
throw FormatException(
'vector batch literal must be a JSON array, got $decoded',
);
}
if (decoded.isEmpty) return const [];
// Detect single-vector shorthand: `[1, 2, 3]` -> wrap.
if (decoded.first is num) {
return [parseVectorText(trimmed)];
}
final out = <Vector>[];
int? dim;
for (var i = 0; i < decoded.length; i++) {
final row = decoded[i];
if (row is! List) {
throw FormatException(
'vector batch entry $i must be a JSON array, got $row',
);
}
final buf = Float32List(row.length);
for (var j = 0; j < row.length; j++) {
final e = row[j];
if (e is num) {
buf[j] = e.toDouble();
} else {
throw FormatException(
'vector batch [$i][$j] is not a number: $e',
);
}
}
dim ??= buf.length;
if (buf.length != dim) {
throw FormatException(
'vector batch entry $i has dim ${buf.length}, expected $dim',
);
}
out.add(Vector(buf));
}
return out;
}