buffer: add indexOf() method
[platform/upstream/nodejs.git] / doc / api / buffer.markdown
index a753aaa..740498e 100644 (file)
@@ -1,10 +1,10 @@
 # Buffer
 
-    Stability: 3 - Stable
+    Stability: 2 - Stable
 
 Pure JavaScript is Unicode friendly but not nice to binary data.  When
 dealing with TCP streams or the file system, it's necessary to handle octet
-streams. Node has several strategies for manipulating, creating, and
+streams. io.js has several strategies for manipulating, creating, and
 consuming octet streams.
 
 Raw data is stored in instances of the `Buffer` class. A `Buffer` is similar
@@ -33,10 +33,26 @@ encoding method.  Here are the different string encodings.
 * `'binary'` - A way of encoding raw binary data into strings by using only
   the first 8 bits of each character. This encoding method is deprecated and
   should be avoided in favor of `Buffer` objects where possible. This encoding
-  will be removed in future versions of Node.
+  will be removed in future versions of io.js.
 
 * `'hex'` - Encode each byte as two hexadecimal characters.
 
+Creating a typed array from a `Buffer` works with the following caveats:
+
+1. The buffer's memory is copied, not shared.
+
+2. The buffer's memory is interpreted as an array, not a byte array.  That is,
+   `new Uint32Array(new Buffer([1,2,3,4]))` creates a 4-element `Uint32Array`
+   with elements `[1,2,3,4]`, not an `Uint32Array` with a single element
+   `[0x1020304]` or `[0x4030201]`.
+
+NOTE: Node.js v0.8 simply retained a reference to the buffer in `array.buffer`
+instead of cloning it.
+
+While more efficient, it introduces subtle incompatibilities with the typed
+arrays specification.  `ArrayBuffer#slice()` makes a copy of the slice while
+`Buffer#slice()` creates a view.
+
 ## Class: Buffer
 
 The Buffer class is a global type for dealing with binary data directly.
@@ -46,7 +62,9 @@ It can be constructed in a variety of ways.
 
 * `size` Number
 
