123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- 'use strict';
-
- const { EMPTY_BUFFER } = require('./constants');
-
-
- function concat(list, totalLength) {
- if (list.length === 0) return EMPTY_BUFFER;
- if (list.length === 1) return list[0];
-
- const target = Buffer.allocUnsafe(totalLength);
- let offset = 0;
-
- for (let i = 0; i < list.length; i++) {
- const buf = list[i];
- target.set(buf, offset);
- offset += buf.length;
- }
-
- if (offset < totalLength) return target.slice(0, offset);
-
- return target;
- }
-
-
- function _mask(source, mask, output, offset, length) {
- for (let i = 0; i < length; i++) {
- output[offset + i] = source[i] ^ mask[i & 3];
- }
- }
-
-
- function _unmask(buffer, mask) {
- for (let i = 0; i < buffer.length; i++) {
- buffer[i] ^= mask[i & 3];
- }
- }
-
-
- function toArrayBuffer(buf) {
- if (buf.byteLength === buf.buffer.byteLength) {
- return buf.buffer;
- }
-
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- }
-
-
- function toBuffer(data) {
- toBuffer.readOnly = true;
-
- if (Buffer.isBuffer(data)) return data;
-
- let buf;
-
- if (data instanceof ArrayBuffer) {
- buf = Buffer.from(data);
- } else if (ArrayBuffer.isView(data)) {
- buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
- } else {
- buf = Buffer.from(data);
- toBuffer.readOnly = false;
- }
-
- return buf;
- }
-
- try {
- const bufferUtil = require('bufferutil');
-
- module.exports = {
- concat,
- mask(source, mask, output, offset, length) {
- if (length < 48) _mask(source, mask, output, offset, length);
- else bufferUtil.mask(source, mask, output, offset, length);
- },
- toArrayBuffer,
- toBuffer,
- unmask(buffer, mask) {
- if (buffer.length < 32) _unmask(buffer, mask);
- else bufferUtil.unmask(buffer, mask);
- }
- };
- } catch (e) {
- module.exports = {
- concat,
- mask: _mask,
- toArrayBuffer,
- toBuffer,
- unmask: _unmask
- };
- }
|