Skip to content

Instantly share code, notes, and snippets.

@chjj chjj/ser-list.js
Created Sep 3, 2016

Embed
What would you like to do?
function serializeList(items) {
var size = 0;
var i, p, data;
for (i = 0; i < items.length; i++)
size += 4 + items[i].length;
data = new Buffer(size);
p = 0;
for (i = 0; i < items.length; i++) {
data.writeUInt32LE(items[i].length, p); // ideally a varint
p += 4;
data.write(items[i], p, 'ascii');
p += items[i].length;
}
return data;
}
function parseItem(data, index) {
var p = 0;
var i = 0;
var len;
// Skip over every item until we
// find the one we're looking for.
while (p < data.length) {
len = data.readUInt32LE(p);
p += 4;
// Found the item.
if (i === index)
return data.toString('ascii', p, p + len);
// Not ours, skip to the next item.
p += len;
i++;
}
// Not found.
return null;
}
function putList(items, callback) {
db.put('list', serializeList(items), callback);
}
function getItem(index, callback) {
db.get('list', function(err, data) {
if (err)
return callback(err);
return callback(null, parseItem(data, index));
});
}
var items = [
'large string0',
'large string1',
'large string2'
];
putList(items, function(err) {
if (err)
throw err;
getItem(1, function(err, item) {
if (err)
throw err;
console.log(item); // large string 1
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.