Completed
Push — master ( 570e0f...e5178b )
by Rafael S.
01:44
created

main.js (2 issues)

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