|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"use strict"; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", { |
|
|
value: true |
|
|
}); |
|
|
exports.extract = extract; |
|
|
exports.inject = inject; |
|
|
exports.getSign = getSign; |
|
|
exports.highOrder = highOrder; |
|
|
|
|
|
function extract(buffer, bitIndex, bitLength, defaultBit) { |
|
|
if (bitLength < 0 || bitLength > 32) { |
|
|
throw new Error("Bad value for bitLength."); |
|
|
} |
|
|
|
|
|
if (defaultBit === undefined) { |
|
|
defaultBit = 0; |
|
|
} else if (defaultBit !== 0 && defaultBit !== 1) { |
|
|
throw new Error("Bad value for defaultBit."); |
|
|
} |
|
|
|
|
|
var defaultByte = defaultBit * 0xff; |
|
|
var result = 0; |
|
|
|
|
|
|
|
|
var lastBit = bitIndex + bitLength; |
|
|
var startByte = Math.floor(bitIndex / 8); |
|
|
var startBit = bitIndex % 8; |
|
|
var endByte = Math.floor(lastBit / 8); |
|
|
var endBit = lastBit % 8; |
|
|
|
|
|
if (endBit !== 0) { |
|
|
|
|
|
|
|
|
result = get(endByte) & (1 << endBit) - 1; |
|
|
} |
|
|
|
|
|
while (endByte > startByte) { |
|
|
endByte--; |
|
|
result = result << 8 | get(endByte); |
|
|
} |
|
|
|
|
|
result >>>= startBit; |
|
|
return result; |
|
|
|
|
|
function get(index) { |
|
|
var result = buffer[index]; |
|
|
return result === undefined ? defaultByte : result; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function inject(buffer, bitIndex, bitLength, value) { |
|
|
if (bitLength < 0 || bitLength > 32) { |
|
|
throw new Error("Bad value for bitLength."); |
|
|
} |
|
|
|
|
|
var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); |
|
|
|
|
|
if (bitIndex < 0 || lastByte >= buffer.length) { |
|
|
throw new Error("Index out of range."); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
var atByte = Math.floor(bitIndex / 8); |
|
|
var atBit = bitIndex % 8; |
|
|
|
|
|
while (bitLength > 0) { |
|
|
if (value & 1) { |
|
|
buffer[atByte] |= 1 << atBit; |
|
|
} else { |
|
|
buffer[atByte] &= ~(1 << atBit); |
|
|
} |
|
|
|
|
|
value >>= 1; |
|
|
bitLength--; |
|
|
atBit = (atBit + 1) % 8; |
|
|
|
|
|
if (atBit === 0) { |
|
|
atByte++; |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function getSign(buffer) { |
|
|
return buffer[buffer.length - 1] >>> 7; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function highOrder(bit, buffer) { |
|
|
var length = buffer.length; |
|
|
var fullyWrongByte = (bit ^ 1) * 0xff; |
|
|
|
|
|
while (length > 0 && buffer[length - 1] === fullyWrongByte) { |
|
|
length--; |
|
|
} |
|
|
|
|
|
if (length === 0) { |
|
|
|
|
|
return -1; |
|
|
} |
|
|
|
|
|
var byteToCheck = buffer[length - 1]; |
|
|
var result = length * 8 - 1; |
|
|
|
|
|
for (var i = 7; i > 0; i--) { |
|
|
if ((byteToCheck >> i & 1) === bit) { |
|
|
break; |
|
|
} |
|
|
|
|
|
result--; |
|
|
} |
|
|
|
|
|
return result; |
|
|
} |