forked from Level/leveldown
-
Notifications
You must be signed in to change notification settings - Fork 3
/
iterator.js
98 lines (78 loc) · 2.13 KB
/
iterator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const util = require('util')
, AbstractIterator = require('abstract-iterator')
, fastFuture = require('fast-future')
function Iterator (db, options) {
AbstractIterator.call(this, db, options)
this.binding = db.binding.iterator(this.options)
this.cache = null
this.finished = false
this.fastFuture = fastFuture()
}
util.inherits(Iterator, AbstractIterator)
Iterator.prototype.seek = function (target) {
if (this._ended)
throw new Error('cannot call seek() after end()')
if (this._nexting)
throw new Error('cannot call seek() before next() has completed')
if (typeof target !== 'string' && !Buffer.isBuffer(target))
throw new Error('seek() requires a string or buffer key')
if (target.length == 0)
throw new Error('cannot seek() to an empty key')
this.cache = null
this.binding.seek(target)
this.finished = false
}
Iterator.prototype._nextSync = function () {
var key, value
if (this.cache && this.cache.length) {
key = this.cache.pop()
value = this.cache.pop()
} else if (this.finished) {
return false
} else {
var result = this.binding.nextSync()
this.cache = result[0]
this.finished = result[1] <= 0
if (this.cache && this.cache.length) {
key = this.cache.pop()
value = this.cache.pop()
} else {
return false
}
}
return [key, value]
}
Iterator.prototype._endSync = function () {
return this.binding.endSync();
}
/*
Iterator.prototype._next = function (callback) {
var that = this
, key
, value
if (this.cache && this.cache.length) {
key = this.cache.pop()
value = this.cache.pop()
this.fastFuture(function () {
callback(null, key, value)
})
} else if (this.finished) {
this.fastFuture(function () {
callback()
})
} else {
this.binding.next(function (err, array, finished) {
if (err) return callback(err)
that.cache = array
that.finished = finished
that._next(callback)
})
}
return this
}
Iterator.prototype._end = function (callback) {
delete this.cache
this.binding.end(callback)
}
*/
module.exports = Iterator