twitst4tz

twitter statistics web application
Log | Files | Refs | README | LICENSE

base64-arraybuffer.js (1896B)


      1 /*
      2  * base64-arraybuffer
      3  * https://github.com/niklasvh/base64-arraybuffer
      4  *
      5  * Copyright (c) 2012 Niklas von Hertzen
      6  * Licensed under the MIT license.
      7  */
      8 (function(){
      9   "use strict";
     10 
     11   var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
     12 
     13   // Use a lookup table to find the index.
     14   var lookup = new Uint8Array(256);
     15   for (var i = 0; i < chars.length; i++) {
     16     lookup[chars.charCodeAt(i)] = i;
     17   }
     18 
     19   exports.encode = function(arraybuffer) {
     20     var bytes = new Uint8Array(arraybuffer),
     21     i, len = bytes.length, base64 = "";
     22 
     23     for (i = 0; i < len; i+=3) {
     24       base64 += chars[bytes[i] >> 2];
     25       base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
     26       base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
     27       base64 += chars[bytes[i + 2] & 63];
     28     }
     29 
     30     if ((len % 3) === 2) {
     31       base64 = base64.substring(0, base64.length - 1) + "=";
     32     } else if (len % 3 === 1) {
     33       base64 = base64.substring(0, base64.length - 2) + "==";
     34     }
     35 
     36     return base64;
     37   };
     38 
     39   exports.decode =  function(base64) {
     40     var bufferLength = base64.length * 0.75,
     41     len = base64.length, i, p = 0,
     42     encoded1, encoded2, encoded3, encoded4;
     43 
     44     if (base64[base64.length - 1] === "=") {
     45       bufferLength--;
     46       if (base64[base64.length - 2] === "=") {
     47         bufferLength--;
     48       }
     49     }
     50 
     51     var arraybuffer = new ArrayBuffer(bufferLength),
     52     bytes = new Uint8Array(arraybuffer);
     53 
     54     for (i = 0; i < len; i+=4) {
     55       encoded1 = lookup[base64.charCodeAt(i)];
     56       encoded2 = lookup[base64.charCodeAt(i+1)];
     57       encoded3 = lookup[base64.charCodeAt(i+2)];
     58       encoded4 = lookup[base64.charCodeAt(i+3)];
     59 
     60       bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
     61       bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
     62       bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
     63     }
     64 
     65     return arraybuffer;
     66   };
     67 })();