Passed
Push — master ( 567ae9...db344a )
by Rafael S.
01:53
created
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 The byte-data API.
27
 * @see https://github.com/rochars/byte-data
28
 */
29
30
/** @module byteData */
31
32
import endianness from './lib/endianness.js';
33
import utf8BufferSize from './lib/utf8-buffer-size.js';
34
import {reader_, setUp_, writer_} from './lib/packer.js';
35
import {validateNotUndefined, validateValueType} from './lib/validation.js';
36
37
/**
38
 * Read a string of UTF-8 characters from a byte buffer.
39
 * @see https://encoding.spec.whatwg.org/#the-encoding
40
 * @see https://stackoverflow.com/a/34926911
41
 * @param {!Uint8Array|!Array<!number>} buffer A byte buffer.
42
 * @param {number=} index The index to read.
43
 * @param {?number=} len The number of bytes to read.
44
 *    If len is undefined will read until the end of the buffer.
45
 * @return {string}
46
 */
47
export function unpackString(buffer, index=0, len=undefined) {
48
  len = len !== undefined ? index + len : buffer.length;
49
  /** @type {string} */
50
  let str = "";
51
  while(index < len) {
52
    /** @type {number} */
53
    let lowerBoundary = 0x80;
54
    /** @type {number} */
55
    let upperBoundary = 0xBF;
56
    /** @type {boolean} */
57
    let replace = false;
58
    /** @type {number} */
59
    let charCode = buffer[index++];
60
    if (charCode >= 0x00 && charCode <= 0x7F) {
61
      str += String.fromCharCode(charCode);
62
    } else {
63
      /** @type {number} */
64
      let count = 0;
65
      if (charCode >= 0xC2 && charCode <= 0xDF) {
66
        count = 1;
67
      } else if (charCode >= 0xE0 && charCode <= 0xEF ) {
68
        count = 2;
69
        if (buffer[index] === 0xE0) {
70
          lowerBoundary = 0xA0;
71
        }
72
        if (buffer[index] === 0xED) {
73
          upperBoundary = 0x9F;
74
        }
75
      } else if (charCode >= 0xF0 && charCode <= 0xF4 ) {
76
        count = 3;
77
        if (buffer[index] === 0xF0) {
78
          lowerBoundary = 0x90;
79
        }
80
        if (buffer[index] === 0xF4) {
81
          upperBoundary = 0x8F;
82
        }
83
      } else {
84
        replace = true;
85
      }
86
      charCode = charCode & (1 << (8 - count - 1)) - 1;
87
      for (let i = 0; i < count; i++) {
88
        if (buffer[index] < lowerBoundary || buffer[index] > upperBoundary) {
89
          replace = true;
90
        }
91
        charCode = (charCode << 6) | (buffer[index] & 0x3f);
92
        index++;
93
      }
94
      if (replace) {
95
        str += String.fromCharCode(0xFFFD);
96
      } 
97
      else if (charCode <= 0xffff) {
98
        str += String.fromCharCode(charCode);
99
      } else {
100
        charCode -= 0x10000;
101
        str += String.fromCharCode(
102
          ((charCode >> 10) & 0x3ff) + 0xd800,
103
          (charCode & 0x3ff) + 0xdc00);
104
      }
105
    }
106
  }
107
  return str;
108
}
109
110
/**
111
 * Write a string of UTF-8 characters as a byte buffer.
112
 * @see https://encoding.spec.whatwg.org/#utf-8-encoder
113
 * @param {string} str The string to pack.
114
 * @return {!Uint8Array} The packed string.
115
 */
116
export function packString(str) {
117
  /** @type {!Uint8Array} */
118
  let bytes = new Uint8Array(utf8BufferSize(str));
119
  let bufferIndex = 0;
120
  for (let i = 0, len = str.length; i < len; i++) {
121
    /** @type {number} */
122
    let codePoint = str.codePointAt(i);
123
    if (codePoint < 128) {
124
      bytes[bufferIndex] = codePoint;
125
      bufferIndex++;
126
    } else {
127
      /** @type {number} */
128
      let count = 0;
129
      /** @type {number} */
130
      let offset = 0;
131
      if (codePoint <= 0x07FF) {
132
        count = 1;
133
        offset = 0xC0;
134
      } else if(codePoint <= 0xFFFF) {
135
        count = 2;
136
        offset = 0xE0;
137
      } else if(codePoint <= 0x10FFFF) {
138
        count = 3;
139
        offset = 0xF0;
140
        i++;
0 ignored issues
show
Complexity Coding Style introduced by
You seem to be assigning a new value to the loop variable i here. Please check if this was indeed your intention. Even if it was, consider using another kind of loop instead.
Loading history...
141
      }
142
      bytes[bufferIndex] = (codePoint >> (6 * count)) + offset;
143
      bufferIndex++;
144
      while (count > 0) {
145
        bytes[bufferIndex] = 0x80 | (codePoint >> (6 * (count - 1)) & 0x3F);
146
        bufferIndex++;
147
        count--;
148
      }
149
    }
150
  }
151
  return bytes;
152
}
153
154
/**
155
 * Write a string of UTF-8 characters to a byte buffer.
156
 * @param {string} str The string to pack.
157
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
158
 * @param {number=} index The buffer index to start writing.
159
 *   Assumes zero if undefined.
160
 * @return {number} The next index to write in the buffer.
161
 */
