1<!DOCTYPE html>
2<!--
3Copyright (c) 2014 The Chromium Authors. All rights reserved.
4Use of this source code is governed by a BSD-style license that can be
5found in the LICENSE file.
6-->
7<link rel="import" href="/base/base.html">
8<script>
9'use strict';
10
11tr.exportTo('tr.b', function() {
12
13  function Base64() {
14  }
15
16  function b64ToUint6(nChr) {
17    if (nChr > 64 && nChr < 91)
18      return nChr - 65;
19    if (nChr > 96 && nChr < 123)
20      return nChr - 71;
21    if (nChr > 47 && nChr < 58)
22      return nChr + 4;
23    if (nChr === 43)
24      return 62;
25    if (nChr === 47)
26      return 63;
27    return 0;
28  }
29
30  Base64.getDecodedBufferLength = function(input) {
31    return input.length * 3 + 1 >> 2;
32  }
33
34  Base64.EncodeArrayBufferToString = function(input) {
35    // http://stackoverflow.com/questions/9267899/
36    var binary = '';
37    var bytes = new Uint8Array(input);
38    var len = bytes.byteLength;
39    for (var i = 0; i < len; i++)
40      binary += String.fromCharCode(bytes[i]);
41    return btoa(binary);
42  }
43
44  Base64.DecodeToTypedArray = function(input, output) {
45
46    var nInLen = input.length;
47    var nOutLen = nInLen * 3 + 1 >> 2;
48    var nMod3 = 0;
49    var nMod4 = 0;
50    var nUint24 = 0;
51    var nOutIdx = 0;
52
53    if (nOutLen > output.byteLength)
54      throw new Error('Output buffer too small to decode.');
55
56    for (var nInIdx = 0; nInIdx < nInLen; nInIdx++) {
57      nMod4 = nInIdx & 3;
58      nUint24 |= b64ToUint6(input.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
59      if (nMod4 === 3 || nInLen - nInIdx === 1) {
60        for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
61          output.setUint8(nOutIdx, nUint24 >>> (16 >>> nMod3 & 24) & 255);
62        }
63        nUint24 = 0;
64      }
65    }
66    return nOutIdx - 1;
67  }
68
69  return {
70    Base64: Base64
71  };
72
73});
74</script>
75