encodeBytes<T> static method

List<int> encodeBytes<T>(
  1. T value, {
  2. Encodable<T>? using,
})

Implementation

static List<int> encodeBytes<T>(T value, {Encodable<T>? using}) {
  final sink = _StringBytesSink();
  final encoder = CsvEncoder._(sink);
  encoder.encodeObject(value, using: using);
  sink.close();

  // We don't know the keys ahead of time, nor even how much space to reserve
  // for them, which forces an extra copy of the bytes here.
  final builder = BytesBuilder(copy: false);
  for (var i = 0; i < encoder.keys.length; i++) {
    // TODO: We could encode this keys string as we go instead of collecting
    // the list of keys, and encoding them at the end.
    if (i != 0) {
      builder.add(utf8.encode(','));
    }
    builder.add(utf8.encode(encoder.keys[i]));
  }
  builder
    ..add(utf8.encode('\n'))
    ..add(encoder.writer.buffer.takeBytes());

  return builder.takeBytes();
}