All files / metadata/src/utilities bulkDataFromArray.ts

32% Statements 8/25
48% Branches 12/25
50% Functions 2/4
33.33% Lines 8/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72                18x 18x                                       18x     18x     18x 18x             18x 18x                                                      
/**
 * Utilities to extract a single ArrayBufferView from bulk data that may be
 * stored as an array of buffers (e.g. from DICOM stream listeners or
 * compressed frame data), matching the pattern used for compressed pixel
 * data frames.
 */
 
function asView(buf: ArrayBuffer | ArrayBufferView): ArrayBufferView {
  Eif (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf);
  }
  return buf as ArrayBufferView;
}
 
/**
 * Extracts a single ArrayBufferView from a value that may be:
 * - A single ArrayBuffer or ArrayBufferView (returned as-view)
 * - An array of one buffer: returns asView(arr[0])
 * - An array of multiple buffers: concatenates and returns one Uint8Array
 *
 * Use for bulk data that can be delivered as either a single buffer or an
 * array of fragments (e.g. palette LUT, pixel data frame).
 *
 * @param raw - ArrayBuffer, ArrayBufferView, or array of same
 * @returns Single ArrayBufferView, or undefined if raw is not a supported type
 */
export function getSingleBufferFromArray(
  raw: unknown
): ArrayBufferView | undefined {
  Iif (raw instanceof ArrayBuffer || ArrayBuffer.isView(raw)) {
    return asView(raw as ArrayBuffer | ArrayBufferView);
  }
  Iif (!Array.isArray(raw) || raw.length === 0) {
    return undefined;
  }
  const first = raw[0];
  Iif (
    first === undefined ||
    first === null ||
    (!(first instanceof ArrayBuffer) && !ArrayBuffer.isView(first))
  ) {
    return undefined;
  }
  Eif (raw.length === 1) {
    return asView(first as ArrayBuffer | ArrayBufferView);
  }
  const views = raw.filter(
    (item): item is ArrayBuffer | ArrayBufferView =>
      item != null && (item instanceof ArrayBuffer || ArrayBuffer.isView(item))
  );
  if (views.length === 0) return undefined;
  const totalLength = views.reduce(
    (sum, v) =>
      sum +
      (v instanceof ArrayBuffer
        ? v.byteLength
        : (v as ArrayBufferView).byteLength),
    0
  );
  const out = new Uint8Array(totalLength);
  let offset = 0;
  for (const v of views) {
    const view = asView(v);
    out.set(
      new Uint8Array(view.buffer, view.byteOffset, view.byteLength),
      offset
    );
    offset += view.byteLength;
  }
  return out;
}