JsModuleBundle.fromBytes constructor

JsModuleBundle.fromBytes(
  1. Uint8List bytes
)

Inverse of toBytes.

Implementation

factory JsModuleBundle.fromBytes(Uint8List bytes) {
  final view = ByteData.view(
    bytes.buffer,
    bytes.offsetInBytes,
    bytes.lengthInBytes,
  );
  var offset = 0;
  int takeUint32(String field) {
    if (offset + 4 > bytes.length) {
      throw FormatException('JsModuleBundle: truncated at $field');
    }
    final value = view.getUint32(offset, Endian.little);
    offset += 4;
    return value;
  }

  Uint8List takeBytes(int length, String field) {
    if (length < 0 || offset + length > bytes.length) {
      throw FormatException('JsModuleBundle: truncated at $field');
    }
    final value = Uint8List.sublistView(bytes, offset, offset + length);
    offset += length;
    return value;
  }

  if (takeUint32('magic') != _magic) {
    throw const FormatException('JsModuleBundle: bad magic');
  }
  final version = takeUint32('version');
  if (version != _formatVersion) {
    throw FormatException('JsModuleBundle: unsupported format v$version');
  }
  final entry = utf8.decode(takeBytes(takeUint32('entry length'), 'entry'));
  final count = takeUint32('module count');
  final modules = <String, Uint8List>{};
  for (var i = 0; i < count; i++) {
    final name = utf8.decode(takeBytes(takeUint32('name length'), 'name'));
    modules[name] = Uint8List.fromList(
      takeBytes(takeUint32('bytecode length'), 'bytecode'),
    );
  }
  return JsModuleBundle(entry: entry, modules: modules);
}