162
export function packStringTo(str, buffer, index=0) {
163
  /** @type {!Uint8Array} */
164
  let bytes = packString(str);
165
  for (let i = 0, len = bytes.length; i < len; i++) {
166
    buffer[index++] = bytes[i];
167
  }
168
  return index;
169
}
170
171
// Numbers
172
/**
173
 * Pack a number as a byte buffer.
174
 * @param {number} value The number.
175
 * @param {!Object} theType The type definition.
176
 * @return {!Array<number>} The packed value.
177
 * @throws {Error} If the type definition is not valid.
178
 * @throws {Error} If the value is not valid.
179
 */
180
export function pack(value, theType) {
181
  /** @type {!Array<!number>} */
182
  let output = [];
183
  packTo(value, theType, output);
184
  return output;
185
}
186
187
/**
188
 * Pack a number to a byte buffer.
189
 * @param {number} value The value.
190
 * @param {!Object} theType The type definition.
191
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
192
 * @param {number=} index The buffer index to write. Assumes 0 if undefined.
193
 * @return {number} The next index to write.
194
 * @throws {Error} If the type definition is not valid.
195
 * @throws {Error} If the value is not valid.
196
 */
197
export function packTo(value, theType, buffer, index=0) {
198
  return packArrayTo([value], theType, buffer, index);
199
}
200
201
/**
202
 * Pack an array of numbers as a byte buffer.
203
 * @param {!Array<number>|!TypedArray} values The values.
204
 * @param {!Object} theType The type definition.
205
 * @return {!Array<number>} The packed values.
206
 * @throws {Error} If the type definition is not valid.
207
 * @throws {Error} If any of the values are not valid.
208
 */
209
export function packArray(values, theType) {
210
  /** @type {!Array<!number>} */
211
  let output = [];
212
  packArrayTo(values, theType, output);
213
  return output;
214
}
215
216
/**
217
 * Pack a array of numbers to a byte buffer.
218
 * @param {!Array<number>|!TypedArray} values The value.
219
 * @param {!Object} theType The type definition.
220
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
221
 * @param {number=} index The buffer index to start writing.
222
 *   Assumes zero if undefined.
223
 * @return {number} The next index to write.
224
 * @throws {Error} If the type definition is not valid.
225
 * @throws {Error} If the value is not valid.
226
 */
227
export function packArrayTo(values, theType, buffer, index=0) {
228
  setUp_(theType);
229
  for (let i = 0, valuesLen = values.length; i < valuesLen; i++) {
230
    validateNotUndefined(values[i]);
231
    validateValueType(values[i]);
232
    /** @type {number} */
233
    let len = index + theType.offset;
234
    while (index < len) {
235
      index = writer_(buffer, values[i], index);
236
    }
237
    if (theType.be) {
238
      endianness(
239
        buffer, theType.offset, index - theType.offset, index);
240
    }
241
  }
242
  return index;
243
}
244
245
/**
246
 * Unpack a number from a byte buffer.
247
 * @param {!Uint8Array|!Array<!number>} buffer The byte buffer.
248
 * @param {!Object} theType The type definition.
249
 * @param {number=} index The buffer index to read. Assumes zero if undefined.
250
 * @return {number}
251
 * @throws {Error} If the type definition is not valid
252
 * @throws {Error} On bad buffer length.
253
 */
254
export function unpack(buffer, theType, index=0) {
255
  setUp_(theType);
256
  if ((theType.offset + index) > buffer.length) {
257
    throw Error('Bad buffer length.');
258
  }
259
  if (theType.be) {
260
    endianness(buffer, theType.offset, index, index + theType.offset);
261
  }
262
  /** @type {number} */
263
  let value = reader_(buffer, index);
264
  if (theType.be) {
265
    endianness(buffer, theType.offset, index, index + theType.offset);
266
  }
267
  return value;
268
}
269
270
/**
271
 * Unpack an array of numbers from a byte buffer.
272
 * @param {!Uint8Array|!Array<!number>} buffer The byte buffer.
273
 * @param {!Object} theType The type definition.
274
 * @param {number=} index The buffer index to start reading.
275
 *   Assumes zero if undefined.
276
 * @param {number=} end The buffer index to stop reading.
277
 *   Assumes the buffer length if undefined.
278
 * @return {!Array<number>}
279
 * @throws {Error} If the type definition is not valid
280
 */
281
export function unpackArray(buffer, theType, index=0, end=buffer.length) {
282
  /** @type {!Array<!number>} */
283
  let output = [];
284
  unpackArrayTo(buffer, theType, output, index, end);
285
  return output;
286
}
287
288
/**
289
 * Unpack a array of numbers to a typed array.
290
 * @param {!Uint8Array|!Array<!number>} buffer The byte buffer.
291
 * @param {!Object} theType The type definition.
292
 * @param {!TypedArray|!Array<!number>} output The output array.
293
 * @param {number=} index The buffer index to start reading.
294
 *   Assumes zero if undefined.
295
 * @param {number=} end The buffer index to stop reading.
296
 *   Assumes the buffer length if undefined.
297
 * @throws {Error} If the type definition is not valid
298
 */
299
export function unpackArrayTo(
300
    buffer, theType, output, index=0, end=buffer.length) {
301
  setUp_(theType);
302
  while ((end - index) % theType.offset) {
303
      end--;
304
  }
305
  for (let i = 0; index < end; index += theType.offset, i++) {
0 ignored issues
show
The loop variable i is initialized by the loop but not used in the test. Consider using another type of loop if this is the intended behavior.
Loading history...
306
    output[i] = unpack(buffer, theType, index);
307
  }
308
}
309