Binary/C/Level 1

From CommonJS Spec Wiki
< Binary‎ | C
Jump to: navigation, search
// -*- coding: UTF-8 -*-
/**
 * CommonJS Binary/C (Level 1) supplementary library
 */
 
Blob.fromCode =
Blob.fromByteCode = function(code) {
  if(typeof code === "number")
    throw new TypeError("Byte codes must be numbers");
  return new Blob(code);
};
Blob.prototype.contentConstructor = Blob;
Blob.prototype.codeAt = Blob.prototype.byteCodeAt;
Blob.prototype.byteAt =
Blob.prototype.valueAt = function(index) {
  return Blob(this.byteCodeAt(index));
};
Blob.prototype.split = function split(separator, limit) {
  if ( typeof limit !== "number" )
    limit = Infinity;
  // @todo
};
Blob.prototype.toBlob = function toBlob(fromCharset, toCharset) {
  if ( arguments.length === 0 )
    return this;
  if ( arguments.length === 1 )
    throw new TypeError("blob.toBlob passed with one argument. blob.toBlob was likely confused with string.toBlob");
  return require('encodings').convert(fromCharset, toCharset, this);
};
Blob.prototype.toString = function toString(fromCharset) {
  if ( arguments.length === 0 )
    return "[Blob length=" + this.length + "]";
  return require('encodings').convertToString(fromCharset, this);
};
Blob.prototype.toArray = function toArray(fromCharset) {
  if ( fromCharset )
    var str = this.toString(fromCharset);
    var arr = new Array(this.length);
    for(var i = 0, l = str.length; i<l; ++i)
      arr[i] = str.charCodeAt(i);
    return arr;
  } else {
    var arr = new Array(this.length);
    for(var i = 0, l = this.length; i<l; ++i)
      arr[i] = this.byteCodeAt(i);
    return arr;
  }
};
Blob.prototype.toSource = function toSource() {
  return "(new Blob(["+this.toArray().join(', ')+"]))";
};
 
StringBuffer.prototype.contentConstructor = String;
BlobBuffer.prototype.contentConstructor = Blob;
Buffer.prototype.valueAt = function(index) {
  return this.contentConstructor.fromCode(this.codeAt(index));
};
Buffer.prototype.append = function append(data) {
  this.insert(data, Infinity);
};
Buffer.prototype.insert = function insert(data, index) {
  this.splice(index, 0, data);
};
Buffer.prototype.clear = function clear(start, length) {
  this.fill(start, length, this.contentConstructor.fromCode(0));
};
Buffer.prototype.fill = function fill(start, length, seq) {
  // @todo
};
Buffer.prototype.replace = function remove(data, offset) {
  // @todo
};
Buffer.prototype.remove = function remove(offset, length) {
  return this.splice(offset, length);
};
Buffer.prototype.split = function split(separator, limit) {
  // @todo
};
 
String.fromCode = String.fromCharCode;
String.prototype.contentConstructor = String;
String.prototype.toBlob = function toBlob(toCharset) {
  return require('encodings').convertFromString(toCharset, this.valueOf());
};
String.prototype.valueAt = String.prototype.charAt;
String.prototype.codeAt = String.prototype.charCodeAt;