1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 import { Log } from "resource://gre/modules/Log.sys.mjs";
7 export var CommonUtils = {
9 * Set manipulation methods. These should be lifted into toolkit, or added to
14 * Return elements of `a` or `b`.
25 * Return elements of `a` that are not present in `b`.
36 * Return elements of `a` that are also in `b`.
49 * Return true if `a` and `b` are the same size, and
50 * every element of `a` is in `b`.
53 if (a.size != b.size) {
65 * Checks elements in two arrays for equality, as determined by the `===`
66 * operator. This function does not perform a deep comparison; see Sync's
67 * `Util.deepEquals` for that.
70 if (a.length !== b.length) {
73 for (let i = 0; i < a.length; i++) {
82 * Encode byte string as base64URL (RFC 4648).
85 * (string) Raw byte string to encode.
87 * (bool) Whether to include padding characters (=). Defaults
88 * to true for historical reasons.
90 encodeBase64URL: function encodeBase64URL(bytes, pad = true) {
91 let s = btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_");
94 return s.replace(/=+$/, "");
101 * Create a nsIURI instance from a string.
103 makeURI: function makeURI(URIString) {
108 return Services.io.newURI(URIString);
110 let log = Log.repository.getLogger("Common.Utils");
111 log.debug("Could not create URI", e);
117 * Execute a function on the next event loop tick.
120 * Function to invoke.
121 * @param thisObj [optional]
122 * Object to bind the callback to.
124 nextTick: function nextTick(callback, thisObj) {
126 callback = callback.bind(thisObj);
128 Services.tm.dispatchToMainThread(callback);
132 * Return a timer that is scheduled to call the callback after waiting the
133 * provided time or as soon as possible. The timer will be set as a property
134 * of the provided object with the given timer name.
136 namedTimer: function namedTimer(callback, wait, thisObj, name) {
137 if (!thisObj || !name) {
139 "You must provide both an object and a property name for the timer!"
143 // Delay an existing timer if it exists
144 if (name in thisObj && thisObj[name] instanceof Ci.nsITimer) {
145 thisObj[name].delay = wait;
146 return thisObj[name];
149 // Create a special timer that we can add extra properties
150 let timer = Object.create(
151 Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer)
154 // Provide an easy way to clear out the timer
155 timer.clear = function () {
156 thisObj[name] = null;
160 // Initialize the timer with a smart callback
161 timer.initWithCallback(
163 notify: function notify() {
164 // Clear out the timer once it's been triggered
166 callback.call(thisObj, timer);
173 return (thisObj[name] = timer);
176 encodeUTF8: function encodeUTF8(str) {
178 str = this._utf8Converter.ConvertFromUnicode(str);
179 return str + this._utf8Converter.Finish();
185 decodeUTF8: function decodeUTF8(str) {
187 str = this._utf8Converter.ConvertToUnicode(str);
188 return str + this._utf8Converter.Finish();
194 byteArrayToString: function byteArrayToString(bytes) {
195 return bytes.map(byte => String.fromCharCode(byte)).join("");
198 stringToByteArray: function stringToByteArray(bytesString) {
199 return Array.prototype.slice.call(bytesString).map(c => c.charCodeAt(0));
202 // A lot of Util methods work with byte strings instead of ArrayBuffers.
203 // A patch should address this problem, but in the meantime let's provide
204 // helpers method to convert byte strings to Uint8Array.
205 byteStringToArrayBuffer(byteString) {
206 if (byteString === undefined) {
207 return new Uint8Array();
209 const bytes = new Uint8Array(byteString.length);
210 for (let i = 0; i < byteString.length; ++i) {
211 bytes[i] = byteString.charCodeAt(i) & 0xff;
216 arrayBufferToByteString(buffer) {
217 return CommonUtils.byteArrayToString([...buffer]);
220 bufferToHex(buffer) {
221 return Array.prototype.map
222 .call(buffer, x => ("00" + x.toString(16)).slice(-2))
226 bytesAsHex: function bytesAsHex(bytes) {
228 for (let i = 0, len = bytes.length; i < len; i++) {
229 let c = (bytes[i].charCodeAt(0) & 0xff).toString(16);
238 stringAsHex: function stringAsHex(str) {
239 return CommonUtils.bytesAsHex(CommonUtils.encodeUTF8(str));
242 stringToBytes: function stringToBytes(str) {
243 return CommonUtils.hexToBytes(CommonUtils.stringAsHex(str));
246 hexToBytes: function hexToBytes(str) {
248 for (let i = 0; i < str.length - 1; i += 2) {
249 bytes.push(parseInt(str.substr(i, 2), 16));
251 return String.fromCharCode.apply(String, bytes);
254 hexToArrayBuffer(str) {
255 const octString = CommonUtils.hexToBytes(str);
256 return CommonUtils.byteStringToArrayBuffer(octString);
259 hexAsString: function hexAsString(hex) {
260 return CommonUtils.decodeUTF8(CommonUtils.hexToBytes(hex));
263 base64urlToHex(b64str) {
264 return CommonUtils.bufferToHex(
265 new Uint8Array(ChromeUtils.base64URLDecode(b64str, { padding: "reject" }))
270 * Base32 encode (RFC 4648) a string
272 encodeBase32: function encodeBase32(bytes) {
273 const key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
274 let leftover = bytes.length % 5;
276 // Pad the last quantum with zeros so the length is a multiple of 5.
278 for (let i = leftover; i < 5; i++) {
283 // Chop the string into quanta of 5 bytes (40 bits). Each quantum
284 // is turned into 8 characters from the 32 character base.
286 for (let i = 0; i < bytes.length; i += 5) {
287 let c = Array.prototype.slice
288 .call(bytes.slice(i, i + 5))
289 .map(byte => byte.charCodeAt(0));
292 key[((c[0] << 2) & 0x1f) | (c[1] >> 6)] +
293 key[(c[1] >> 1) & 0x1f] +
294 key[((c[1] << 4) & 0x1f) | (c[2] >> 4)] +
295 key[((c[2] << 1) & 0x1f) | (c[3] >> 7)] +
296 key[(c[3] >> 2) & 0x1f] +
297 key[((c[3] << 3) & 0x1f) | (c[4] >> 5)] +
303 return ret.slice(0, -6) + "======";
305 return ret.slice(0, -4) + "====";
307 return ret.slice(0, -3) + "===";
309 return ret.slice(0, -1) + "=";
316 * Base32 decode (RFC 4648) a string.
318 decodeBase32: function decodeBase32(str) {
319 const key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
321 let padChar = str.indexOf("=");
322 let chars = padChar == -1 ? str.length : padChar;
323 let bytes = Math.floor((chars * 5) / 8);
324 let blocks = Math.ceil(chars / 8);
326 // Process a chunk of 5 bytes / 8 characters.
327 // The processing of this is known in advance,
328 // so avoid arithmetic!
329 function processBlock(ret, cOffset, rOffset) {
332 // N.B., this relies on
333 // undefined | foo == foo.
334 function accumulate(val) {
340 if (!c || c == "" || c == "=") {
341 // Easier than range checking.
342 throw new Error("Done");
343 } // Will be caught far away.
344 val = key.indexOf(c);
346 throw new Error(`Unknown character in base32: ${c}`);
350 // Handle a left shift, restricted to bytes.
351 function left(octet, shift) {
352 return (octet << shift) & 0xff;
356 accumulate(left(val, 3));
358 accumulate(val >> 2);
360 accumulate(left(val, 6));
362 accumulate(left(val, 1));
364 accumulate(val >> 4);
366 accumulate(left(val, 4));
368 accumulate(val >> 1);
370 accumulate(left(val, 7));
372 accumulate(left(val, 2));
374 accumulate(val >> 3);
376 accumulate(left(val, 5));
382 // Our output. Define to be explicit (and maybe the compiler will be smart).
383 let ret = new Array(bytes);
388 for (; i < blocks; ++i) {
390 processBlock(ret, cOff, rOff);
392 // Handle the detection of padding.
393 if (ex.message == "Done") {
402 // Slice in case our shift overflowed to the right.
403 return CommonUtils.byteArrayToString(ret.slice(0, bytes));
407 * Trim excess padding from a Base64 string and atob().
409 * See bug 562431 comment 4.
411 safeAtoB: function safeAtoB(b64) {
412 let len = b64.length;
414 return over ? atob(b64.substr(0, len - over)) : atob(b64);
418 * Ensure that the specified value is defined in integer milliseconds since
421 * This throws an error if the value is not an integer, is negative, or looks
422 * like seconds, not milliseconds.
424 * If the value is null or 0, no exception is raised.
429 ensureMillisecondsTimestamp: function ensureMillisecondsTimestamp(value) {
434 if (!/^[0-9]+$/.test(value)) {
435 throw new Error("Timestamp value is not a positive integer: " + value);
438 let intValue = parseInt(value, 10);
444 // Catch what looks like seconds, not milliseconds.
445 if (intValue < 10000000000) {
446 throw new Error("Timestamp appears to be in seconds: " + intValue);
451 * Read bytes from an nsIInputStream into a string.
454 * (nsIInputStream) Stream to read from.
456 * (number) Integer number of bytes to read. If not defined, or
457 * 0, all available input is read.
459 readBytesFromInputStream: function readBytesFromInputStream(stream, count) {
460 let BinaryInputStream = Components.Constructor(
461 "@mozilla.org/binaryinputstream;1",
462 "nsIBinaryInputStream",
466 count = stream.available();
469 return new BinaryInputStream(stream).readBytes(count);
473 * Generate a new UUID using nsIUUIDGenerator.
475 * Example value: "1e00a2e2-1570-443e-bf5e-000354124234"
477 * @return string A hex-formatted UUID string.
479 generateUUID: function generateUUID() {
480 let uuid = Services.uuid.generateUUID().toString();
482 return uuid.substring(1, uuid.length - 1);
486 * Obtain an epoch value from a preference.
488 * This reads a string preference and returns an integer. The string
489 * preference is expected to contain the integer milliseconds since epoch.
490 * For best results, only read preferences that have been saved with
493 * We need to store times as strings because integer preferences are only
494 * 32 bits and likely overflow most dates.
496 * If the pref contains a non-integer value, the specified default value will
500 * (Preferences) Branch from which to retrieve preference.
502 * (string) The preference to read from.
504 * (Number) The default value to use if the preference is not defined.
506 * (Log.Logger) Logger to write warnings to.
508 getEpochPref: function getEpochPref(branch, pref, def = 0, log = null) {
509 if (!Number.isInteger(def)) {
510 throw new Error("Default value is not a number: " + def);
513 let valueStr = branch.getStringPref(pref, null);
515 if (valueStr !== null) {
516 let valueInt = parseInt(valueStr, 10);
517 if (Number.isNaN(valueInt)) {
520 "Preference value is not an integer. Using default. " +
539 * Obtain a Date from a preference.
541 * This is a wrapper around getEpochPref. It converts the value to a Date
542 * instance and performs simple range checking.
544 * The range checking ensures the date is newer than the oldestYear
548 * (Preferences) Branch from which to read preference.
550 * (string) The preference from which to read.
552 * (Number) The default value (in milliseconds) if the preference is
553 * not defined or invalid.
555 * (Log.Logger) Logger to write warnings to.
557 * (Number) Oldest year to accept in read values.
559 getDatePref: function getDatePref(
566 let valueInt = this.getEpochPref(branch, pref, def, log);
567 let date = new Date(valueInt);
569 if (valueInt == def || date.getFullYear() >= oldestYear) {
575 "Unexpected old date seen in pref. Returning default: " +
584 return new Date(def);
588 * Store a Date in a preference.
590 * This is the opposite of getDatePref(). The same notes apply.
592 * If the range check fails, an Error will be thrown instead of a default
593 * value silently being used.
596 * (Preference) Branch from which to read preference.
598 * (string) Name of preference to write to.
600 * (Date) The value to save.
602 * (Number) The oldest year to accept for values.
604 setDatePref: function setDatePref(branch, pref, date, oldestYear = 2010) {
605 if (date.getFullYear() < oldestYear) {
609 " to a very old time: " +
611 ". The current time is " +
613 ". Is the system clock wrong?"
617 branch.setStringPref(pref, "" + date.getTime());
621 * Convert a string between two encodings.
623 * Output is only guaranteed if the input stream is composed of octets. If
624 * the input string has characters with values larger than 255, data loss
627 * The returned string is guaranteed to consist of character codes no greater
631 * (string) The source string to convert.
633 * (string) The current encoding of the string.
635 * (string) The target encoding of the string.
639 convertString: function convertString(s, source, dest) {
641 throw new Error("Input string must be defined.");
644 let is = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
645 Ci.nsIStringInputStream
647 is.setData(s, s.length);
649 let listener = Cc["@mozilla.org/network/stream-loader;1"].createInstance(
656 onStreamComplete: function onStreamComplete(
663 result = String.fromCharCode.apply(this, data);
667 let converter = this._converterService.asyncConvertData(
673 converter.onStartRequest(null, null);
674 converter.onDataAvailable(null, is, 0, s.length);
675 converter.onStopRequest(null, null, null);
681 ChromeUtils.defineLazyGetter(CommonUtils, "_utf8Converter", function () {
683 "@mozilla.org/intl/scriptableunicodeconverter"
684 ].createInstance(Ci.nsIScriptableUnicodeConverter);
685 converter.charset = "UTF-8";
689 ChromeUtils.defineLazyGetter(CommonUtils, "_converterService", function () {
690 return Cc["@mozilla.org/streamConverters;1"].getService(
691 Ci.nsIStreamConverterService