Passed
Push — master ( 4a4361...ea4b6f )
by Rafael S.
01:25
created

ieee754-buffer.js ➔ constructor   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 8
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 9
rs 10
1
/*
2
 * Copyright (c) 2018 Rafael da Silva Rocha.
3
 * Copyright (c) 2013 DeNA Co., Ltd.
4
 * Copyright (c) 2010, Linden Research, Inc
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining
7
 * a copy of this software and associated documentation files (the
8
 * "Software"), to deal in the Software without restriction, including
9
 * without limitation the rights to use, copy, modify, merge, publish,
10
 * distribute, sublicense, and/or sell copies of the Software, and to
11
 * permit persons to whom the Software is furnished to do so, subject to
12
 * the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be
15
 * included in all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
 *
25
 */
26
27
/**
28
 * @fileoverview Functions to pack and unpack IEEE 754 floating point numbers.
29
 * @see https://github.com/rochars/ieee754-buffer
30
 * @see https://bitbucket.org/lindenlab/llsd/raw/7d2646cd3f9b4c806e73aebc4b32bd81e4047fdc/js/typedarray.js
31
 * @see https://github.com/kazuho/ieee754.js/blob/master/ieee754.js
32
 */
33
34
/** @module IEEE754Buffer */
35
36
export class IEEE754Buffer {
37
38
  /**
39
   * Pack a IEEE 754 floating point number.
40
   * @param {number} ebits The exponent bits.
41
   * @param {number} fbits The fraction bits.
42
   */
43
  constructor(ebits, fbits) {
44
    this.ebits = ebits;
45
    this.fbits = fbits;
46
    this.bias = (1 << (ebits - 1)) - 1;
47
    this.numBytes = Math.ceil((ebits + fbits) / 8);
48
    this.biasP2 = Math.pow(2, this.bias + 1);
49
    this.ebitsFbits = (ebits + fbits);
50
    this.fbias = Math.pow(2, -(8 * this.numBytes - 1 - ebits));
51
  }
52
53
  /**
54
   * Pack a IEEE 754 floating point number.
55
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
56
   * @param {number} index The index to write on the buffer.
57
   * @param {number} num The number.
58
   * @return {number} The next index to write on the buffer.
59
   */
60
  pack(buffer, index, num) {
61
    // Round overflows
62
    if (Math.abs(num) > this.biasP2 - (this.ebitsFbits * 2)) {
63
      num = num < 0 ? -Infinity : Infinity;
64
    }
65
    /**
66
     * sign, need this to handle negative zero
67
     * @see http://cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/
68
     * @type {number}
69
     */
70
    let sign = (((num = +num) || 1 / num) < 0) ? 1 : num < 0 ? 1 : 0;
71
    num = Math.abs(num);
72
    /** @type {number} */
73
    let exp = Math.min(Math.floor(Math.log(num) / Math.LN2), 1023);
74
    /** @type {number} */
75
    let fraction = this.roundToEven(num / Math.pow(2, exp) * Math.pow(2, this.fbits));
76
    // NaN
77
    if (num !== num) {
78
      fraction = Math.pow(2, this.fbits - 1);
79
      exp = (1 << this.ebits) - 1;
80
    // Number
81
    } else if (num !== 0) {
82
      if (num >= Math.pow(2, 1 - this.bias)) {
83
        if (fraction / Math.pow(2, this.fbits) >= 2) {
84
          exp = exp + 1;
85
          fraction = 1;
86
        }
87
        // Overflow
88
        if (exp > this.bias) {
89
          exp = (1 << this.ebits) - 1;
90
          fraction = 0;
91
        } else {
92
          exp = exp + this.bias;
93
          fraction = this.roundToEven(fraction) - Math.pow(2, this.fbits);
94
        }
95
      } else {
96
        fraction = this.roundToEven(num / Math.pow(2, 1 - this.bias - this.fbits));
97
        exp = 0;
98
      } 
99
    }
100
    return this.packFloatBits_(buffer, index, sign, exp, fraction);
101
  }
102
103
  /**
104
   * Unpack a IEEE 754 floating point number.
105
   * Derived from IEEE754 by DeNA Co., Ltd., MIT License. 
106
   * Adapted to handle NaN. Should port the solution to the original repo.
107
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
108
   * @param {number} index The index to read from the buffer.
109
   * @return {number} The floating point number.
110
   */
111
  unpack(buffer, index) {
112
    /** @type {number} */
113
    let eMax = (1 << this.ebits) - 1;
114
    /** @type {number} */
115
    let significand;
116
    /** @type {string} */
117
    let leftBits = "";
118
    for (let i = this.numBytes - 1; i >= 0 ; i--) {
119
      /** @type {string} */
120
      let t = buffer[i + index].toString(2);
121
      leftBits += "00000000".substring(t.length) + t;
122
    }
123
    /** @type {number} */
124
    let sign = leftBits.charAt(0) == "1" ? -1 : 1;
125
    leftBits = leftBits.substring(1);
126
    /** @type {number} */
127
    let exponent = parseInt(leftBits.substring(0, this.ebits), 2);
128
    leftBits = leftBits.substring(this.ebits);
129
    if (exponent == eMax) {
130
      if (parseInt(leftBits, 2) !== 0) {
131
        return NaN;
132
      }
133
      return sign * Infinity;  
134
    } else if (exponent === 0) {
135
      exponent += 1;
136
      significand = parseInt(leftBits, 2);
137
    } else {
138
      significand = parseInt("1" + leftBits, 2);
139
    }
140
    return sign * significand * this.fbias * Math.pow(2, exponent - this.bias);
141
  }
142
143
  /**
144
   * Pack a IEEE754 from its sign, exponent and fraction bits
145
   * and place it in a byte buffer.
146
   * @param {!Uint8Array|!Array<number>} buffer The byte buffer to write to.
147
   * @param {number} index The buffer index to write.
148
   * @param {number} ebits The number of bits of the exponent.
149
   * @param {number} fbits The number of bits of the fraction.
150
   * @param {number} sign The sign.
151
   * @param {number} exp the exponent.
152
   * @param {number} fraction The fraction.
153
   * @return {number}
154
   * @private
155
   */
156
  packFloatBits_(buffer, index, sign, exp, fraction) {
157
    /** @type {!Array<number>} */
158
    let bits = [];
159
    // the sign
160
    bits.push(sign);
161
    // the exponent
162
    for (let i = this.ebits; i > 0; i -= 1) {
163
      bits[i] = (exp % 2 ? 1 : 0);
164
      exp = Math.floor(exp / 2);
165
    }
166
    // the fraction
167
    let len = bits.length;
168
    for (let i = this.fbits; i > 0; i -= 1) {
169
      bits[len + i] = (fraction % 2 ? 1 : 0);
170
      fraction = Math.floor(fraction / 2);
171
    }
172
    // pack as bytes
173
    /** @type {string} */
174
    let str = bits.join('');
175
    /** @type {number} */
176
    let numBytes = this.numBytes + index - 1;
177
    /** @type {number} */
178
    let k = index;
179
    while (numBytes >= index) {
180
      buffer[numBytes] = parseInt(str.substring(0, 8), 2);
181
      str = str.substring(8);
182
      numBytes--;
183
      k++;
184
    }
185
    return k;
186
  }
187
188
  roundToEven(n) {
189
    var w = Math.floor(n), f = n - w;
190
    if (f < 0.5) {
191
      return w;
192
    }
193
    if (f > 0.5) {
194
      return w + 1;
195
    }
196
    return w % 2 ? w + 1 : w;
197
  }
198
}