Module binary
When dealing with network sockets or binary files, it’s necessary to read and write into byte streams. JavaScript itself does not provide a native representation of binary data, so this module provides two classes addressing this shortcoming. The implementation follows the CommonJS Binary/B proposal.
ByteArray
implements a modifiable and
resizable byte buffer.
ByteString
implements an immutable byte
sequence.
Both classes share a common base class Binary
. The base class
can't be instantiated. It exists only to affirm that ByteString
and ByteArray
instances of Binary
.
When passed to a Java method that expects a byte[]
, instances of
these classes are automatically unwrapped.
Example
// raw network streams only accept Binary as input
const stream = socket.getStream();
stream.write(new ByteArray([0xFA, 0xF0, 0x10, 0x58, 0xFF]));
// network protocols like HTTP/1.1 require ASCII
const CRLF = new ByteString("\r\n", "ASCII");
const EMPTY_LINE = new ByteString("\r\n\r\n", "ASCII");
// saves a java.security.Key to a file;
// the method getEncoded() returns a Java byte[]
fs.write("id_dsa.pub", ByteArray.wrap(publicKey.getEncoded()));
// Generates a salt for hashing
const random = java.security.SecureRandom.getInstance("SHA1PRNG");
const salt = new ByteArray(8);
random.nextBytes(salt); // fills up salt with random bytes
Functions
- toByteArray (str, charset)
- toByteString (str, charset)
Class Binary
Class ByteArray
Instance Methods
- byteAt(offset)
- charAt(offset)
- charCodeAt(offset)
- concat(args...)
- copy(start, end, target, targetOffset)
- decodeToString(encoding)
- every(callback, thisObj)
- filter(callback, thisObj)
- forEach(fn, thisObj)
- get(offset)
- indexOf(sequence, start, stop)
- lastIndexOf(sequence, start, stop)
- map(callback, thisObj)
- pop()
- push(num...)
- reduce(callback, initialValue)
- reduceRight(callback, initialValue)
- reverse()
- set(offset, value)
- shift()
- slice(begin, end)
- some(callback, thisObj)
- sort(comparator)
- splice(index, howMany, elements...)
- split(delimiter, options)
- toArray()
- toByteArray()
- toByteString()
- toString()
- unshift(num...)
- unwrap()
Instance Properties
Static Methods
- wrap(bytes)
Class ByteString
Instance Methods
- byteAt(offset)
- charAt(offset)
- charCodeAt(offset)
- concat(args...)
- copy(start, end, target, targetStart)
- decodeToString(charset)
- get(offset)
- indexOf(sequence, start, stop)
- lastIndexOf(sequence, start, stop)
- slice(begin, end)
- split(delimiter, options)
- toArray()
- toByteArray()
- toByteString()
- toString()
- unwrap()
Instance Properties
Static Methods
- wrap(bytes)
Binary ()
Abstract base class for ByteArray and ByteString. The Binary type exists only to affirm that ByteString and ByteArray instances of Binary.
ByteArray (contentOrLength, [charset])
Constructs a writable and growable byte array.
If the first argument to this constructor is a number, it specifies the initial length of the ByteArray in bytes.
Else, the argument defines the content of the ByteArray. If the argument is a String, the constructor requires a second argument containing the name of the String's encoding. If called without arguments, an empty ByteArray is returned.
Parameters
Binary|Array|String|Number | contentOrLength | content or length of the ByteArray. |
String | [charset] | the encoding name if the first argument is a String. |
ByteArray.prototype. byteAt (offset)
Returns the byte at the given offset as ByteArray.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.byteAt(0); // --> [ByteArray 1]
Parameters
Number | offset |
Returns
ByteArray |
ByteArray.prototype. charAt (offset)
Returns the byte at the given offset as ByteArray.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.charAt(0); // --> [ByteArray 1]
Parameters
Number | offset |
Returns
ByteArray |
ByteArray.prototype. charCodeAt (offset)
Returns charcode at the given offset.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.charCodeAt(0); // --> 0
Parameters
Number | offset |
Returns
Number |
ByteArray.prototype. concat (args...)
Returns a ByteArray composed of itself concatenated with the given ByteString, ByteArray, and Array values.
Parameters
Binary...|Array... | args... | one or more elements to concatenate |
Returns
ByteArray | a new ByteArray |
ByteArray.prototype. copy (start, end, target, targetOffset)
Copy a range of bytes between start and stop from this object to another ByteArray at the given target offset.
Parameters
Number | start | |
Number | end | |
ByteArray | target | |
Number | targetOffset |
ByteArray.prototype. decodeToString (encoding)
Returns the ByteArray decoded to a String using the given encoding
Example
const ba = new ByteArray([240, 159, 152, 130]);
console.log(ba.decodeToString("UTF-8")); // prints 😂
Parameters
String | encoding | the name of the encoding to use |
ByteArray.prototype. every (callback, thisObj)
Tests whether all elements in the array pass the test implemented by the provided function.
Example
const ba = new ByteArray([0,1,2,3,4,5,6,7,8]);
ba.every(function(byte) { return byte > 5; }); // --> false
ba.every(function(byte) { return byte < 10; }); // --> true
Parameters
Function | callback | the callback function |
Object | thisObj | optional this-object for callback |
Returns
Boolean | true if every invocation of callback returns true |
ByteArray.prototype. filter (callback, thisObj)
Return a ByteArray containing the elements of this ByteArray for which the callback function returns true.
Example
const ba = binary.toByteArray("hello world", "utf-8");
const bf = ba.filter(function(byte) { return byte > 110 });
bf.decodeToString(); // returns "owor"
Parameters
Function | callback | the filter function |
Object | thisObj | optional this-object for callback |
Returns
ByteArray | a new ByteArray |
ByteArray.prototype. forEach (fn, thisObj)
Apply a function for each element in the ByteArray.
Example
const ba = binary.toByteArray("hello world", "utf-8");
// prints 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100
ba.forEach(function(byte) { console.log(byte) });
Parameters
Function | fn | the function to call for each element |
Object | thisObj | optional this-object for callback |
ByteArray.prototype. get (offset)
Returns the byte at the given offset as integer. get(offset)
is
analogous to indexing with brackets [offset]
.
Example
const ba = new ByteArray([0,255]);
print(ba[0]); // prints 0
Parameters
Number | offset |
Returns
Number |
ByteArray.prototype. indexOf (sequence, start, stop)
Returns the index of the first occurrence of sequence (a Number or a ByteString or ByteArray of any length) or -1 if none was found. If start and/or stop are specified, only elements between the indexes start and stop are searched.
Parameters
Number|Binary | sequence | the number or binary to look for |
Number | start | optional index position at which to start searching |
Number | stop | optional index position at which to stop searching |
Returns
Number | the index of the first occurrence of sequence, or -1 |
ByteArray.prototype. lastIndexOf (sequence, start, stop)
Returns the index of the last occurrence of sequence (a Number or a ByteString or ByteArray of any length) or -1 if none was found. If start and/or stop are specified, only elements between the indexes start and stop are searched.
Parameters
Number|Binary | sequence | the number or binary to look for |
Number | start | optional index position at which to start searching |
Number | stop | optional index position at which to stop searching |
Returns
Number | the index of the last occurrence of sequence, or -1 |
ByteArray.prototype. length
The length in bytes. This property is writable. Setting it to a value higher than the current value fills the new slots with 0, setting it to a lower value truncates the byte array.
ByteArray.prototype. map (callback, thisObj)
Returns a new ByteArray whose content is the result of calling the provided function with every element of the original ByteArray.
Example
const ba1 = new ByteArray([0,1,2,3,4,5,6,7,8]);
const ba2 = ba1.map(function(byte) { return 2 * byte; });
console.log(ba2.toArray()); // prints [0, 2, 4, 6, 8, 10, 12, 14, 16]
Parameters
Function | callback | the callback |
Object | thisObj | optional this-object for callback |
Returns
ByteArray | a new ByteArray |
ByteArray.prototype. pop ()
Removes the last element from an array and returns that element.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.pop() === 8; // --> true
Returns
Number |
ByteArray.prototype. push (num...)
Appends the given elements and returns the new length of the array.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.push(16);
console.log(ba.toArray()); // [0, 1, 2, 4, 8, 16]
Parameters
Number... | num... | one or more numbers to append |
Returns
Number | the new length of the ByteArray |
ByteArray.prototype. reduce (callback, initialValue)
Apply a function to each element in this ByteArray from left-to-right as to reduce its content to a single value.
Example
const ba = new ByteArray([0,1,2,3,4,5,6,7,8]);
ba.reduce(function(prev, curr) { return prev + curr; }); // --> 36
Parameters
Function | callback | the function to call with each element of the ByteArray |
Object | initialValue | optional argument to be used as the first argument to the first call to the callback |
Returns
the return value of the last callback invocation |
ByteArray.prototype. reduceRight (callback, initialValue)
Apply a function to each element in this ByteArray starting at the last element as to reduce its content to a single value.
Parameters
Function | callback | the function to call with each element of the ByteArray |
Object | initialValue | optional argument to be used as the first argument to the first call to the callback |
Returns
the return value of the last callback invocation |
ByteArray.prototype. reverse ()
Reverses the content of the ByteArray in-place.
Example
const ba = new ByteArray([0,1,2,3,4,5,6,7,8]);
ba.reverse();
print(ba[0] == 8); // --> true
Returns
ByteArray | this ByteArray with its elements reversed |
ByteArray.prototype. set (offset, value)
Sets the byte at the given offset. set(offset, value)
is
analogous to indexing with brackets [offset]=value
.
Example
const ba = new ByteArray([0,255]);
ba[0] = 64;
print(ba[0]); // prints 64
Parameters
Number | offset | |
Number | value |
ByteArray.prototype. shift ()
Removes the first element from the ByteArray and returns that element. This method changes the length of the ByteArray
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.shift();
console.log(ba.toArray()); // [1, 2, 4, 8]
Returns
Number | the removed first element |
ByteArray.prototype. slice (begin, end)
Returns a new ByteArray containing a portion of this ByteArray.
Parameters
Number | begin | Zero-based index at which to begin extraction. As a negative index, begin indicates an offset from the end of the sequence. |
Number | end | Zero-based index at which to end extraction. slice extracts up to but not including end. As a negative index, end indicates an offset from the end of the sequence. If end is omitted, slice extracts to the end of the sequence. |
Returns
ByteArray | a new ByteArray |
ByteArray.prototype. some (callback, thisObj)
Tests whether some element in the array passes the test implemented by the provided function.
Example
const ba = new ByteArray([0,1,2,3,4,5,6,7,8]);
ba.some(function(byte) { return byte > 10; }); // --> false
ba.some(function(byte) { return byte < 10; }); // --> true
Parameters
Function | callback | the callback function |
Object | thisObj | optional this-object for callback |
Returns
Boolean | true if at least one invocation of callback returns true |
ByteArray.prototype. sort (comparator)
Sorts the content of the ByteArray in-place.
Example
const ba = binary.toByteArray("hello world", "utf-8");
ba.sort();
ba.decodeToString() // --> "dehllloorw"
Parameters
Function | comparator | the function to compare entries |
Returns
ByteArray | this ByteArray with its elements sorted |
ByteArray.prototype. splice (index, howMany, elements...)
Changes the content of the ByteArray, adding new elements while removing old elements.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.splice(2,2);
console.log(ba.toArray()); // [0, 1, 8]
Parameters
Number | index | the index at which to start changing the ByteArray |
Number | howMany | The number of elements to remove at the given position |
Number... | elements... | the new elements to add at the given position |
ByteArray.prototype. split (delimiter, options)
Split at delimiter, which can by a Number, a ByteString, a ByteArray or an Array of the prior (containing multiple delimiters, i.e., "split at any of these delimiters"). Delimiters can have arbitrary size.
Parameters
Number|Binary | delimiter | one or more delimiter items |
Object | options | optional object parameter with the following optional properties:
|
ByteArray.prototype. toArray ()
Returns an array containing the bytes as numbers.
ByteArray.prototype. toByteArray ()
ByteArray.prototype. toByteString ()
ByteArray.prototype. toString ()
Returns a String representation of the ByteArray.
Example
const ba = new ByteArray([0,1,2,4,8]);
console.log(ba.toString()); // prints '[ByteArray 5]'
ByteArray.prototype. unshift (num...)
Adds one or more elements to the beginning of the ByteArray and returns its new length.
Example
const ba = new ByteArray([0,1,2,4,8]);
ba.unshift(-8, -4, -2, -1);
console.log(ba.toArray()); // [248, 252, 254, 255, 0, 1, 2, 4, 8]
Parameters
Number... | num... | one or more numbers to append |
Returns
Number | the new length of the ByteArray |
ByteArray.prototype. unwrap ()
Unwraps the underlying Java byte[]
from ByteArray. It can be
passed to a Java method that expects a byte array.
Returns
byte[] | a native Java byte array |
ByteArray. wrap (bytes)
Create a ByteArray wrapper for a Java byte array without creating a new copy as the ByteArray constructor does. Any changes made on the ByteArray instance will be applied to the original byte array.
Example
// writes a java.security.Key byte[] to a file;
fs.write("id_dsa.pub", ByteArray.wrap(publicKey.getEncoded()));
Parameters
Binary | bytes | a Java byte array or Binary instance |
Returns
ByteArray | a ByteArray wrapping the argument |
ByteString (content, charset)
Constructs an immutable byte string.
If the first argument is a String, the constructor requires a second argument containing the name of the String's encoding. If called without arguments, an empty ByteString is returned.
Parameters
Binary|Array|String | content | the content of the ByteString. |
String | charset | the encoding name if the first argument is a String. |
ByteString.prototype. byteAt (offset)
Returns the byte at the given offset as ByteString.
Parameters
Number | offset |
Returns
ByteString |
ByteString.prototype. charAt (offset)
Returns the byte at the given offset as ByteString.
Parameters
Number | offset |
Returns
ByteString |
ByteString.prototype. charCodeAt (offset)
Returns charcode at the given offset.
Parameters
Number | offset |
Returns
Number |
ByteString.prototype. concat (args...)
Returns a ByteString composed of itself concatenated with the given ByteString, ByteArray, and Array values.
Parameters
Binary...|Array... | args... | one or more elements to concatenate |
Returns
ByteString | a new ByteString |
ByteString.prototype. copy (start, end, target, targetStart)
Copy a range of bytes between start and stop from this ByteString to a target ByteArray at the given targetStart offset.
Parameters
Number | start | |
Number | end | |
ByteArray | target | |
Number | targetStart |
ByteString.prototype. decodeToString (charset)
Returns this ByteString as string, decoded using the given charset.
Parameters
String | charset | the name of the string encoding |
ByteString.prototype. get (offset)
Returns the byte at the given offset as a ByteString. get(offset)
is
analogous to indexing with brackets [offset].
Parameters
Number | offset |
Returns
ByteString |
ByteString.prototype. indexOf (sequence, start, stop)
Returns the index of the first occurrence of sequence (a Number or a ByteString or ByteArray of any length), or -1 if none was found. If start and/or stop are specified, only elements between the indexes start and stop are searched.
Parameters
Number|Binary | sequence | the number or binary to look for |
Number | start | optional index position at which to start searching |
Number | stop | optional index position at which to stop searching |
Returns
Number | the index of the first occurrence of sequence, or -1 |
ByteString.prototype. lastIndexOf (sequence, start, stop)
Returns the index of the last occurrence of sequence (a Number or a ByteString or ByteArray of any length) or -1 if none was found. If start and/or stop are specified, only elements between the indexes start and stop are searched.
Parameters
Number|Binary | sequence | the number or binary to look for |
Number | start | optional index position at which to start searching |
Number | stop | optional index position at which to stop searching |
Returns
Number | the index of the last occurrence of sequence, or -1 |
ByteString.prototype. length
The length in bytes. This property is read-only. Setting it to a value silently fails.
ByteString.prototype. slice (begin, end)
Returns a new ByteString containing a portion of this ByteString.
Parameters
Number | begin | Zero-based index at which to begin extraction. As a negative index, begin indicates an offset from the end of the sequence. |
Number | end | Zero-based index at which to end extraction. slice extracts up to but not including end. As a negative index, end indicates an offset from the end of the sequence. If end is omitted, slice extracts to the end of the sequence. |
Returns
ByteString | a new ByteString |
ByteString.prototype. split (delimiter, options)
Split at delimiter, which can by a Number, a ByteString, a ByteArray or an Array of the prior (containing multiple delimiters, i.e., "split at any of these delimiters"). Delimiters can have arbitrary size.
Parameters
Number|Binary | delimiter | one or more delimiter items |
Object | options | optional object parameter with the following optional properties:
|
ByteString.prototype. toArray ()
Returns an array containing the bytes as numbers.
ByteString.prototype. toByteArray ()
Returns a byte for byte copy of this immutable ByteString as a mutable ByteArray.
Returns
ByteArray |
ByteString.prototype. toByteString ()
Returns this ByteString itself.
ByteString.prototype. toString ()
Returns a debug representation such as "[ByteSTring 10]"
where 10 is the
length of this ByteString.
ByteString.prototype. unwrap ()
Unwraps the underlying Java byte[]
from ByteString. It can be
passed to a Java method that expects a byte array.
Returns
byte[] | a native Java byte array |
ByteString. wrap (bytes)
Create a ByteString wrapper for a Java byte array without creating a new copy as the ByteString constructor does.
Parameters
Binary | bytes | a Java byte array or Binary instance |
Returns
ByteString | a ByteString wrapping the argument |
toByteArray (str, charset)
Converts a String or Binary instance to a mutable ByteArray using the specified encoding.
Example
const binary = require("binary");
const ba = binary.toByteArray("hello world");
Parameters
String|Binary | str | The String or Binary to convert into a ByteArray |
String | charset | the string's encoding. Defaults to 'UTF-8' |
Returns
ByteArray | a ByteArray representing the str |
toByteString (str, charset)
Converts a String or Binary instance to an immutable ByteString using the specified encoding.
Example
const binary = require("binary");
const bs = binary.toByteString("hello world");
Parameters
String|Binary | str | A String or Binary to convert into a ByteString |
String | charset | the string's encoding. Defaults to 'UTF-8' |
Returns
ByteString | a ByteString representing str |