ZBytes.fromString constructor

ZBytes.fromString(
  1. String value
)

Creates ZBytes by copying the given value string.

The string is encoded to UTF-8 bytes and copied via the length-based native copy, so embedded NUL characters are preserved (a NUL-terminated copy would truncate at the first NUL). This mirrors ZBytes.fromUint8List.

Throws ZenohException if the native copy fails.

Implementation

factory ZBytes.fromString(String value) {
  final data = Uint8List.fromList(utf8.encode(value));
  final ptr = calloc.allocate<Void>(bindings.zd_bytes_sizeof());
  final nativeBuf = calloc<Uint8>(data.length);
  // memcpy-form copy, the idiom already used at serializer.dart:253/270,
  // native_string.dart:35 and keyexpr.dart:282. Guarded on non-empty: the
  // byte loop was vacuously safe at length 0 and `asTypedList` need not be.
  if (data.isNotEmpty) {
    nativeBuf.asTypedList(data.length).setAll(0, data);
  }
  try {
    final rc = bindings.zd_bytes_copy_from_buf(
      ptr.cast(),
      nativeBuf,
      data.length,
    );
    if (rc != 0) {
      calloc.free(ptr);
      throw ZenohException('Failed to create ZBytes from string', rc);
    }
  } finally {
    calloc.free(nativeBuf);
  }
  return ZBytes._(ptr);
}