summaryrefslogtreecommitdiff
path: root/lib/buffer.js
diff options
context:
space:
mode:
authorVladimir Kurchatkin <vladimir.kurchatkin@gmail.com>2014-12-23 21:03:54 +0300
committerVladimir Kurchatkin <vladimir.kurchatkin@gmail.com>2015-01-28 16:40:15 +0300
commit45d8d9f8262983d7d6434f4500b4e88b63052cd5 (patch)
tree79d9a05710d3bedf240394c1dff57dfe1c232c59 /lib/buffer.js
parent3cbb5cdfdb621baec5dc3a2ac505be37f1718086 (diff)
downloadnodejs-45d8d9f8262983d7d6434f4500b4e88b63052cd5.tar.gz
nodejs-45d8d9f8262983d7d6434f4500b4e88b63052cd5.tar.bz2
nodejs-45d8d9f8262983d7d6434f4500b4e88b63052cd5.zip
buffer: implement `iterable` interface
This makes possible to use `for..of` loop with buffers. Also related `keys`, `values` and `entries` methods are added for feature parity with `Uint8Array`. PR-URL: https://github.com/iojs/io.js/pull/525 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Diffstat (limited to 'lib/buffer.js')
-rw-r--r--lib/buffer.js77
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/buffer.js b/lib/buffer.js
index dbc5d5f56..4c87726d5 100644
--- a/lib/buffer.js
+++ b/lib/buffer.js
@@ -930,3 +930,80 @@ Buffer.prototype.writeDoubleBE = function writeDoubleBE(val, offset, noAssert) {
internal.writeDoubleBE(this, val, offset);
return offset + 8;
};
+
+// ES6 iterator
+
+var ITERATOR_KIND_KEYS = 1;
+var ITERATOR_KIND_ENTRIES = 3;
+
+function BufferIteratorResult(value, done) {
+ this.value = value;
+ this.done = done;
+}
+
+var resultCache = new Array(256);
+
+for (var i = 0; i < 256; i++)
+ resultCache[i] = Object.freeze(new BufferIteratorResult(i, false));
+
+var finalResult = Object.freeze(new BufferIteratorResult(undefined, true));
+
+function BufferIterator(buffer, kind) {
+ this._buffer = buffer;
+ this._kind = kind;
+ this._index = 0;
+}
+
+BufferIterator.prototype.next = function() {
+ var buffer = this._buffer;
+ var kind = this._kind;
+ var index = this._index;
+
+ if (index >= buffer.length)
+ return finalResult;
+
+ this._index++;
+
+ if (kind === ITERATOR_KIND_ENTRIES)
+ return new BufferIteratorResult([index, buffer[index]], false);
+
+ return new BufferIteratorResult(index, false);
+};
+
+function BufferValueIterator(buffer) {
+ BufferIterator.call(this, buffer, null);
+}
+
+BufferValueIterator.prototype.next = function() {
+ var buffer = this._buffer;
+ var index = this._index;
+
+ if (index >= buffer.length)
+ return finalResult;
+
+ this._index++;
+
+ return resultCache[buffer[index]];
+};
+
+
+BufferIterator.prototype[Symbol.iterator] = function() {
+ return this;
+};
+
+BufferValueIterator.prototype[Symbol.iterator] =
+ BufferIterator.prototype[Symbol.iterator];
+
+Buffer.prototype.keys = function() {
+ return new BufferIterator(this, ITERATOR_KIND_KEYS);
+};
+
+Buffer.prototype.entries = function() {
+ return new BufferIterator(this, ITERATOR_KIND_ENTRIES);
+};
+
+Buffer.prototype.values = function() {
+ return new BufferValueIterator(this);
+};
+
+Buffer.prototype[Symbol.iterator] = Buffer.prototype.values;