UNPKG

ioredis-mock-with-info

Version:

This library emulates ioredis by performing all operations in-memory.

67 lines (58 loc) 1.94 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.setbit = setbit; var MAX_OFFSET = Math.pow(2, 32) - 1; var STR_BIT_0 = String.fromCharCode(0); var constantLengthOf = function constantLengthOf(len) { return function (str) { return str + Array(Math.max(0, len - str.length)).fill(STR_BIT_0).join(''); }; }; /* eslint-disable no-bitwise */ var getBitAt = function getBitAt(position) { return function (byte) { return byte >> position & 1; }; }; var setBitAt = function setBitAt(position) { return function (byte) { return byte | 1 << position; }; }; var resetBitAt = function resetBitAt(position) { return function (byte) { return byte & ~(1 << position); }; }; /* eslint-enable no-bitwise */ var setOrResetBitAt = function setOrResetBitAt(bit) { return bit === 1 ? setBitAt : resetBitAt; }; var getByteAt = function getByteAt(position) { return function (str) { return str.charCodeAt(position); }; }; var setByteAt = function setByteAt(byte) { return function (position) { return function (str) { return str.substr(0, position) + String.fromCharCode(byte) + str.substr(position + 1); }; }; }; function setbit(key, offset, value) { if (offset > MAX_OFFSET) throw new Error('ERR bit offset is not an integer or out of range'); var bit = parseInt(value, 10); if (bit !== 0 && bit !== 1) throw new Error('ERR bit is not an integer or out of range'); var byteOffset = parseInt(offset / 8, 10); var bitOffset = 7 - offset % 8; // redis store bit in reverse order (left to right) var prev = this.data.has(key) ? this.data.get(key) : ''; var prevByte = getByteAt(byteOffset)(prev); var padded = constantLengthOf(byteOffset + 1)(prev); var newByte = setOrResetBitAt(bit)(bitOffset)(prevByte); var newValue = setByteAt(newByte)(byteOffset)(padded); this.data.set(key, newValue); return getBitAt(bitOffset)(prevByte); }