Passed
Push — master ( 13b350...038bd4 )
by Rafael S.
03:46
created

FloatParser.packFloatBits_   B

Complexity

Conditions 6

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 19
dl 0
loc 31
rs 8.5166
c 0
b 0
f 0
1
/*
2
 * Copyright (c) 2018-2019 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 Encode and decode IEEE 754 floating point numbers.
29
 * @see https://github.com/rochars/byte-data
30
 * @see https://github.com/rochars/wavefile
31
 * @see https://bitbucket.org/lindenlab/llsd/raw/7d2646cd3f9b4c806e73aebc4b32bd81e4047fdc/js/typedarray.js
32
 * @see https://github.com/kazuho/ieee754.js/blob/master/ieee754.js
33
 */
34
35
/**
36
 * A class to encode and decode IEEE 754 floating-point numbers.
37
 */
38
export class FloatParser {
39
40
  /**
41
   * Pack a IEEE 754 floating point number.
42
   * @param {number} ebits The exponent bits.
43
   * @param {number} fbits The fraction bits.
44
   */
45
  constructor(ebits, fbits) {
46
    /**
47
     * @type {number}
48
     */
49
    this.offset = Math.ceil((ebits + fbits) / 8);
50
    /**
51
     * @type {number}
52
     * @private
53
     */
54
    this.ebits = ebits;
55
    /**
56
     * @type {number}
57
     * @private
58
     */
59
    this.fbits = fbits;
60
    /**
61
     * @type {number}
62
     * @private
63
     */
64
    this.bias = (1 << (ebits - 1)) - 1;
65
    /**
66
     * @type {number}
67
     * @private
68
     */
69
    this.biasP2 = Math.pow(2, this.bias + 1);
70
    /**
71
     * @type {number}
72
     * @private
73
     */
74
    this.ebitsFbits = (ebits + fbits);
75
    /**
76
     * @type {number}
77
     * @private
78
     */
79
    this.fbias = Math.pow(2, -(8 * this.offset - 1 - ebits));
80
  }
81
82
  /**
83
   * Pack a IEEE 754 floating point number.
84
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
85
   * @param {number} num The number.
86
   * @param {number} index The index to write on the buffer.
87
   * @return {number} The next index to write on the buffer.
88
   */
89
  pack(buffer, num, index) {
90
    // Round overflows
91
    if (Math.abs(num) > this.biasP2 - (this.ebitsFbits * 2)) {
92
      num = num < 0 ? -Infinity : Infinity;
93
    }
94
    /**
95
     * sign, need this to handle negative zero
96
     * @see http://cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/
97
     * @type {number}
98
     */
99
    let sign = (((num = +num) || 1 / num) < 0) ? 1 : num < 0 ? 1 : 0;
100
    num = Math.abs(num);
101
    /** @type {number} */
102
    let exp = Math.min(Math.floor(Math.log(num) / Math.LN2), 1023);
103
    /** @type {number} */
104
    let fraction = roundToEven(num / Math.pow(2, exp) * Math.pow(2, this.fbits));
105
    // NaN
106
    if (num !== num) {
107
      fraction = Math.pow(2, this.fbits - 1);
108
      exp = (1 << this.ebits) - 1;
109
    // Number
110
    } else if (num !== 0) {
111
      if (num >= Math.pow(2, 1 - this.bias)) {
112
        if (fraction / Math.pow(2, this.fbits) >= 2) {
113
          exp = exp + 1;
114
          fraction = 1;
115
        }
116
        // Overflow
117
        if (exp > this.bias) {
118
          exp = (1 << this.ebits) - 1;
119
          fraction = 0;
120
        } else {
121
          exp = exp + this.bias;
122
          fraction = roundToEven(fraction) - Math.pow(2, this.fbits);
123
        }
124
      } else {
125
        fraction = roundToEven(num / Math.pow(2, 1 - this.bias - this.fbits));
126
        exp = 0;
127
      } 
128
    }
129
    return this.packFloatBits_(buffer, index, sign, exp, fraction);
130
  }
131
132
  /**
133
   * Unpack a IEEE 754 floating point number.
134
   * Derived from IEEE754 by DeNA Co., Ltd., MIT License. 
135
   * Adapted to handle NaN. Should port the solution to the original repo.
136
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
137
   * @param {number} index The index to read from the buffer.
138
   * @return {number} The floating point number.
139
   */
140
  unpack(buffer, index) {
141
    /** @type {number} */
142
    let eMax = (1 << this.ebits) - 1;
143
    /** @type {number} */
144
    let significand;
145
    /** @type {string} */
146
    let leftBits = "";
147
    for (let i = this.offset - 1; i >= 0 ; i--) {
148
      /** @type {string} */
149
      let t = buffer[i + index].toString(2);
150
      leftBits += "00000000".substring(t.length) + t;
151
    }
152
    /** @type {number} */
153
    let sign = leftBits.charAt(0) == "1" ? -1 : 1;
154
    leftBits = leftBits.substring(1);
155
    /** @type {number} */
156
    let exponent = parseInt(leftBits.substring(0, this.ebits), 2);
157
    leftBits = leftBits.substring(this.ebits);
158
    if (exponent == eMax) {
159
      if (parseInt(leftBits, 2) !== 0) {
160
        return NaN;
161
      }
162
      return sign * Infinity;  
163
    } else if (exponent === 0) {
164
      exponent += 1;
165
      significand = parseInt(leftBits, 2);
166
    } else {
167
      significand = parseInt("1" + leftBits, 2);
168
    }
169
    return sign * significand * this.fbias * Math.pow(2, exponent - this.bias);
170
  }
171
172
  /**
173
   * Pack a IEEE754 from its sign, exponent and fraction bits
174
   * and place it in a byte buffer.
175
   * @param {!Uint8Array|!Array<number>} buffer The byte buffer to write to.
176
   * @param {number} index The buffer index to write.
177
   * @param {number} sign The sign.
178
   * @param {number} exp the exponent.
179
   * @param {number} fraction The fraction.
180
   * @return {number}
181
   * @private
182
   */
183
  packFloatBits_(buffer, index, sign, exp, fraction) {
184
    /** @type {!Array<number>} */
185
    let bits = [];
186
    // the sign
187
    bits.push(sign);
188
    // the exponent
189
    for (let i = this.ebits; i > 0; i -= 1) {
190
      bits[i] = (exp % 2 ? 1 : 0);
191
      exp = Math.floor(exp / 2);
192
    }
193
    // the fraction
194
    let len = bits.length;
195
    for (let i = this.fbits; i > 0; i -= 1) {
196
      bits[len + i] = (fraction % 2 ? 1 : 0);
197
      fraction = Math.floor(fraction / 2);
198
    }
199
    // pack as bytes
200
    /** @type {string} */
201
    let str = bits.join('');
202
    /** @type {number} */
203
    let offset = this.offset + index - 1;
204
    /** @type {number} */
205
    let k = index;
206
    while (offset >= index) {
207
      buffer[offset] = parseInt(str.substring(0, 8), 2);
208
      str = str.substring(8);
209
      offset--;
210
      k++;
211
    }
212
    return k;
213
  }
214
}
215
216
/**
217
 * Round a number to its nearest even value.
218
 * @param {number} n The number.
219
 * @return {number}
220
 * @private
221
 */
222
function roundToEven(n) {
223
  /** @type {number} */
224
  let w = Math.floor(n);
225
  let f = n - w;
226
  if (f < 0.5) {
227
    return w;
228
  }
229
  if (f > 0.5) {
230
    return w + 1;
231
  }
232
  return w % 2 ? w + 1 : w;
233
}
234