add getAsync.

This commit is contained in:
Christopher Jeffrey 2016-01-21 03:58:33 -08:00
parent b65ed25b29
commit c5bc356bc9

View File

@ -756,6 +756,9 @@ ChainDB.prototype.getBuffer = function(size) {
if (!this._bufferPool[size])
this._bufferPool[size] = new Buffer(size);
// if (this._bufferPool[size].__used)
// return new Buffer(size);
return this._bufferPool[size];
};
@ -828,6 +831,46 @@ ChainDB.prototype.get = function get(height) {
return entry;
};
ChainDB.prototype.getAsync = function getAsync(height, callback) {
var self = this;
callback = utils.asyncify(callback);
if (this._cache[height])
return callback(null, this._cache[height]);
if (this._queue[height])
return callback(null, this._queue[height]);
if (height < 0 || height == null)
return callback();
if ((height + 1) * BLOCK_SIZE > this.size)
return callback();
this._readAsync(BLOCK_SIZE, height * BLOCK_SIZE, function(err, data) {
var entry;
if (err)
return callback(err);
if (!data)
return callback();
// Ignore if it is a null block.
if (utils.read32(data, 0) === 0)
return callback();
entry = ChainBlock.fromRaw(self.chain, height, data);
// Cache the past 1001 blocks in memory
// (necessary for isSuperMajority)
self.cache(entry);
return callback(null, entry);
});
};
ChainDB.prototype.save = function save(entry) {
var self = this;
var raw, offset;
@ -843,7 +886,7 @@ ChainDB.prototype.save = function save(entry) {
};
// This causes weird race conditions with size/count/tip.
ChainDB.prototype.saveAsync = function save(entry, callback) {
ChainDB.prototype.saveAsync = function saveAsync(entry, callback) {
var self = this;
var raw, offset;
@ -953,6 +996,32 @@ ChainDB.prototype._read = function _read(size, offset) {
}
};
ChainDB.prototype._readAsync = function _read(size, offset) {
var self = this;
var data = new Buffer(size);
var index = 0;
var bytes;
if (offset < 0 || offset == null)
return false;
(function callee() {
fs.read(self.fd, data, index, size, offset, function(err, bytes) {
if (err)
return callback(err);
index += bytes;
size -= bytes;
offset += bytes;
if (index === data.length)
return callback(null, data);
callee();
});
})();
};
ChainDB.prototype._writeAsync = function _writeAsync(data, offset, callback) {
var self = this;
var added = Math.max(0, (offset + data.length) - this.size);