Passed
Branch v13.x (3f0d34)
by Rafael S.
02:14
created

T_EXPORT   A

Complexity

Total Complexity 5
Complexity/F 2.5

Size

Lines of Code 1
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
noi 0
c 0
b 0
f 0
cc 0
wmc 5
mnd 1
bc 5
fnc 2
rs 10
bpm 2.5
cpm 2.5
1
/*
2
 * Copyright (c) 2017-2018 Rafael da Silva Rocha.
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining
5
 * a copy of this software and associated documentation files (the
6
 * "Software"), to deal in the Software without restriction, including
7
 * without limitation the rights to use, copy, modify, merge, publish,
8
 * distribute, sublicense, and/or sell copies of the Software, and to
9
 * permit persons to whom the Software is furnished to do so, subject to
10
 * the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be
13
 * included in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
25
/**
26
 * @fileoverview A function to swap endianness in byte buffers.
27
 * @see https://github.com/rochars/endianness
28
 */
29
30
/**
31
 * Swap the byte ordering in a buffer. The buffer is modified in place.
32
 * @param {!Array<number|string>|!Uint8Array} bytes The bytes.
33
 * @param {number} offset The byte offset.
34
 * @param {number=} index The start index. Assumes 0.
35
 * @param {?number=} end The end index. Assumes the buffer length.
36
 * @throws {Error} If the buffer length is not valid.
37
 */
38
export default function endianness(bytes, offset, index=0, end=null) {
39
  let len = end || bytes.length;
40
  let limit = parseInt(offset / 2, 10);
41
  if (len % offset) {
42
    throw new Error("Bad buffer length.");
43
  }
44
  while (index < len) {
45
    swap(bytes, offset, index, limit);
46
    index += offset;
47
  }
48
}
49
50
/**
51
 * Swap the byte order of a value in a buffer. The buffer is modified in place.
52
 * @param {!Array<number|string>|!Uint8Array} bytes The bytes.
53
 * @param {number} offset The byte offset.
54
 * @param {number} index The start index.
55
 * @private
56
 */
57
function swap(bytes, offset, index, limit) {
58
  let x = 0;
59
  let y = offset - 1;
60
  while(x < limit) {
61
    let theByte = bytes[index + x];
62
    bytes[index + x] = bytes[index + y];
63
    bytes[index + y] = theByte;
64
    x++;
65
    y--;
66
  }
67
}
68