# All files / src/emitter/section data.js

100% Statements 30/30
100% Branches 0/0
100% Functions 4/4
100% Lines 29/29

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    23x
    23x
    23x
    23x

    23x
    57x

    57x

    57x
    57x
    57x

    57x
    57x

    23x
    3x
    3x
    3x
    3x

    3x
    3x
    3x

    3x
    3x

    3x
    3x

    3x
    3x
    3x

    57x

    3x

     // @flow
    import { u8, u32 } from "wasm-types";
    import { varint32, varuint32 } from "../numbers";
    import opcode from "../opcode";
    import OutputStream from "../../utils/output-stream";
    import type { DataSectionType } from "../../generator/flow/types";

    const emitDataSegment = (stream, segment) => {
      stream.push(varuint32, 0, "memory index");

      const { offset, data } = segment;

      stream.push(u8, opcode.i32Const.code, opcode.i32Const.text);
      stream.push(varint32, offset, `segment offset (${offset})`);
      stream.push(u8, opcode.End.code, "end");

      stream.push(varuint32, data.size, "segment size");
      stream.write(data);
    };

    const encodeDataLength = (stream, length) => {
      stream.push(varuint32, 0, "memory index");
      const offset = 0;
      const data = new OutputStream();
      data.push(u32, length, "dataLength");

      stream.push(u8, opcode.i32Const.code, opcode.i32Const.text);
      stream.push(varint32, offset, `segment offset (${offset})`);
      stream.push(u8, opcode.End.code, "end");

      stream.push(varuint32, data.size, "");
      stream.write(data);
    };

    export default function emit(dataSection: DataSectionType): OutputStream {
      const stream = new OutputStream();
      stream.push(varuint32, dataSection.length + 1, "entries");

      // push an entry for the total size of the data section
      const lastEntry = dataSection[dataSection.length - 1];
      const totalDataLength = lastEntry.offset + lastEntry.data.size;
      encodeDataLength(stream, totalDataLength);

      dataSection.forEach(segment => emitDataSegment(stream, segment));

      return stream;
    }