All files / core/src/utilities getBufferConfiguration.ts

43.75% Statements 7/16
21.42% Branches 3/14
100% Functions 2/2
43.75% Lines 7/16

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 73                            4138x       4138x                                                                               4138x 4138x           4138x 4138x   4138x        
import type { PixelDataTypedArray, PixelDataTypedArrayString } from '../types';
 
/**
 * Gets the appropriate TypedArray constructor based on the provided buffer type.
 *
 * @param bufferType - The type of the buffer.
 * @param isVolumeBuffer - Whether the buffer is for volume rendering.
 * @returns The TypedArray constructor.
 * @throws Error if an unsupported buffer type is provided.
 */
function getConstructorFromType(
  bufferType: PixelDataTypedArrayString,
  isVolumeBuffer: boolean
): new (length: number) => PixelDataTypedArray {
  switch (bufferType) {
    case 'Float32Array':
      return Float32Array;
    case 'Uint8Array':
      return Uint8Array;
    case 'Uint32Array':
      return Uint32Array;
    case 'Uint16Array':
    case 'Int16Array':
      if (!isVolumeBuffer) {
        return bufferType === 'Uint16Array' ? Uint16Array : Int16Array;
      } else {
        console.debug(
          `${bufferType} is not supported for volume rendering, switching back to Float32Array`
        );
        return Float32Array;
      }
    default:
      if (bufferType) {
        throw new Error(
          'TargetBuffer should be Float32Array, Uint8Array, Uint16Array, Int16Array, or Uint32Array'
        );
      } else {
        return Float32Array;
      }
  }
}
 
/**
 * Creates a target buffer configuration based on the provided options.
 *
 * @param targetBufferType - The type of the target buffer.
 * @param length - The length of the target buffer.
 * @param options - Options for the target buffer.
 * @returns An object containing the number of bytes and the TypedArray constructor for the target buffer.
 */
function getBufferConfiguration(
  targetBufferType: PixelDataTypedArrayString,
  length: number,
  options: { isVolumeBuffer?: boolean } = {}
): {
  numBytes: number;
  TypedArrayConstructor: new (length: number) => PixelDataTypedArray;
} {
  const { isVolumeBuffer = false } = options;
  const TypedArrayConstructor = getConstructorFromType(
    targetBufferType,
    isVolumeBuffer
  );
 
  // @ts-expect-error
  const bytesPerElement = TypedArrayConstructor.BYTES_PER_ELEMENT;
  const numBytes = length * bytesPerElement;
 
  return { numBytes, TypedArrayConstructor };
}
 
export { getBufferConfiguration, getConstructorFromType };