Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Remove dep on commonjs-utils, and add needed modules

  • Loading branch information...
commit 55daf3f85f014d58c944cf6068edf2e6e80488c9 1 parent 016bec5
@kriszyp authored
View
2  jsgi/auth.js
@@ -7,7 +7,7 @@ var AccessError = require("perstore/errors").AccessError,
promiseModule = require("promised-io/promise"),
when = promiseModule.when,
print = require("promised-io/process").print,
- base64 = require("commonjs-utils/base64");
+ base64 = require("../util/base64");
exports.Authentication = function(security, nextApp){
// initialize the user model
View
4 jsgi/cache.js
@@ -2,7 +2,7 @@ var CacheStore = require("perstore/store/cache").Cache,
shash = require("narwhal/sha").hash;
exports.FetchCache= function(cache, nextApp) {
- var config = require("commonjs-utils/settings").cache || {};
+ var config = require("perstore/util/settings").cache || {};
config.alwaysVaryOn = config.alwaysVaryOn || [];
return function(request) {
@@ -67,7 +67,7 @@ exports.FetchCache= function(cache, nextApp) {
exports.UpdateCache = function(cache, nextApp){
- var config = require("commonjs-utils/settings").cache || {};
+ var config = require("perstore/util/settings").cache || {};
config.alwaysVaryOn = config.alwaysVaryOn || [];
return function(request) {
View
1  jsgi/error.js
@@ -7,7 +7,6 @@ var METHOD_HAS_BODY = require("./methods").METHOD_HAS_BODY,
AccessError = require("perstore/errors").AccessError,
MethodNotAllowedError = require("perstore/errors").MethodNotAllowedError,
print = require("promised-io/process").print,
- ErrorConstructor = require("commonjs-utils/extend-error").ErrorConstructor,
when = require("promised-io/promise").when;
exports.ErrorHandler = function(nextApp){
View
2  jsgi/rest-store.js
@@ -8,7 +8,7 @@ var METHOD_HAS_BODY = require("./methods").METHOD_HAS_BODY,
when = promiseModule.when,
resolve = require("perstore/path").resolve,
Response = require("./response").Response,
- settings = require("commonjs-utils/settings");
+ settings = require("perstore/util/settings");
function dir(){var sys=require('sys');for(var i=0,l=arguments.length;i<l;i++)sys.debug(sys.inspect(arguments[i]));}
exports.RestStore = function(options){
View
4 jsgi/session.js
@@ -7,9 +7,9 @@
*/
var promiseModule = require("promised-io/promise"),
when = promiseModule.when,
- settings = require("commonjs-utils/settings"),
+ settings = require("perstore/util/settings"),
sessionModel,
- sha1 = require("commonjs-utils/sha1").hex_sha1;
+ sha1 = require("../util/sha1").hex_sha1;
exports.Session = function(options, nextApp){
// assign defaults
View
2  media/atom.js
@@ -21,7 +21,7 @@ Media({
}
write('<link rel="alternate" type="text/html" href="' + (qs.length > 1 && qs || '') + '"/>\n');
if(typeof object.forEach === "function") {
- var range = require("commonjs-utils/jsgi/parse-header")["content-range"](response.headers["content-range"], 25);
+ var range = require("../util/parse-header")["content-range"](response.headers["content-range"], 25);
// TODO escape entities, especially in qs
if (range.prev) {
var prevRange = [range.prev.start, range.prev.end].join("-");
View
2  media/hatom.js
@@ -28,7 +28,7 @@ Media({
}
if (typeof object.forEach === "function") {
var headers = object.getMetadata && object.getMetadata() || {},
- range = require("commonjs-utils/jsgi/parse-header")["content-range"](headers["content-range"], 25);
+ range = require("../util/parse-header")["content-range"](headers["content-range"], 25);
if (range && range.prev) {
var prevRange = [range.prev.start, range.prev.end].join("-");
write('<div id="prevLink"><a rel="prev" href="' + qs + '&http-range=items%3d' + prevRange + '">Previous</a></div>')
View
4 media/html.js
@@ -7,9 +7,9 @@ var Media = require("../media").Media,
transform = require("../html-transform"),
Response=require("../jsgi/response").Response,
resolver = require("templify/lib/templify").Resolver,
- toJSON = require("commonjs-utils/json-ext").stringify,
+ toJSON = require("perstore/util/json-ext").stringify,
when = require("promised-io/promise").when,
- copy = require("commonjs-utils/copy").copy;
+ copy = require("perstore/util/copy").copy;
var templateEngine = require('templify/lib/templify').TemplateEngine({resolver: resolver, store: filesystem});
var defaultHandler = {
View
2  media/javascript.js
@@ -1,7 +1,7 @@
/**
* Registers JavaScript media type handling
*/
-var JSONExt = require("commonjs-utils/json-ext"),
+var JSONExt = require("perstore/util/json-ext"),
StreamingSerializer = require("./json").StreamingSerializer,
when = require("promised-io/promise").when,
Media = require("../media").Media,
View
2  media/json.js
@@ -1,7 +1,7 @@
/**
* Registers JSON media type handling
*/
-var JSONExt = require("commonjs-utils/json-ext"),
+var JSONExt = require("perstore/util/json-ext"),
Media = require("../media").Media,
when = require("promised-io/promise").when,
forEachableToString = require("../media").forEachableToString;
View
2  media/message/json.js
@@ -2,7 +2,7 @@
* Registers message/json media handler. This is used for sending and receiving multiple
* requests/responses/messages, and is very useful for bulk updates and Comet
*/
-var JSONExt = require("commonjs-utils/json-ext"),
+var JSONExt = require("perstore/util/json-ext"),
Media = require("../../media").Media,
all = require("promised-io/promise").all,
when = require("promised-io/promise").when,
View
2  media/plain.js
@@ -6,7 +6,7 @@ var Media = require("../media").Media,
when = require("promised-io/promise").when,
getColumnsToExport = require("../media").getColumnsToExport,
print = require("promised-io/process").print,
- JSONExt = require("commonjs-utils/json-ext");
+ JSONExt = require("perstore/util/json-ext");
Media({
mediaType: "text/plain",
View
2  media/url-encoded.js
@@ -1,7 +1,7 @@
/**
* Registers URLEncoded media type handling
*/
-var JSONExt = require("commonjs-utils/json-ext"),
+var JSONExt = require("perstore/util/json-ext"),
stringToValue = require("./auto-type").stringToValue,
print = require("promised-io/process").print,
when = require("promised-io/promise").when,
View
1  package.json
@@ -15,7 +15,6 @@
"mappings":{
"perstore": "http://github.com/kriszyp/perstore/zipball/v0.2.4",
"templify": "http://github.com/dmachi/templify/zipball/master",
- "commonjs-utils": "http://github.com/kriszyp/commonjs-utils/zipball/v0.2.2",
"promised-io": "jar:http://github.com/kriszyp/promised-io/zipball/v0.2.3!/",
"patr": "jar:http://github.com/kriszyp/patr/zipball/v0.2.6!/",
"tunguska": "http://github.com/kriszyp/tunguska/zipball/v0.2.4",
View
4 security.js
@@ -7,8 +7,8 @@ var AccessError = require("perstore/errors").AccessError,
when = require("promised-io/promise").when,
getCurrentSession = require("./jsgi/session").getCurrentSession,
Restrictive = require("perstore/facet").Restrictive,
- sha1 = require("commonjs-utils/sha1").b64_sha1,
- settings = require("commonjs-utils/settings");
+ sha1 = require("./util/sha1").b64_sha1,
+ settings = require("perstore/util/settings");
try{
var uuid = require("uuid");
View
6 start-node.js
@@ -1,5 +1,5 @@
// helpful for debugging
-var settings = require("commonjs-utils/settings"),
+var settings = require("perstore/util/settings"),
ws = require("node-websocket-server"),
messageJson = require("./media/message/json");
@@ -22,7 +22,7 @@ exports.start = function(jsgiApp, socketApp){
console.log("Listening on port " + port);
// having a REPL is really helpful
-// if(nodes.isMaster){
+ if (require.main === module) {
require("./util/repl").start();
- //}
+ }
};
View
4 tests/rest.js
@@ -1,9 +1,9 @@
-require("commonjs-utils/settings").admins = ["user"];// must do this first
+require("perstore/util/settings").admins = ["user"];// must do this first
var MockRequest = require("jack/mock").MockRequest,
mock = new MockRequest(require("pintura").app),
assert = require("assert"),
TestStore = require("perstore/stores").DefaultStore();
- parse = require("commonjs-utils/json-ext").parse;
+ parse = require("perstore/util/json-ext").parse;
TestStore.setPath("TestStore");
require("pintura").config.getDataModel = function(){
return {
View
4 tests/stack.js
@@ -1,10 +1,10 @@
-require("commonjs-utils/settings").admins = ["user"];// must do this first
+require("perstore/util/settings").admins = ["user"];// must do this first
var MockRequest = require("jack/mock").MockRequest,
mock = new MockRequest(require("pintura").app),
assert = require("assert"),
TestStore = require("perstore/stores").DefaultStore();
var config = require("pintura").config;
- var parse = require("commonjs-utils/json-ext").parse;
+ var parse = require("perstore/util/json-ext").parse;
TestStore.setPath("TestStore");
View
101 util/base64.js
@@ -0,0 +1,101 @@
+/* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
+ * Version: 1.0
+ * LastModified: Dec 25 1999
+ * This library is free. You can redistribute it and/or modify it.
+ */
+
+
+var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+var base64DecodeChars = new Array(
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
+ -1, 0, 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, -1, -1, -1, -1, -1,
+ -1, 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, -1, -1, -1, -1, -1);
+
+exports.encode = function(str) {
+ var out, i, len;
+ var c1, c2, c3;
+
+ len = str.length;
+ i = 0;
+ out = "";
+ while(i < len) {
+ c1 = str.charCodeAt(i++) & 0xff;
+ if(i == len)
+ {
+ out += base64EncodeChars.charAt(c1 >> 2);
+ out += base64EncodeChars.charAt((c1 & 0x3) << 4);
+ out += "==";
+ break;
+ }
+ c2 = str.charCodeAt(i++);
+ if(i == len)
+ {
+ out += base64EncodeChars.charAt(c1 >> 2);
+ out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
+ out += base64EncodeChars.charAt((c2 & 0xF) << 2);
+ out += "=";
+ break;
+ }
+ c3 = str.charCodeAt(i++);
+ out += base64EncodeChars.charAt(c1 >> 2);
+ out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
+ out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
+ out += base64EncodeChars.charAt(c3 & 0x3F);
+ }
+ return out;
+}
+
+exports.decode = function(str) {
+ var c1, c2, c3, c4;
+ var i, len, out;
+
+ len = str.length;
+ i = 0;
+ out = "";
+ while(i < len) {
+ /* c1 */
+ do {
+ c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
+ } while(i < len && c1 == -1);
+ if(c1 == -1)
+ break;
+
+ /* c2 */
+ do {
+ c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
+ } while(i < len && c2 == -1);
+ if(c2 == -1)
+ break;
+
+ out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
+
+ /* c3 */
+ do {
+ c3 = str.charCodeAt(i++) & 0xff;
+ if(c3 == 61)
+ return out;
+ c3 = base64DecodeChars[c3];
+ } while(i < len && c3 == -1);
+ if(c3 == -1)
+ break;
+
+ out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
+
+ /* c4 */
+ do {
+ c4 = str.charCodeAt(i++) & 0xff;
+ if(c4 == 61)
+ return out;
+ c4 = base64DecodeChars[c4];
+ } while(i < len && c4 == -1);
+ if(c4 == -1)
+ break;
+ out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
+ }
+ return out;
+}
View
134 util/json.js
@@ -0,0 +1,134 @@
+/**
+ * This is a port of Dojo's JSON module
+ */
+(function(define){
+define(function(require, exports){
+if(typeof JSON === "undefined"){
+exports.parse = function(/*String*/ json){
+ // summary:
+ // Parses a [JSON](http://json.org) string to return a JavaScript object.
+ // description:
+ // Throws for invalid JSON strings, but it does not use a strict JSON parser. It
+ // delegates to eval().
+ // json:
+ // a string literal of a JSON item, for instance:
+ // `'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'`
+
+ return eval("(" + json + ")"); // Object
+}
+
+function escapeString(/*String*/str){
+ //summary:
+ // Adds escape sequences for non-visual characters, double quote and
+ // backslash and surrounds with double quotes to form a valid string
+ // literal.
+ return ('"' + str.replace(/(["\\])/g, '\\$1') + '"').
+ replace(/[\f]/g, "\\f").replace(/[\b]/g, "\\b").replace(/[\n]/g, "\\n").
+ replace(/[\t]/g, "\\t").replace(/[\r]/g, "\\r"); // string
+}
+
+exports.toJsonIndentStr = "\t";
+exports.stringify = function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*String?*/ _indentStr){
+ // summary:
+ // Returns a [JSON](http://json.org) serialization of an object.
+ // description:
+ // Returns a [JSON](http://json.org) serialization of an object.
+ // Note that this doesn't check for infinite recursion, so don't do that!
+ // it:
+ // an object to be serialized. Objects may define their own
+ // serialization via a special "__json__" or "json" function
+ // property. If a specialized serializer has been defined, it will
+ // be used as a fallback.
+ // prettyPrint:
+ // if true, we indent objects and arrays to make the output prettier.
+ // The variable `toJsonIndentStr` is used as the indent string --
+ // to use something other than the default (tab), change that variable
+ // before calling stringify().
+ // _indentStr:
+ // private variable for recursive calls when pretty printing, do not use.
+ // example:
+ // simple serialization of a trivial object
+ // | var jsonStr = require("commonjs-utils/json").stringify({ howdy: "stranger!", isStrange: true });
+
+ if(it === undefined){
+ return "undefined";
+ }
+ var objtype = typeof it;
+ if(objtype == "number" || objtype == "boolean"){
+ return it + "";
+ }
+ if(it === null){
+ return "null";
+ }
+ if(typeof it == "string"){
+ return escapeString(it);
+ }
+ // recurse
+ var recurse = arguments.callee;
+ // short-circuit for objects that support "json" serialization
+ // if they return "self" then just pass-through...
+ var newObj;
+ _indentStr = _indentStr || "";
+ var nextIndent = prettyPrint ? _indentStr + exports.toJsonIndentStr : "";
+ var tf = it.__json__||it.json;
+ if(typeof tf == "function"){
+ newObj = tf.call(it);
+ if(it !== newObj){
+ return recurse(newObj, prettyPrint, nextIndent);
+ }
+ }
+ if(it.nodeType && it.cloneNode){ // isNode
+ // we can't seriailize DOM nodes as regular objects because they have cycles
+ // DOM nodes could be serialized with something like outerHTML, but
+ // that can be provided by users in the form of .json or .__json__ function.
+ throw new Error("Can't serialize DOM nodes");
+ }
+
+ var sep = prettyPrint ? " " : "";
+ var newLine = prettyPrint ? "\n" : "";
+
+ // array
+ if(it instanceof Array){
+ var res = [];
+ for(var i = 0, l = it.length; i < l; i++){
+ var val = recurse(it[i], prettyPrint, nextIndent);
+ if(typeof val != "string"){
+ val = "undefined";
+ }
+ res.push(newLine + nextIndent + val);
+ }
+ return "[" + res.join("," + sep) + newLine + _indentStr + "]";
+ }
+ if(objtype == "function"){
+ return null; // null
+ }
+ // generic object code path
+ var output = [], key;
+ for(key in it){
+ var keyStr, val;
+ if(typeof key == "number"){
+ keyStr = '"' + key + '"';
+ }else if(typeof key == "string"){
+ keyStr = escapeString(key);
+ }else{
+ // skip non-string or number keys
+ continue;
+ }
+ val = recurse(it[key], prettyPrint, nextIndent);
+ if(typeof val != "string"){
+ // skip non-serializable values
+ continue;
+ }
+ // FIXME: use += on Moz!!
+ // MOW NOTE: using += is a pain because you have to account for the dangling comma...
+ output.push(newLine + nextIndent + keyStr + ":" + sep + val);
+ }
+ return "{" + output.join("," + sep) + newLine + _indentStr + "}"; // String
+}
+}
+else{
+ exports.parse = JSON.parse;
+ exports.stringify = JSON.stringify;
+}
+});
+})(typeof define == "undefined" ? function(factory){factory(require, exports);} : define);
View
28 util/parse-header.js
@@ -0,0 +1,28 @@
+/**
+ * Provides parsers for various HTTP headers
+ */
+
+exports["content-range"] = function(contentRange, pageSize) {
+ if (!contentRange) return;
+ var parts = contentRange.match(/(\d+)\-(\d+)\/(\d+)/);
+ if (!parts) return;
+ var r = {};
+ r.start = parseInt(parts[1], 10);
+ r.end = parseInt(parts[2], 10);
+ r.total = parseInt(parts[3], 10);
+
+ if (!pageSize) return r;
+ if (r.start) {
+ r.prev = {};
+ r.prev.start = r.start - pageSize;
+ if (r.prev.start < 0) r.prev.start = 0;
+ r.prev.end = r.start - 1;
+ }
+ if (r.total - r.end > 1) {
+ r.next = {};
+ r.next.start = r.end + 1;
+ r.next.end = r.end + pageSize;
+ if (r.next.end >= r.total) r.next.end = r.total - 1;
+ }
+ return r;
+};
View
2  util/repl.js
@@ -1,4 +1,4 @@
-var settings = require("commonjs-utils/settings");
+var settings = require("perstore/util/settings");
exports.start = function(context){
if (!context) context = {require: require};
View
330 util/sha1.js
@@ -0,0 +1,330 @@
+/*
+ * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
+ * in FIPS 180-1
+ * Version 2.2 Copyright Paul Johnston 2000 - 2009.
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
+ * Distributed under the BSD License
+ * See http://pajhome.org.uk/crypt/md5 for details.
+ */
+
+/*
+ * Configurable variables. You may need to tweak these to be compatible with
+ * the server-side, but the defaults work in most cases.
+ */
+var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
+var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
+
+/*
+ * These are the functions you'll usually want to call
+ * They take string arguments and return either hex or base-64 encoded strings
+ */
+exports.hex_sha1 = function(s) { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); }
+exports.b64_sha1 = function(s) { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }
+exports.any_sha1 = function (s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }
+exports.hex_hmac_sha1 = function (k, d)
+ { return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
+exports.b64_hmac_sha1 = function(k, d)
+ { return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
+exports.any_hmac_sha1 = function(k, d, e)
+ { return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
+
+/*
+ * Perform a simple self-test to see if the VM is working
+ */
+function sha1_vm_test()
+{
+ return hex_sha1("abc").toLowerCase() == "a9993e364706816aba3e25717850c26c9cd0d89d";
+}
+
+/*
+ * Calculate the SHA1 of a raw string
+ */
+function rstr_sha1(s)
+{
+ return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));
+}
+
+/*
+ * Calculate the HMAC-SHA1 of a key and some data (raw strings)
+ */
+function rstr_hmac_sha1(key, data)
+{
+ var bkey = rstr2binb(key);
+ if(bkey.length > 16) bkey = binb_sha1(bkey, key.length * 8);
+
+ var ipad = Array(16), opad = Array(16);
+ for(var i = 0; i < 16; i++)
+ {
+ ipad[i] = bkey[i] ^ 0x36363636;
+ opad[i] = bkey[i] ^ 0x5C5C5C5C;
+ }
+
+ var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
+ return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160));
+}
+
+/*
+ * Convert a raw string to a hex string
+ */
+function rstr2hex(input)
+{
+ try { hexcase } catch(e) { hexcase=0; }
+ var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
+ var output = "";
+ var x;
+ for(var i = 0; i < input.length; i++)
+ {
+ x = input.charCodeAt(i);
+ output += hex_tab.charAt((x >>> 4) & 0x0F)
+ + hex_tab.charAt( x & 0x0F);
+ }
+ return output;
+}
+
+/*
+ * Convert a raw string to a base-64 string
+ */
+function rstr2b64(input)
+{
+ try { b64pad } catch(e) { b64pad=''; }
+ var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ var output = "";
+ var len = input.length;
+ for(var i = 0; i < len; i += 3)
+ {
+ var triplet = (input.charCodeAt(i) << 16)
+ | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
+ | (i + 2 < len ? input.charCodeAt(i+2) : 0);
+ for(var j = 0; j < 4; j++)
+ {
+ if(i * 8 + j * 6 > input.length * 8) output += b64pad;
+ else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
+ }
+ }
+ return output;
+}
+
+/*
+ * Convert a raw string to an arbitrary string encoding
+ */
+function rstr2any(input, encoding)
+{
+ var divisor = encoding.length;
+ var remainders = Array();
+ var i, q, x, quotient;
+
+ /* Convert to an array of 16-bit big-endian values, forming the dividend */
+ var dividend = Array(Math.ceil(input.length / 2));
+ for(i = 0; i < dividend.length; i++)
+ {
+ dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
+ }
+
+ /*
+ * Repeatedly perform a long division. The binary array forms the dividend,
+ * the length of the encoding is the divisor. Once computed, the quotient
+ * forms the dividend for the next step. We stop when the dividend is zero.
+ * All remainders are stored for later use.
+ */
+ while(dividend.length > 0)
+ {
+ quotient = Array();
+ x = 0;
+ for(i = 0; i < dividend.length; i++)
+ {
+ x = (x << 16) + dividend[i];
+ q = Math.floor(x / divisor);
+ x -= q * divisor;
+ if(quotient.length > 0 || q > 0)
+ quotient[quotient.length] = q;
+ }
+ remainders[remainders.length] = x;
+ dividend = quotient;
+ }
+
+ /* Convert the remainders to the output string */
+ var output = "";
+ for(i = remainders.length - 1; i >= 0; i--)
+ output += encoding.charAt(remainders[i]);
+
+ /* Append leading zero equivalents */
+ var full_length = Math.ceil(input.length * 8 /
+ (Math.log(encoding.length) / Math.log(2)))
+ for(i = output.length; i < full_length; i++)
+ output = encoding[0] + output;
+
+ return output;
+}
+
+/*
+ * Encode a string as utf-8.
+ * For efficiency, this assumes the input is valid utf-16.
+ */
+function str2rstr_utf8(input)
+{
+ var output = "";
+ var i = -1;
+ var x, y;
+
+ while(++i < input.length)
+ {
+ /* Decode utf-16 surrogate pairs */
+ x = input.charCodeAt(i);
+ y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
+ if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
+ {
+ x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
+ i++;
+ }
+
+ /* Encode output as utf-8 */
+ if(x <= 0x7F)
+ output += String.fromCharCode(x);
+ else if(x <= 0x7FF)
+ output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
+ 0x80 | ( x & 0x3F));
+ else if(x <= 0xFFFF)
+ output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
+ 0x80 | ((x >>> 6 ) & 0x3F),
+ 0x80 | ( x & 0x3F));
+ else if(x <= 0x1FFFFF)
+ output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
+ 0x80 | ((x >>> 12) & 0x3F),
+ 0x80 | ((x >>> 6 ) & 0x3F),
+ 0x80 | ( x & 0x3F));
+ }
+ return output;
+}
+
+/*
+ * Encode a string as utf-16
+ */
+function str2rstr_utf16le(input)
+{
+ var output = "";
+ for(var i = 0; i < input.length; i++)
+ output += String.fromCharCode( input.charCodeAt(i) & 0xFF,
+ (input.charCodeAt(i) >>> 8) & 0xFF);
+ return output;
+}
+
+function str2rstr_utf16be(input)
+{
+ var output = "";
+ for(var i = 0; i < input.length; i++)
+ output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
+ input.charCodeAt(i) & 0xFF);
+ return output;
+}
+
+/*
+ * Convert a raw string to an array of big-endian words
+ * Characters >255 have their high-byte silently ignored.
+ */
+function rstr2binb(input)
+{
+ var output = Array(input.length >> 2);
+ for(var i = 0; i < output.length; i++)
+ output[i] = 0;
+ for(var i = 0; i < input.length * 8; i += 8)
+ output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
+ return output;
+}
+
+/*
+ * Convert an array of big-endian words to a string
+ */
+function binb2rstr(input)
+{
+ var output = "";
+ for(var i = 0; i < input.length * 32; i += 8)
+ output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
+ return output;
+}
+
+/*
+ * Calculate the SHA-1 of an array of big-endian words, and a bit length
+ */
+function binb_sha1(x, len)
+{
+ /* append padding */
+ x[len >> 5] |= 0x80 << (24 - len % 32);
+ x[((len + 64 >> 9) << 4) + 15] = len;
+
+ var w = Array(80);
+ var a = 1732584193;
+ var b = -271733879;
+ var c = -1732584194;
+ var d = 271733878;
+ var e = -1009589776;
+
+ for(var i = 0; i < x.length; i += 16)
+ {
+ var olda = a;
+ var oldb = b;
+ var oldc = c;
+ var oldd = d;
+ var olde = e;
+
+ for(var j = 0; j < 80; j++)
+ {
+ if(j < 16) w[j] = x[i + j];
+ else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
+ var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),
+ safe_add(safe_add(e, w[j]), sha1_kt(j)));
+ e = d;
+ d = c;
+ c = bit_rol(b, 30);
+ b = a;
+ a = t;
+ }
+
+ a = safe_add(a, olda);
+ b = safe_add(b, oldb);
+ c = safe_add(c, oldc);
+ d = safe_add(d, oldd);
+ e = safe_add(e, olde);
+ }
+ return Array(a, b, c, d, e);
+
+}
+
+/*
+ * Perform the appropriate triplet combination function for the current
+ * iteration
+ */
+function sha1_ft(t, b, c, d)
+{
+ if(t < 20) return (b & c) | ((~b) & d);
+ if(t < 40) return b ^ c ^ d;
+ if(t < 60) return (b & c) | (b & d) | (c & d);
+ return b ^ c ^ d;
+}
+
+/*
+ * Determine the appropriate additive constant for the current iteration
+ */
+function sha1_kt(t)
+{
+ return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
+ (t < 60) ? -1894007588 : -899497514;
+}
+
+/*
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
+ * to work around bugs in some JS interpreters.
+ */
+function safe_add(x, y)
+{
+ var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+ var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+ return (msw << 16) | (lsw & 0xFFFF);
+}
+
+/*
+ * Bitwise rotate a 32-bit number to the left.
+ */
+function bit_rol(num, cnt)
+{
+ return (num << cnt) | (num >>> (32 - cnt));
+}
Please sign in to comment.
Something went wrong with that request. Please try again.