-Allocates a new buffer of `size` octets.
+Allocates a new buffer of `size` octets. Note, `size` must be no more than
+[kMaxLength](smalloc.html#smalloc_smalloc_kmaxlength). Otherwise, a `RangeError`
+will be thrown here.
 
 ### new Buffer(array)
 
@@ -54,7 +72,13 @@ Allocates a new buffer of `size` octets.
 
 Allocates a new buffer using an `array` of octets.
 
-### new Buffer(str, [encoding])
+### new Buffer(buffer)
+
+* `buffer` {Buffer}
+
+Copies the passed `buffer` data onto a new `Buffer` instance.
+
+### new Buffer(str[, encoding])
 
 * `str` String - string to encode.
 * `encoding` String - encoding to use, Optional.
@@ -76,7 +100,7 @@ otherwise.
 
 Tests if `obj` is a `Buffer`.
 
-### Class Method: Buffer.byteLength(string, [encoding])
+### Class Method: Buffer.byteLength(string[, encoding])
 
 * `string` String
 * `encoding` String, Optional, Default: 'utf8'
@@ -95,7 +119,7 @@ Example:
 
     // ½ + ¼ = ¾: 9 characters, 12 bytes
 
-### Class Method: Buffer.concat(list, [totalLength])
+### Class Method: Buffer.concat(list[, totalLength])
 
 * `list` {Array} List of Buffer objects to concat
 * `totalLength` {Number} Total length of the buffers when concatenated
@@ -115,6 +139,18 @@ If totalLength is not provided, it is read from the buffers in the list.
 However, this adds an additional loop to the function, so it is faster
 to provide the length explicitly.
 
+### Class Method: Buffer.compare(buf1, buf2)
+
+* `buf1` {Buffer}
+* `buf2` {Buffer}
+
+The same as [`buf1.compare(buf2)`](#buffer_buf_compare_otherbuffer). Useful
+for sorting an Array of Buffers:
+
+    var arr = [Buffer('1234'), Buffer('0123')];
+    arr.sort(Buffer.compare);
+
+
 ### buf.length
 
 * Number
@@ -132,7 +168,18 @@ buffer object.  It does not change when the contents of the buffer are changed.
     // 1234
     // 1234
 
-### buf.write(string, [offset], [length], [encoding])
+While the `length` property is not immutable, changing the value of `length`
+can result in undefined and inconsistent behavior. Applications that wish to
+modify the length of a buffer should therefore treat `length` as read-only and
+use `buf.slice` to create a new buffer.
+
+    buf = new Buffer(10);
+    buf.write("abcdefghj", 0, "ascii");
+    console.log(buf.length); // 10
+    buf = buf.slice(0,5);
+    console.log(buf.length); // 5
+
+### buf.write(string[, offset][, length][, encoding])
 
 * `string` String - data to be written to buffer
 * `offset` Number, Optional, Default: 0
@@ -150,16 +197,68 @@ The method will not write partial characters.
     len = buf.write('\u00bd + \u00bc = \u00be', 0);
     console.log(len + " bytes: " + buf.toString('utf8', 0, len));
 
+### buf.writeUIntLE(value, offset, byteLength[, noAssert])
+### buf.writeUIntBE(value, offset, byteLength[, noAssert])
+### buf.writeIntLE(value, offset, byteLength[, noAssert])
+### buf.writeIntBE(value, offset, byteLength[, noAssert])
+
+* `value` {Number} Bytes to be written to buffer
+* `offset` {Number} `0 <= offset <= buf.length`
+* `byteLength` {Number} `0 < byteLength <= 6`
+* `noAssert` {Boolean} Default: false
+* Return: {Number}
 
-### buf.toString([encoding], [start], [end])
+Writes `value` to the buffer at the specified `offset` and `byteLength`.
+Supports up to 48 bits of accuracy. For example:
+
+    var b = new Buffer(6);
+    b.writeUIntBE(0x1234567890ab, 0, 6);
+    // <Buffer 12 34 56 78 90 ab>
+
+Set `noAssert` to `true` to skip validation of `value` and `offset`. Defaults
+to `false`.
+
+### buf.readUIntLE(offset, byteLength[, noAssert])
+### buf.readUIntBE(offset, byteLength[, noAssert])
+### buf.readIntLE(offset, byteLength[, noAssert])
+### buf.readIntBE(offset, byteLength[, noAssert])
+
+* `offset` {Number} `0 <= offset <= buf.length`
+* `byteLength` {Number} `0 < byteLength <= 6`
+* `noAssert` {Boolean} Default: false
+* Return: {Number}
+
+A generalized version of all numeric read methods. Supports up to 48 bits of
+accuracy. For example:
+
+    var b = new Buffer(6);
+    b.writeUint16LE(0x90ab, 0);
+    b.writeUInt32LE(0x12345678, 2);
+    b.readUIntLE(0, 6).toString(16);  // Specify 6 bytes (48 bits)
+    // output: '1234567890ab'
+
+Set `noAssert` to true to skip validation of `offset`. This means that `offset`
+may be beyond the end of the buffer. Defaults to `false`.
+
+### buf.toString([encoding][, start][, end])
 
 * `encoding` String, Optional, Default: 'utf8'
 * `start` Number, Optional, Default: 0
 * `end` Number, Optional, Default: `buffer.length`
 
-Decodes and returns a string from buffer data encoded with `encoding`
-(defaults to `'utf8'`) beginning at `start` (defaults to `0`) and ending at
-`end` (defaults to `buffer.length`).
+Decodes and returns a string from buffer data encoded using the specified
+character set encoding. If `encoding` is `undefined` or `null`, then `encoding`
+defaults to `'utf8'. The `start` and `end` parameters default to `0` and
+`buffer.length` when `undefined`.
+
+    buf = new Buffer(26);
+    for (var i = 0 ; i < 26 ; i++) {
+      buf[i] = i + 97; // 97 is ASCII a
+    }
+    buf.toString('ascii'); // outputs: abcdefghijklmnopqrstuvwxyz
+    buf.toString('ascii',0,5); // outputs: abcde
+    buf.toString('utf8',0,5); // outputs: abcde
+    buf.toString(undefined,0,5); // encoding defaults to 'utf8', outputs abcde
 
 See `buffer.write()` example, above.
 
@@ -196,7 +295,7 @@ so the legal range is between `0x00` and `0xFF` hex or `0` and `255`.
 
 Example: copy an ASCII string into a buffer, one byte at a time:
 
-    str = "node.js";
+    str = "io.js";
     buf = new Buffer(str.length);
 
     for (var i = 0; i < str.length ; i++) {
@@ -205,21 +304,34 @@ Example: copy an ASCII string into a buffer, one byte at a time:
 
     console.log(buf);
 
-    // node.js
+    // io.js
+
+### buf.equals(otherBuffer)
+
+* `otherBuffer` {Buffer}
 
-### buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
+Returns a boolean of whether `this` and `otherBuffer` have the same
+bytes.
+
+### buf.compare(otherBuffer)
+
+* `otherBuffer` {Buffer}
+
+Returns a number indicating whether `this` comes before or after or is
+the same as the `otherBuffer` in sort order.
+
+
+### buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
 
 * `targetBuffer` Buffer object - Buffer to copy into
 * `targetStart` Number, Optional, Default: 0
 * `sourceStart` Number, Optional, Default: 0
 * `sourceEnd` Number, Optional, Default: `buffer.length`
 
-Does copy between buffers. The source and target regions can be overlapped.
-`targetStart` and `sourceStart` default to `0`.
-`sourceEnd` defaults to `buffer.length`.
-
-All values passed that are `undefined`/`NaN` or are out of bounds are set equal
-to their respective defaults.
+Copies data from a region of this buffer to a region in the target buffer even
+if the target memory region overlaps with the source. If `undefined` the
+`targetStart` and `sourceStart` parameters default to `0` while `sourceEnd`
+defaults to `buffer.length`.
 
 Example: build two Buffers, then copy `buf1` from byte 16 through byte 19
 into `buf2`, starting at the 8th byte in `buf2`.
@@ -237,8 +349,22 @@ into `buf2`, starting at the 8th byte in `buf2`.
 
     // !!!!!!!!qrst!!!!!!!!!!!!!
 
+Example: Build a single buffer, then copy data from one region to an overlapping
+region in the same buffer
 
-### buf.slice([start], [end])
+    buf = new Buffer(26);
+
+    for (var i = 0 ; i < 26 ; i++) {
+      buf[i] = i + 97; // 97 is ASCII a
+    }
+
+    buf.copy(buf, 0, 4, 10);
+    console.log(buf.toString());
+
+    // efghijghijklmnopqrstuvwxyz
+
+
+### buf.slice([start][, end])
 
 * `start` Number, Optional, Default: 0
 * `end` Number, Optional, Default: `buffer.length`
@@ -266,7 +392,20 @@ byte from the original Buffer.
     // abc
     // !bc
 
-### buf.readUInt8(offset, [noAssert])
+
+### buf.indexOf(value[, byteOffset])
+
+* `value` String, Buffer or Number
+* `byteOffset` Number, Optional, Default: 0
+* Return: Number
+
+Operates similar to
+[Array#indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf).
+Accepts a String, Buffer or Number. Strings are interpreted as UTF8. Buffers
+will use the entire buffer. So in order to compare a partial Buffer use
+`Buffer#slice()`. Numbers can range from 0 to 255.
+
+### buf.readUInt8(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -295,8 +434,8 @@ Example:
     // 0x23
     // 0x42
 
-### buf.readUInt16LE(offset, [noAssert])
-### buf.readUInt16BE(offset, [noAssert])
+### buf.readUInt16LE(offset[, noAssert])
+### buf.readUInt16BE(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -331,8 +470,8 @@ Example:
     // 0x2342
     // 0x4223
 
-### buf.readUInt32LE(offset, [noAssert])
-### buf.readUInt32BE(offset, [noAssert])
+### buf.readUInt32LE(offset[, noAssert])
+### buf.readUInt32BE(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -359,7 +498,7 @@ Example:
     // 0x03042342
     // 0x42230403
 
-### buf.readInt8(offset, [noAssert])
+### buf.readInt8(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -373,8 +512,8 @@ may be beyond the end of the buffer. Defaults to `false`.
 Works as `buffer.readUInt8`, except buffer contents are treated as two's
 complement signed values.
 
-### buf.readInt16LE(offset, [noAssert])
-### buf.readInt16BE(offset, [noAssert])
+### buf.readInt16LE(offset[, noAssert])
+### buf.readInt16BE(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -389,8 +528,8 @@ may be beyond the end of the buffer. Defaults to `false`.
 Works as `buffer.readUInt16*`, except buffer contents are treated as two's
 complement signed values.
 
-### buf.readInt32LE(offset, [noAssert])
-### buf.readInt32BE(offset, [noAssert])
+### buf.readInt32LE(offset[, noAssert])
+### buf.readInt32BE(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -405,8 +544,8 @@ may be beyond the end of the buffer. Defaults to `false`.
 Works as `buffer.readUInt32*`, except buffer contents are treated as two's
 complement signed values.
 
-### buf.readFloatLE(offset, [noAssert])
-### buf.readFloatBE(offset, [noAssert])
+### buf.readFloatLE(offset[, noAssert])
+### buf.readFloatBE(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -431,8 +570,8 @@ Example:
 
     // 0x01
 
-### buf.readDoubleLE(offset, [noAssert])
-### buf.readDoubleBE(offset, [noAssert])
+### buf.readDoubleLE(offset[, noAssert])
+### buf.readDoubleBE(offset[, noAssert])
 
 * `offset` Number
 * `noAssert` Boolean, Optional, Default: false
@@ -461,7 +600,7 @@ Example:
 
     // 0.3333333333333333
 
-### buf.writeUInt8(value, offset, [noAssert])
+### buf.writeUInt8(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -487,8 +626,8 @@ Example:
 
     // <Buffer 03 04 23 42>
 
-### buf.writeUInt16LE(value, offset, [noAssert])
-### buf.writeUInt16BE(value, offset, [noAssert])
+### buf.writeUInt16LE(value, offset[, noAssert])
+### buf.writeUInt16BE(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -518,8 +657,8 @@ Example:
     // <Buffer de ad be ef>
     // <Buffer ad de ef be>
 
-### buf.writeUInt32LE(value, offset, [noAssert])
-### buf.writeUInt32BE(value, offset, [noAssert])
+### buf.writeUInt32LE(value, offset[, noAssert])
+### buf.writeUInt32BE(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -547,7 +686,7 @@ Example:
     // <Buffer fe ed fa ce>
     // <Buffer ce fa ed fe>
 
-### buf.writeInt8(value, offset, [noAssert])
+### buf.writeInt8(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -564,8 +703,8 @@ should not be used unless you are certain of correctness. Defaults to `false`.
 Works as `buffer.writeUInt8`, except value is written out as a two's complement
 signed integer into `buffer`.
 
-### buf.writeInt16LE(value, offset, [noAssert])
-### buf.writeInt16BE(value, offset, [noAssert])
+### buf.writeInt16LE(value, offset[, noAssert])
+### buf.writeInt16BE(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -582,8 +721,8 @@ should not be used unless you are certain of correctness. Defaults to `false`.
 Works as `buffer.writeUInt16*`, except value is written out as a two's
 complement signed integer into `buffer`.
 
-### buf.writeInt32LE(value, offset, [noAssert])
-### buf.writeInt32BE(value, offset, [noAssert])
+### buf.writeInt32LE(value, offset[, noAssert])
+### buf.writeInt32BE(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -600,8 +739,8 @@ should not be used unless you are certain of correctness. Defaults to `false`.
 Works as `buffer.writeUInt32*`, except value is written out as a two's
 complement signed integer into `buffer`.
 
-### buf.writeFloatLE(value, offset, [noAssert])
-### buf.writeFloatBE(value, offset, [noAssert])
+### buf.writeFloatLE(value, offset[, noAssert])
+### buf.writeFloatBE(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -629,8 +768,8 @@ Example:
     // <Buffer 4f 4a fe bb>
     // <Buffer bb fe 4a 4f>
 
-### buf.writeDoubleLE(value, offset, [noAssert])
-### buf.writeDoubleBE(value, offset, [noAssert])
+### buf.writeDoubleLE(value, offset[, noAssert])
+### buf.writeDoubleBE(value, offset[, noAssert])
 
 * `value` Number
 * `offset` Number
@@ -658,7 +797,7 @@ Example:
     // <Buffer 43 eb d5 b7 dd f9 5f d7>
     // <Buffer d7 5f f9 dd b7 d5 eb 43>
 
-### buf.fill(value, [offset], [end])
+### buf.fill(value[, offset][, end])
 
 * `value`
 * `offset` Number, Optional
@@ -671,6 +810,19 @@ buffer.
     var b = new Buffer(50);
     b.fill("h");
 
+### buffer.values()
+
+Creates iterator for buffer values (bytes). This function is called automatically
+when `buffer` is used in a `for..of` statement.
+
+### buffer.keys()
+
+Creates iterator for buffer keys (indices).
+
+### buffer.entries()
+
+Creates iterator for `[index, byte]` arrays.
+
 ## buffer.INSPECT_MAX_BYTES
 
 * Number, Default: 50
@@ -681,6 +833,22 @@ be overridden by user modules.
 Note that this is a property on the buffer module returned by
 `require('buffer')`, not on the Buffer global, or a buffer instance.
 
+## ES6 iteration
+
+Buffers can be iterated over using `for..of` syntax:
+
+    var buf = new Buffer([1, 2, 3]);
+
+    for (var b of buf)
+      console.log(b)
+
+    // 1
+    // 2
+    // 3
+
+Additionally, `buffer.values()`, `buffer.keys()` and `buffer.entries()`
+methods can be used to create iterators.
+
 ## Class: SlowBuffer
 
 Returns an un-pooled `Buffer`.