@@ -195,12 +195,29 @@ function BufferSlicer(buffer, options) {
195
195
}
196
196
197
197
BufferSlicer . prototype . read = function ( buffer , offset , length , position , callback ) {
198
- var end = position + length ;
199
- var delta = end - this . buffer . length ;
200
- var written = ( delta > 0 ) ? delta : length ;
201
- this . buffer . copy ( buffer , offset , position , end ) ;
198
+ if ( ! ( 0 <= offset && offset <= buffer . length ) ) throw new RangeError ( "offset outside buffer: 0 <= " + offset + " <= " + buffer . length ) ;
199
+ if ( position < 0 ) throw new RangeError ( "position is negative: " + position ) ;
200
+ if ( offset + length > buffer . length ) {
201
+ // The caller's buffer can't hold all the bytes they're trying to read.
202
+ // Clamp the length instead of giving an error.
203
+ // The callback will be informed of fewer than expected bytes written.
204
+ length = buffer . length - offset ;
205
+ }
206
+ if ( position + length > this . buffer . length ) {
207
+ // Clamp any attempt to read past the end of the source buffer.
208
+ length = this . buffer . length - position ;
209
+ }
210
+ if ( length <= 0 ) {
211
+ // After any clamping, we're fully out of bounds or otherwise have nothing to do.
212
+ // This isn't an error; it's just zero bytes written.
213
+ setImmediate ( function ( ) {
214
+ callback ( null , 0 ) ;
215
+ } ) ;
216
+ return ;
217
+ }
218
+ this . buffer . copy ( buffer , offset , position , position + length ) ;
202
219
setImmediate ( function ( ) {
203
- callback ( null , written ) ;
220
+ callback ( null , length ) ;
204
221
} ) ;
205
222
} ;
206
223
0 commit comments