Completed
Push — master ( e5178b...0c37db )
by Rafael S.
01:52
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 {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
 */
151
export function packStringTo(str, buffer, index=0) {
152
  /** @type {!Array<!number>} */
153
  let bytes = packString(str);
154
  for (let i = 0; i < bytes.length; i++) {
155
    buffer[index++] = bytes[i];
156
  }
157
  return index;
158
}
159
160
// Numbers
161
/**
162
 * Pack a number as a byte buffer.
163
 * @param {number} value The number.
164
 * @param {!Object} theType The type definition.
165
 * @return {!Array<number>} The packed value.
166
 * @throws {Error} If the type definition is not valid.
167
 * @throws {Error} If the value is not valid.
168
 */
169
export function pack(value, theType) {
170
  /** @type {!Array<!number>} */
171
  let output = [];
172
  packTo(value, theType, output);
173
  return output;
174
}
175
176
/**
177
 * Pack a number to a byte buffer.
178
 * @param {number} value The value.
179
 * @param {!Object} theType The type definition.
180
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
181
 * @param {number=} index The index to write.
182
 * @return {number} The next index to write.
183
 * @throws {Error} If the type definition is not valid.
184
 * @throws {Error} If the value is not valid.
185
 */
186
export function packTo(value, theType, buffer, index=0) {
187
  return packArrayTo([value], theType, buffer, index);
188
}
189
190
/**
191
 * Pack an array of numbers as a byte buffer.
192
 * @param {!Array<number>|!TypedArray} values The values.
193
 * @param {!Object} theType The type definition.
194
 * @return {!Array<number>} The packed values.
195
 * @throws {Error} If the type definition is not valid.
196
 * @throws {Error} If any of the values are not valid.
197
 */
198
export function packArray(values, theType) {
199
  /** @type {!Array<!number>} */
200
  let output = [];
201
  packArrayTo(values, theType, output);
202
  return output;
203
}
204
205
/**
206
 * Pack a array of numbers to a byte buffer.
207
 * @param {!Array<number>|!TypedArray} values The value.
208
 * @param {!Object} theType The type definition.
209
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
210
 * @param {number=} index The buffer index to write.
211
 * @return {number} The next index to write.
212
 * @throws {Error} If the type definition is not valid.
213
 * @throws {Error} If the value is not valid.
214
 */
215
export function packArrayTo(values, theType, buffer, index=0) {
216
  setUp_(theType);
217
  for (let i=0; i < values.length; i++) {
218
    validateNotUndefined(values[i]);
219
    validateValueType(values[i]);
220
    /** @type {number} */
221
    let len = index + theType.offset;
222
    while (index < len) {
223
      index = writer_(buffer, values[i], index);
224
    }
225
    if (theType.be) {
226
      endianness(
227
        buffer, theType.offset, index - theType.offset, index);
228
    }
229
  }
230
  return index;
231
}
232
233
/**
234
 * Unpack a number from a byte buffer.
235
 * @param {!Uint8Array|!Array<!number>} buffer The byte buffer.
236
 * @param {!Object} theType The type definition.
237
 * @param {number=} index The buffer index to read.
238
 * @return {number}
239
 * @throws {Error} If the type definition is not valid
240
 */
241
export function unpack(buffer, theType, index=0) {
242
  setUp_(theType);
243
  if ((theType.offset + index) > buffer.length) {
244
    throw Error('Bad buffer length.');
245
  }
246
  if (theType.be) {
247
    endianness(buffer, theType.offset, index, index + theType.offset);
248
  }
249
  /** @type {number} */
250
  let value = reader_(buffer, index);
251
  if (theType.be) {
252
    endianness(buffer, theType.offset, index, index + theType.offset);
253
  }
254
  return value;
255
}
256
257
/**
258
 * Unpack an array of numbers from a byte buffer.
259
 * @param {!Uint8Array|!Array<!number>} buffer The byte buffer.
260
 * @param {!Object} theType The type definition.
261
 * @param {number=} index The start index. Assumes 0.
262
 * @param {?number=} end The end index. Assumes the buffer length.
263
 * @return {!Array<number>}
264
 * @throws {Error} If the type definition is not valid
265
 */
266
export function unpackArray(buffer, theType, index=0, end=buffer.length) {
267
  /** @type {!Array<!number>} */
268
  let output = [];
269
  unpackArrayTo(buffer, theType, output, index, end);
270
  return output;
271
}
272
273
/**
274
 * Unpack a array of numbers to a typed array.
275
 * @param {!Uint8Array|!Array<!number>} buffer The byte buffer.
276
 * @param {!Object} theType The type definition.
277
 * @param {!TypedArray|!Array<!number>} output The output array.
278
 * @param {number=} index The start index. Assumes 0.
279
 * @param {?number=} end The end index. Assumes the buffer length.
280
 * @throws {Error} If the type definition is not valid
281
 */
282
export function unpackArrayTo(buffer, theType, output, index=0, end=buffer.length) {
283
  setUp_(theType);
284
  while ((end - index) % theType.offset) {
285
      end--;
286
  }
287
  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...
288
    output[i] = unpack(buffer, theType, index);
289
  }
290
}
291