addon-sdk/source/lib/sdk/base64.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/lib/sdk/base64.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,40 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +"use strict";
     1.9 +
    1.10 +module.metadata = {
    1.11 +  "stability": "unstable"
    1.12 +};
    1.13 +
    1.14 +const { Cu } = require("chrome");
    1.15 +
    1.16 +// Passing an empty object as second argument to avoid scope's pollution
    1.17 +const { atob, btoa } = Cu.import("resource://gre/modules/Services.jsm", {});
    1.18 +
    1.19 +function isUTF8(charset) {
    1.20 +  let type = typeof charset;
    1.21 +
    1.22 +  if (type === "undefined")
    1.23 +    return false;
    1.24 +
    1.25 +  if (type === "string" && charset.toLowerCase() === "utf-8")
    1.26 +    return true;
    1.27 +
    1.28 +  throw new Error("The charset argument can be only 'utf-8'");
    1.29 +}
    1.30 +
    1.31 +exports.decode = function (data, charset) {
    1.32 +  if (isUTF8(charset))
    1.33 +		return decodeURIComponent(escape(atob(data)))
    1.34 +
    1.35 +	return atob(data);
    1.36 +}
    1.37 +
    1.38 +exports.encode = function (data, charset) {
    1.39 +  if (isUTF8(charset))
    1.40 +    return btoa(unescape(encodeURIComponent(data)))
    1.41 +
    1.42 +	return btoa(data);
    1.43 +}

mercurial