forked from ainsleys/glossy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.io-stream.js
6575 lines (5503 loc) · 170 KB
/
socket.io-stream.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ss = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = require('./lib');
},{"./lib":3}],2:[function(require,module,exports){
(function (Buffer){
var util = require('util');
var Readable = require('stream').Readable;
var bind = require('component-bind');
module.exports = BlobReadStream;
util.inherits(BlobReadStream, Readable);
/**
* Readable stream for Blob and File on browser.
*
* @param {Object} options
* @api private
*/
function BlobReadStream(blob, options) {
if (!(this instanceof BlobReadStream)) {
return new BlobReadStream(blob, options);
}
Readable.call(this, options);
options = options || {};
this.blob = blob;
this.slice = blob.slice || blob.webkitSlice || blob.mozSlice;
this.start = 0;
this.sync = options.synchronous || false;
var fileReader;
if (options.synchronous) {
fileReader = this.fileReader = new FileReaderSync();
} else {
fileReader = this.fileReader = new FileReader();
}
fileReader.onload = bind(this, '_onload');
fileReader.onerror = bind(this, '_onerror');
}
BlobReadStream.prototype._read = function(size) {
var start = this.start;
var end = this.start = this.start + size;
var chunk = this.slice.call(this.blob, start, end);
if (chunk.size) {
if (this.sync) {
var bufferChunk = new Buffer(new Uint8Array(this.fileReader.readAsArrayBuffer(chunk)));
this.push(bufferChunk);
} else {
this.fileReader.readAsArrayBuffer(chunk);
}
} else {
this.push(null);
}
}
BlobReadStream.prototype._onload = function(e) {
var chunk = new Buffer(new Uint8Array(e.target.result));
this.push(chunk);
};
BlobReadStream.prototype._onerror = function(e) {
var err = e.target.error;
this.emit('error', err);
};
}).call(this,require("buffer").Buffer)
},{"buffer":9,"component-bind":35,"stream":31,"util":34}],3:[function(require,module,exports){
(function (Buffer){
var Socket = require('./socket');
var IOStream = require('./iostream');
var BlobReadStream = require('./blob-read-stream');
exports = module.exports = lookup;
/**
* Expose Node Buffer for browser.
*
* @api public
*/
exports.Buffer = Buffer;
/**
* Expose Socket constructor.
*
* @api public
*/
exports.Socket = Socket;
/**
* Expose IOStream constructor.
*
* @api public
*/
exports.IOStream = IOStream;
/**
* Forces base 64 encoding when emitting. Must be set to true for Socket.IO v0.9 or lower.
*
* @api public
*/
exports.forceBase64 = false;
/**
* Look up an existing Socket.
*
* @param {socket.io#Socket} socket.io
* @param {Object} options
* @return {Socket} Socket instance
* @api public
*/
function lookup(sio, options) {
options = options || {};
if (null == options.forceBase64) {
options.forceBase64 = exports.forceBase64;
}
if (!sio._streamSocket) {
sio._streamSocket = new Socket(sio, options);
}
return sio._streamSocket;
}
/**
* Creates a new duplex stream.
*
* @param {Object} options
* @return {IOStream} duplex stream
* @api public
*/
exports.createStream = function(options) {
return new IOStream(options);
};
/**
* Creates a new readable stream for Blob/File on browser.
*
* @param {Blob} blob
* @param {Object} options
* @return {BlobReadStream} stream
* @api public
*/
exports.createBlobReadStream = function(blob, options) {
return new BlobReadStream(blob, options);
};
}).call(this,require("buffer").Buffer)
},{"./blob-read-stream":2,"./iostream":4,"./socket":6,"buffer":9}],4:[function(require,module,exports){
var util = require('util');
var Duplex = require('stream').Duplex;
var bind = require('component-bind');
var uuid = require('./uuid');
var debug = require('debug')('socket.io-stream:iostream');
module.exports = IOStream;
util.inherits(IOStream, Duplex);
/**
* Duplex
*
* @param {Object} options
* @api private
*/
function IOStream(options) {
if (!(this instanceof IOStream)) {
return new IOStream(options);
}
IOStream.super_.call(this, options);
this.options = options;
this.id = uuid();
this.socket = null;
// Buffers
this.pushBuffer = [];
this.writeBuffer = [];
// Op states
this._readable = false;
this._writable = false;
this.destroyed = false;
// default to *not* allowing half open sockets
this.allowHalfOpen = options && options.allowHalfOpen || false;
this.on('finish', this._onfinish);
this.on('end', this._onend);
this.on('error', this._onerror);
}
/**
* Ensures that no more I/O activity happens on this stream.
* Not necessary in the usual case.
*
* @api public
*/
IOStream.prototype.destroy = function() {
debug('destroy');
if (this.destroyed) {
debug('already destroyed');
return;
}
this.readable = this.writable = false;
if (this.socket) {
debug('clean up');
this.socket.cleanup(this.id);
this.socket = null;
}
this.destroyed = true;
};
/**
* Local read
*
* @api private
*/
IOStream.prototype._read = function(size) {
var push;
// We can not read from the socket if it's destroyed obviously ...
if (this.destroyed) return;
if (this.pushBuffer.length) {
// flush buffer and end if it exists.
while (push = this.pushBuffer.shift()) {
if (!push()) break;
}
return;
}
this._readable = true;
// Go get data from remote stream
// Calls
// ._onread remotely
// then
// ._onwrite locally
this.socket._read(this.id, size);
};
/**
* Read from remote stream
*
* @api private
*/
IOStream.prototype._onread = function(size) {
var write = this.writeBuffer.shift();
if (write) return write();
this._writable = true;
};
/**
* Write local data to remote stream
* Calls
* remtote ._onwrite
*
* @api private
*/
IOStream.prototype._write = function(chunk, encoding, callback) {
var self = this;
function write() {
// We can not write to the socket if it's destroyed obviously ...
if (self.destroyed) return;
self._writable = false;
self.socket._write(self.id, chunk, encoding, callback);
}
if (this._writable) {
write();
} else {
this.writeBuffer.push(write);
}
};
/**
* Write the data fetched remotely
* so that we can now read locally
*
* @api private
*/
IOStream.prototype._onwrite = function(chunk, encoding, callback) {
var self = this;
function push() {
self._readable = false;
var ret = self.push(chunk || '', encoding);
callback();
return ret;
}
if (this._readable) {
push();
} else {
this.pushBuffer.push(push);
}
};
/**
* When ending send 'end' event to remote stream
*
* @api private
*/
IOStream.prototype._end = function() {
if (this.pushBuffer.length) {
// end after flushing buffer.
this.pushBuffer.push(bind(this, '_done'));
} else {
this._done();
}
};
/**
* Remote stream just ended
*
* @api private
*/
IOStream.prototype._done = function() {
this._readable = false;
// signal the end of the data.
return this.push(null);
};
/**
* the user has called .end(), and all the bytes have been
* sent out to the other side.
* If allowHalfOpen is false, or if the readable side has
* ended already, then destroy.
* If allowHalfOpen is true, then we need to set writable false,
* so that only the writable side will be cleaned up.
*
* @api private
*/
IOStream.prototype._onfinish = function() {
debug('_onfinish');
// Local socket just finished
// send 'end' event to remote
if (this.socket) {
this.socket._end(this.id);
}
this.writable = false;
this._writableState.ended = true;
if (!this.readable || this._readableState.ended) {
debug('_onfinish: ended, destroy %s', this._readableState);
return this.destroy();
}
debug('_onfinish: not ended');
if (!this.allowHalfOpen) {
this.push(null);
// just in case we're waiting for an EOF.
if (this.readable && !this._readableState.endEmitted) {
this.read(0);
}
}
};
/**
* the EOF has been received, and no more bytes are coming.
* if the writable side has ended already, then clean everything
* up.
*
* @api private
*/
IOStream.prototype._onend = function() {
debug('_onend');
this.readable = false;
this._readableState.ended = true;
if (!this.writable || this._writableState.finished) {
debug('_onend: %s', this._writableState);
return this.destroy();
}
debug('_onend: not finished');
if (!this.allowHalfOpen) {
this.end();
}
};
/**
* When error in local stream
* notyify remote
* if err.remote = true
* then error happened on remote stream
*
* @api private
*/
IOStream.prototype._onerror = function(err) {
// check if the error came from remote stream.
if (!err.remote && this.socket) {
// notify the error to the corresponding remote stream.
this.socket._error(this.id, err);
}
this.destroy();
};
},{"./uuid":7,"component-bind":35,"debug":36,"stream":31,"util":34}],5:[function(require,module,exports){
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var IOStream = require('./iostream');
var slice = Array.prototype.slice;
exports.Encoder = Encoder;
exports.Decoder = Decoder;
util.inherits(Encoder, EventEmitter);
function Encoder() {
EventEmitter.call(this);
}
/**
* Encode streams to placeholder objects.
*
* @api public
*/
Encoder.prototype.encode = function(v) {
if (v instanceof IOStream) {
return this.encodeStream(v);
} else if (util.isArray(v)) {
return this.encodeArray(v);
} else if (v && 'object' == typeof v) {
return this.encodeObject(v);
}
return v;
}
Encoder.prototype.encodeStream = function(stream) {
this.emit('stream', stream);
// represent a stream in an object.
var v = { $stream: stream.id };
if (stream.options) {
v.options = stream.options;
}
return v;
}
Encoder.prototype.encodeArray = function(arr) {
var v = [];
for (var i = 0, len = arr.length; i < len; i++) {
v.push(this.encode(arr[i]));
}
return v;
}
Encoder.prototype.encodeObject = function(obj) {
var v = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
v[k] = this.encode(obj[k]);
}
}
return v;
}
util.inherits(Decoder, EventEmitter);
function Decoder() {
EventEmitter.call(this);
}
/**
* Decode placeholder objects to streams.
*
* @api public
*/
Decoder.prototype.decode = function(v) {
if (v && v.$stream) {
return this.decodeStream(v);
} else if (util.isArray(v)) {
return this.decodeArray(v);
} else if (v && 'object' == typeof v) {
return this.decodeObject(v);
}
return v;
}
Decoder.prototype.decodeStream = function(obj) {
var stream = new IOStream(obj.options);
stream.id = obj.$stream;
this.emit('stream', stream);
return stream;
}
Decoder.prototype.decodeArray = function(arr) {
var v = [];
for (var i = 0, len = arr.length; i < len; i++) {
v.push(this.decode(arr[i]));
}
return v;
}
Decoder.prototype.decodeObject = function(obj) {
var v = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
v[k] = this.decode(obj[k]);
}
}
return v;
}
},{"./iostream":4,"events":13,"util":34}],6:[function(require,module,exports){
(function (global,Buffer){
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var bind = require('component-bind');
var IOStream = require('./iostream');
var parser = require('./parser');
var debug = require('debug')('socket.io-stream:socket');
var emit = EventEmitter.prototype.emit;
var on = EventEmitter.prototype.on;
var slice = Array.prototype.slice;
exports = module.exports = Socket;
/**
* Base event name for messaging.
*
* @api public
*/
exports.event = '$stream';
exports.events = [
'error',
'newListener',
'removeListener'
];
util.inherits(Socket, EventEmitter);
/**
* Bidirectional stream socket which wraps Socket.IO.
*
* @param {socket.io#Socket} socket.io
* @api public
*/
function Socket(sio, options) {
if (!(this instanceof Socket)) {
return new Socket(sio, options);
}
EventEmitter.call(this);
options = options || {};
this.sio = sio;
this.forceBase64 = !!options.forceBase64;
this.streams = {};
this.encoder = new parser.Encoder();
this.decoder = new parser.Decoder();
var eventName = exports.event;
sio.on(eventName, bind(this, emit));
sio.on(eventName + '-read', bind(this, '_onread'));
sio.on(eventName + '-write', bind(this, '_onwrite'));
sio.on(eventName + '-end', bind(this, '_onend'));
sio.on(eventName + '-error', bind(this, '_onerror'));
sio.on('error', bind(this, emit, 'error'));
sio.on('disconnect', bind(this, '_ondisconnect'));
this.encoder.on('stream', bind(this, '_onencode'));
this.decoder.on('stream', bind(this, '_ondecode'));
}
/**
* Original emit function.
*
* @api private
*/
Socket.prototype.$emit = emit;
/**
* Emits streams to this corresponding server/client.
*
* @return {Socket} self
* @api public
*/
Socket.prototype.emit = function(type) {
if (~exports.events.indexOf(type)) {
return emit.apply(this, arguments);
}
this._stream.apply(this, arguments);
return this;
};
Socket.prototype.on = function(type, listener) {
if (~exports.events.indexOf(type)) {
return on.apply(this, arguments);
}
this._onstream(type, listener);
return this;
};
/**
* Sends a new stream request.
*
* @param {String} event type
* @api private
*/
Socket.prototype._stream = function(type) {
debug('sending new streams');
var self = this;
var args = slice.call(arguments, 1);
var ack = args[args.length - 1];
if ('function' == typeof ack) {
args[args.length - 1] = function() {
var args = slice.call(arguments);
args = self.decoder.decode(args);
ack.apply(this, args);
};
}
args = this.encoder.encode(args);
var sio = this.sio;
sio.emit.apply(sio, [exports.event, type].concat(args));
};
/**
* Notifies the read event.
*
* @api private
*/
Socket.prototype._read = function(id, size) {
this.sio.emit(exports.event + '-read', id, size);
};
/**
* Requests to write a chunk.
*
* @api private
*/
Socket.prototype._write = function(id, chunk, encoding, callback) {
if (Buffer.isBuffer(chunk)) {
if (this.forceBase64) {
encoding = 'base64';
chunk = chunk.toString(encoding);
} else if (!global.Buffer) {
// socket.io can't handle Buffer when using browserify.
chunk = chunk.toArrayBuffer();
}
}
this.sio.emit(exports.event + '-write', id, chunk, encoding, callback);
};
Socket.prototype._end = function(id) {
this.sio.emit(exports.event + '-end', id);
};
Socket.prototype._error = function(id, err) {
this.sio.emit(exports.event + '-error', id, err.message || err);
};
/**
* Handles a new stream request.
*
* @param {String} event type
* @param {Function} listener
*
* @api private
*/
Socket.prototype._onstream = function(type, listener) {
if ('function' != typeof listener) {
throw TypeError('listener must be a function');
}
function onstream() {
debug('new streams');
var self = this;
var args = slice.call(arguments);
var ack = args[args.length - 1];
if ('function' == typeof ack) {
args[args.length - 1] = function() {
var args = slice.call(arguments);
args = self.encoder.encode(args);
ack.apply(this, args);
};
}
args = this.decoder.decode(args);
listener.apply(this, args);
}
// for removeListener
onstream.listener = listener;
on.call(this, type, onstream);
};
Socket.prototype._onread = function(id, size) {
debug('read: "%s"', id);
var stream = this.streams[id];
if (stream) {
stream._onread(size);
} else {
debug('ignore invalid stream id');
}
};
Socket.prototype._onwrite = function(id, chunk, encoding, callback) {
debug('write: "%s"', id);
var stream = this.streams[id];
if (!stream) {
callback('invalid stream id: ' + id);
return;
}
if (global.ArrayBuffer && chunk instanceof ArrayBuffer) {
// make sure that chunk is a buffer for stream
chunk = new Buffer(new Uint8Array(chunk));
}
stream._onwrite(chunk, encoding, callback);
};
Socket.prototype._onend = function(id) {
debug('end: "%s"', id);
var stream = this.streams[id];
if (!stream) {
debug('ignore non-existent stream id: "%s"', id);
return;
}
stream._end();
};
Socket.prototype._onerror = function(id, message) {
debug('error: "%s", "%s"', id, message);
var stream = this.streams[id];
if (!stream) {
debug('invalid stream id: "%s"', id);
return;
}
var err = new Error(message);
err.remote = true;
stream.emit('error', err);
};
Socket.prototype._ondisconnect = function() {
var stream;
for (var id in this.streams) {
stream = this.streams[id];
stream.destroy();
// Close streams when the underlaying
// socket.io connection is closed (regardless why)
stream.emit('close');
stream.emit('error', new Error('Connection aborted'));
}
};
Socket.prototype._onencode = function(stream) {
if (stream.socket || stream.destroyed) {
throw new Error('stream has already been sent.');
}
var id = stream.id;
if (this.streams[id]) {
throw new Error('Encoded stream already exists: ' + id);
}
this.streams[id] = stream;
stream.socket = this;
};
Socket.prototype._ondecode = function(stream) {
var id = stream.id;
if (this.streams[id]) {
this._error(id, new Error('Decoded stream already exists: ' + id));
return;
}
this.streams[id] = stream;
stream.socket = this;
};
Socket.prototype.cleanup = function(id) {
delete this.streams[id];
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"./iostream":4,"./parser":5,"buffer":9,"component-bind":35,"debug":36,"events":13,"util":34}],7:[function(require,module,exports){
// UUID function from https://gist.github.com/jed/982883
// More lightweight than node-uuid
function b(
a // placeholder
){
return a // if the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
Math.random() // in which case
* 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
b // random hex digits
)
}
module.exports = b;
},{}],8:[function(require,module,exports){
},{}],9:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
* on objects.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
function typedArraySupport () {
function Bar () {}
try {
var arr = new Uint8Array(1)
arr.foo = function () { return 42 }
arr.constructor = Bar
return arr.foo() === 42 && // typed array instances can be augmented
arr.constructor === Bar && // constructor can be set
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (arg) {
if (!(this instanceof Buffer)) {
// Avoid going through an ArgumentsAdaptorTrampoline in the common case.
if (arguments.length > 1) return new Buffer(arg, arguments[1])
return new Buffer(arg)
}
this.length = 0
this.parent = undefined
// Common case.
if (typeof arg === 'number') {
return fromNumber(this, arg)
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
}
// Unusual.
return fromObject(this, arg)
}
function fromNumber (that, length) {
that = allocate(that, length < 0 ? 0 : checked(length) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < length; i++) {
that[i] = 0
}
}
return that
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
// Assumption: byteLength() return value is always < kMaxLength.
var length = byteLength(string, encoding) | 0
that = allocate(that, length)
that.write(string, encoding)
return that
}
function fromObject (that, object) {
if (Buffer.isBuffer(object)) return fromBuffer(that, object)
if (isArray(object)) return fromArray(that, object)
if (object == null) {
throw new TypeError('must start with number, buffer, array or string')
}
if (typeof ArrayBuffer !== 'undefined') {
if (object.buffer instanceof ArrayBuffer) {
return fromTypedArray(that, object)
}
if (object instanceof ArrayBuffer) {
return fromArrayBuffer(that, object)
}
}
if (object.length) return fromArrayLike(that, object)
return fromJsonObject(that, object)
}