testing/xpcshell/node-spdy/lib/spdy/utils.js

branch
TOR_BUG_9701
changeset 15
b8a032363ba2
equal deleted inserted replaced
-1:000000000000 0:59d215f168a5
1 var spdy = require('../spdy'),
2 utils = exports;
3
4 var zlib = require('zlib'),
5 Buffer = require('buffer').Buffer;
6
7 //
8 // ### function createDeflate ()
9 // Creates deflate stream with SPDY dictionary
10 //
11 utils.createDeflate = function createDeflate(version) {
12 var deflate = zlib.createDeflate({
13 dictionary: spdy.protocol[version].dictionary,
14 windowBits: 11
15 });
16
17 // Define lock information early
18 deflate.locked = false;
19 deflate.lockBuffer = [];
20
21 return deflate;
22 };
23
24 //
25 // ### function createInflate ()
26 // Creates inflate stream with SPDY dictionary
27 //
28 utils.createInflate = function createInflate(version) {
29 var inflate = zlib.createInflate({
30 dictionary: spdy.protocol[version].dictionary,
31 windowBits: 15
32 });
33
34 // Define lock information early
35 inflate.locked = false;
36 inflate.lockBuffer = [];
37
38 return inflate;
39 };
40
41 //
42 // ### function resetZlibStream (stream)
43 // #### @stream {zlib.Stream} stream
44 // Resets zlib stream and associated locks
45 //
46 utils.resetZlibStream = function resetZlibStream(stream, callback) {
47 if (stream.locked) {
48 stream.lockBuffer.push(function() {
49 resetZlibStream(stream, callback);
50 });
51 return;
52 }
53
54 stream.reset();
55 stream.lockBuffer = [];
56
57 callback(null);
58 };
59
60 var delta = 0;
61 //
62 // ### function zstream (stream, buffer, callback)
63 // #### @stream {Deflate|Inflate} One of streams above
64 // #### @buffer {Buffer} Input data (to compress or to decompress)
65 // #### @callback {Function} Continuation to callback
66 // Compress/decompress data and pass it to callback
67 //
68 utils.zstream = function zstream(stream, buffer, callback) {
69 var flush = stream._flush,
70 chunks = [],
71 total = 0;
72
73 if (stream.locked) {
74 stream.lockBuffer.push(function() {
75 zstream(stream, buffer, callback);
76 });
77 return;
78 }
79 stream.locked = true;
80
81 function collect(chunk) {
82 chunks.push(chunk);
83 total += chunk.length;
84 }
85 stream.on('data', collect);
86 stream.write(buffer);
87
88 stream.once('error', function(err) {
89 stream.removeAllListeners('data');
90 callback(err);
91 });
92
93 stream.flush(function() {
94 stream.removeAllListeners('data');
95 stream.removeAllListeners('error');
96 stream._flush = flush;
97
98 callback(null, chunks, total);
99
100 stream.locked = false;
101 var deferred = stream.lockBuffer.shift();
102 if (deferred) deferred();
103 });
104 };
105
106 //
107 // ### function zwrap (stream)
108 // #### @stream {zlib.Stream} stream to wrap
109 // Wraps stream within function to allow simple deflate/inflate
110 //
111 utils.zwrap = function zwrap(stream) {
112 return function(data, callback) {
113 utils.zstream(stream, data, callback);
114 };
115 };

mercurial