setTo method

void setTo(
  1. Object src
)

Copies the given src data into this tensor.

Implementation

void setTo(Object src) {
  Uint8List bytes = _convertObjectToBytes(src);
  int size = bytes.length;

  // String tensors require buffer reallocation because the pre-allocated
  // buffer size does not match the encoded string data size. The native
  // copy path is kept here because the data pointer moves on realloc.
  if (type == TensorType.string) {
    final reallocStatus = tfliteBinding.TfLiteTensorRealloc(size, _tensor);
    checkState(
      reallocStatus == TfLiteStatus.kTfLiteOk,
      message:
          'TfLiteTensorRealloc failed for string tensor '
          '(requested $size bytes, status=$reallocStatus).',
    );
    final ptr = calloc<Uint8>(size);
    checkState(isNotNull(ptr), message: 'unallocated');
    ptr.asTypedList(size).setRange(0, size, bytes);
    try {
      checkState(
        tfliteBinding.TfLiteTensorCopyFromBuffer(_tensor, ptr.cast(), size) ==
            TfLiteStatus.kTfLiteOk,
        message:
            'TfLiteTensorCopyFromBuffer failed '
            '(buffer=$size bytes, tensor=${numBytes()} bytes).',
      );
    } finally {
      calloc.free(ptr);
    }
    return;
  }

  // Single memcpy straight into the tensor's buffer; no native scratch copy.
  // Plain if+throw instead of checkState: quiver builds the interpolated
  // message eagerly, on every successful call in the hot path.
  final tensorByteSize = tfliteBinding.TfLiteTensorByteSize(_tensor);
  if (tensorByteSize != size) {
    throw StateError(
      'TfLiteTensorCopyFromBuffer failed '
      '(buffer=$size bytes, tensor=$tensorByteSize bytes).',
    );
  }
  final data = cast<Uint8>(tfliteBinding.TfLiteTensorData(_tensor));
  checkState(isNotNull(data), message: 'Tensor data is null.');
  data.asTypedList(tensorByteSize).setRange(0, tensorByteSize, bytes);
}