src/javascript/crypto/e2e/compression/bzip2.js

1/**
2 * @license
3 * Copyright 2015 Google Inc. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18/**
19 * @fileoverview Implementation of bzip2.
20 * @author adhintz@google.com (Drew Hintz)
21 */
22
23goog.provide('e2e.compression.Bzip2');
24
25goog.require('e2e.compression.Algorithm');
26goog.require('e2e.compression.Compression');
27
28
29
30/**
31 * Bzip2 implementation.
32 * @extends {e2e.compression.Compression}
33 * @constructor
34 */
35e2e.compression.Bzip2 = function() {
36 goog.base(this, e2e.compression.Algorithm.BZIP2);
37};
38goog.inherits(e2e.compression.Bzip2,
39 e2e.compression.Compression);
40
41
42/** @inheritDoc */
43e2e.compression.Bzip2.prototype.decompress = function(compressedData) {
44 throw new Error('bzip2 decompression not implemented.');
45};
46
47
48/** @inheritDoc */
49e2e.compression.Bzip2.prototype.compress = function(data) {
50 throw new Error('bzip2 compression not implemented.');
51};
52
53
54
55/**
56 * Reads a ByteArray bit by bit.
57 * @param {!e2e.ByteArray} data Input to read bits from.
58 * @private
59 * @constructor
60 */
61e2e.compression.Bzip2.Bits_ = function(data) {
62 /**
63 * @private
64 * @type {!e2e.ByteArray}
65 */
66 this.data_ = data;
67
68 /**
69 * Offset in bits into the data ByteArray.
70 * @private
71 * @type {number}
72 */
73 this.offset_ = 0;
74};
75
76
77/**
78 * @param {number} bits Number of bits to read, between 1 and 32 inclusive.
79 * @return {number} Bits stored in a number.
80 */
81e2e.compression.Bzip2.Bits_.prototype.read = function(bits) {
82 if (bits < 1 || bits > 32 || this.offset_ + bits > this.data_.length * 8) {
83 throw new RangeError('invalid number of bits to read from data array');
84 }
85 var byte_offset = this.offset_ >>> 3;
86 var bit_offset = this.offset_ % 8;
87 this.offset_ += bits;
88
89 var result = 0;
90 while (bits > 0) {
91 var bits_read_count = Math.min(8 - bit_offset, bits);
92 result <<= bits_read_count;
93 result |= this.data_[byte_offset] >>> (8 - bits_read_count);
94
95 byte_offset++;
96 bit_offset = 0;
97 bits -= bits_read_count;
98 }
99
100 return result;
101};
102
103// TODO(adhintz) Uncomment after bzip2 is implemented.
104// e2e.compression.factory.add(e2e.compression.Bzip2,
105// e2e.compression.Algorithm.BZIP2);