1

I need to initialize a large bitmap in Redis with a set of 4 * n bits all equal to 1. If I do this:

var redis = require('redis');
var client = redis.createClient();
var n = 8;
var mask = '\\x';
for (var i = 0; i < n; ++i) {
  mask += 'f';
}
client.set('mybitmap', mask, callback);

...mybitmap gets set to xffffffff instead of the desired \xffffffff.

Any idea on how to escape the backslash in JavaScript in such a way that we don't lose it in Redis?

Note: I am using the node_redis client.

Ismael Ghalimi
  • 3,515
  • 2
  • 22
  • 25

1 Answers1

2

It seems that you cannot put a bitmap with only "1" bits using redis client. Indeed if you build your string like that :

var mask = ''; 
for (var i = 0; i < n; ++i) {
  mask += String.fromCharCode(0xffff);
}

You will get something like that in Redis : 11101111 10111111 10111111 11101111 10111111 10111111 11101111 10111111 10111111 11101111 10111111

While I made sure that in Javascript the following is true : String.fromCharCode(0xffff).toString().charCodeAt(0) === 0xffff

(I had some doubts because of this https://stackoverflow.com/a/3482698/667433 ), somewhere between the Node's Redis client and Redis some bits are lost.

A a solution that would build a plain "1" bitmap is to put all "0" and using NOT on it :

var client = require('redis').createClient();

var n = 8;
var mask = new Array(n + 1).join(String.fromCharCode(0));
client.set('mybitmap', mask, function() {
  client.bitop(['not', 'mybitmap', 'mybitmap'], displayBits);
});

// Just to display what Redis actually stored.
function displayBits() {
  var res = '';
  (function getBit(idx) {
    if (idx === (n + 1) * 8) {
      console.log(res);
      client.quit();
      return;
    }

    client.getbit(['mybitmap', idx], function(e, r) {
     res += r;
     if ((idx + 1) % 8 === 0) { res += '\n'; }
     getBit(idx + 1);
    });
  })(0);
}

Hope it helps

Community
  • 1
  • 1
Y__
  • 1,687
  • 2
  • 11
  • 23