All files / static / util / int16bytes_conv.js

100.00% Branches 6/6
100.00% Lines 59/59
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
x1
x1
x1
x1
x1
x1
x2
x1
x1
x1
x1
x1
x1
x1
x1
x2
x10
x10
x18
x18
x1
x17
x17
x17
x17
x1
x17
x10
x1
x1
x1
x1
x1
x1
x1
x1
x2
x6
x6
x10
x10
x1
x9
x9
x9
x1
x6
x8829
x8829
x8829
x1
x9
x6
x1
x1
x1
x1
x1
























































/**
 * @file Conversion between `Int16Array` and `Uint8Array` without system dependency
 *
 * @author aKuad
 */

import { typeof_detail } from "../util/typeof_detail.js";


/**
 * Convert from Int16Array to `Uint8Array` as little endian, without dependency of system
 *
 * @param {Int16Array} int16_array Array to convert to `Uint8Array`
 * @return {Uint8Array} Converted array
 */
export function int16_to_uint8_little_endian(int16_array) {
  // Arguments type checking
  if(!(int16_array instanceof Int16Array)) {
    throw new TypeError(`int16_array must be a Int16Array, but got ${typeof_detail(int16_array)}`);
  }

  const int16_array_little = new Int16Array(int16_array.length);
  const int16_array_little_view = new DataView(int16_array_little.buffer);
  int16_array.forEach((value, index) => int16_array_little_view.setInt16(index * 2, value, true));
  //                                                          int16 is 2 bytes ~~~         ~~~~ write as little endian

  return new Uint8Array(int16_array_little.buffer);
}


/**
 * Convert from `Uint8Array` to `Int16Array` as little endian, without dependency of system
 *
 * @param {Uint8Array} uint8_array Array to convert to `Int16Array`
 * @returns {Int16Array} Converted array
 */
export function uint8_to_int16_little_endian(uint8_array) {
  // Arguments type checking
  if(!(uint8_array instanceof Uint8Array)) {
    throw new TypeError(`uint8_array must be a Uint8Array, but got ${typeof_detail(uint8_array)}`);
  }

  const int16_array_little = new Int16Array(uint8_array.buffer);
  const int16_array_little_view = new DataView(int16_array_little.buffer);
  const int16_array = new Int16Array(int16_array_little);

  for(let i = 0; i < int16_array_little.length; i++) {
    int16_array[i] = int16_array_little_view.getInt16(i * 2, true);
    //                            int16 is 2 bytes ~~~  ~~~~ read as little endian
  }

  return int16_array;
}


// For big endian is not implemented, because of unnecessary now
// export function int16_to_uint8_little_endian(int16_array) {}
// export function uint8_to_int16_little_endian(uint8_array) {}