signal-desktop/libtextsecure/helpers.js

72 lines
2.1 KiB
JavaScript
Raw Normal View History

2014-05-17 05:53:58 +00:00
window.textsecure = window.textsecure || {};
2014-01-12 07:32:13 +00:00
/*********************************
*** Type conversion utilities ***
*********************************/
2014-01-15 07:46:05 +00:00
// Strings/arrays
2014-03-06 21:44:59 +00:00
//TODO: Throw all this shit in favor of consistent types
//TODO: Namespace
2014-01-12 14:07:13 +00:00
var StaticByteBufferProto = new dcodeIO.ByteBuffer().__proto__;
2014-01-22 06:23:41 +00:00
var StaticArrayBufferProto = new ArrayBuffer().__proto__;
2014-03-06 18:18:11 +00:00
var StaticUint8ArrayProto = new Uint8Array().__proto__;
2014-01-12 07:32:13 +00:00
function getString(thing) {
if (thing === Object(thing)) {
if (thing.__proto__ == StaticUint8ArrayProto)
return String.fromCharCode.apply(null, thing);
if (thing.__proto__ == StaticArrayBufferProto)
return getString(new Uint8Array(thing));
if (thing.__proto__ == StaticByteBufferProto)
return thing.toString('binary');
}
return thing;
2014-01-12 07:32:13 +00:00
}
2014-03-05 01:31:15 +00:00
function getStringable(thing) {
return (
typeof thing == 'string' ||
typeof thing == 'number' ||
typeof thing == 'boolean' ||
(thing === Object(thing) &&
(thing.__proto__ == StaticArrayBufferProto ||
thing.__proto__ == StaticUint8ArrayProto ||
thing.__proto__ == StaticByteBufferProto))
);
2014-03-05 01:31:15 +00:00
}
// Number formatting utils
window.textsecure.utils = (function() {
var self = {};
self.unencodeNumber = function(number) {
return number.split('.');
};
self.isNumberSane = function(number) {
return number[0] == '+' && /^[0-9]+$/.test(number.substring(1));
};
/**************************
*** JSON'ing Utilities ***
**************************/
function ensureStringed(thing) {
if (getStringable(thing)) return getString(thing);
else if (thing instanceof Array) {
var res = [];
for (var i = 0; i < thing.length; i++) res[i] = ensureStringed(thing[i]);
return res;
} else if (thing === Object(thing)) {
var res = {};
for (var key in thing) res[key] = ensureStringed(thing[key]);
return res;
} else if (thing === null) {
return null;
}
throw new Error('unsure of how to jsonify object of type ' + typeof thing);
}
self.jsonThing = function(thing) {
return JSON.stringify(ensureStringed(thing));
};
2014-05-25 22:45:22 +00:00
return self;
})();