2 // System.IO.MemoryStream.cs
4 // Authors: Marcin Szczepanski (marcins@zipworld.com.au)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // (c) 2001,2002 Marcin Szczepanski, Patrik Torstensson
10 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Globalization;
35 using System.Runtime.InteropServices;
36 using System.Threading;
38 using System.Threading.Tasks;
45 [MonoLimitation ("Serialization format not compatible with .NET")]
46 public class MemoryStream : Stream
52 byte [] internalBuffer;
63 public MemoryStream () : this (0)
67 public MemoryStream (int capacity)
70 throw new ArgumentOutOfRangeException ("capacity");
74 this.capacity = capacity;
75 internalBuffer = new byte [capacity];
78 allowGetBuffer = true;
81 public MemoryStream (byte [] buffer)
84 throw new ArgumentNullException ("buffer");
86 InternalConstructor (buffer, 0, buffer.Length, true, false);
89 public MemoryStream (byte [] buffer, bool writable)
92 throw new ArgumentNullException ("buffer");
94 InternalConstructor (buffer, 0, buffer.Length, writable, false);
97 public MemoryStream (byte [] buffer, int index, int count)
99 InternalConstructor (buffer, index, count, true, false);
102 public MemoryStream (byte [] buffer, int index, int count, bool writable)
104 InternalConstructor (buffer, index, count, writable, false);
107 public MemoryStream (byte [] buffer, int index, int count, bool writable, bool publiclyVisible)
109 InternalConstructor (buffer, index, count, writable, publiclyVisible);
112 void InternalConstructor (byte [] buffer, int index, int count, bool writable, bool publicallyVisible)
115 throw new ArgumentNullException ("buffer");
117 if (index < 0 || count < 0)
118 throw new ArgumentOutOfRangeException ("index or count is less than 0.");
120 if (buffer.Length - index < count)
121 throw new ArgumentException ("index+count",
122 "The size of the buffer is less than index + count.");
126 internalBuffer = buffer;
127 capacity = count + index;
130 initialIndex = index;
132 allowGetBuffer = publicallyVisible;
136 void CheckIfClosedThrowDisposed ()
139 throw new ObjectDisposedException ("MemoryStream");
142 public override bool CanRead {
143 get { return !streamClosed; }
146 public override bool CanSeek {
147 get { return !streamClosed; }
150 public override bool CanWrite {
151 get { return (!streamClosed && canWrite); }
154 public virtual int Capacity {
156 CheckIfClosedThrowDisposed ();
157 return capacity - initialIndex;
161 CheckIfClosedThrowDisposed ();
164 throw new NotSupportedException ("Cannot expand this MemoryStream");
166 if (value < 0 || value < length)
167 throw new ArgumentOutOfRangeException ("value",
168 "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
170 if (internalBuffer != null && value == internalBuffer.Length)
173 byte [] newBuffer = null;
175 newBuffer = new byte [value];
176 if (internalBuffer != null)
177 Buffer.BlockCopy (internalBuffer, 0, newBuffer, 0, length);
180 dirty_bytes = 0; // discard any dirty area beyond previous length
181 internalBuffer = newBuffer; // It's null when capacity is set to 0
186 public override long Length {
188 // LAMESPEC: The spec says to throw an IOException if the
189 // stream is closed and an ObjectDisposedException if
190 // "methods were called after the stream was closed". What
191 // is the difference?
193 CheckIfClosedThrowDisposed ();
195 // This is ok for MemoryStreamTest.ConstructorFive
196 return length - initialIndex;
200 public override long Position {
202 CheckIfClosedThrowDisposed ();
203 return position - initialIndex;
207 CheckIfClosedThrowDisposed ();
209 throw new ArgumentOutOfRangeException ("value",
210 "Position cannot be negative" );
212 if (value > Int32.MaxValue)
213 throw new ArgumentOutOfRangeException ("value",
214 "Position must be non-negative and less than 2^31 - 1 - origin");
216 position = initialIndex + (int) value;
220 protected override void Dispose (bool disposing)
226 public override void Flush ()
231 public virtual byte [] GetBuffer ()
234 throw new UnauthorizedAccessException ();
236 return internalBuffer;
239 public override int Read ([In,Out] byte [] buffer, int offset, int count)
242 throw new ArgumentNullException ("buffer");
244 if (offset < 0 || count < 0)
245 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
247 if (buffer.Length - offset < count )
248 throw new ArgumentException ("offset+count",
249 "The size of the buffer is less than offset + count.");
251 CheckIfClosedThrowDisposed ();
253 if (position >= length || count == 0)
256 if (position > length - count)
257 count = length - position;
259 Buffer.BlockCopy (internalBuffer, position, buffer, offset, count);
264 public override int ReadByte ()
266 CheckIfClosedThrowDisposed ();
267 if (position >= length)
270 return internalBuffer [position++];
273 public override long Seek (long offset, SeekOrigin loc)
275 CheckIfClosedThrowDisposed ();
277 // It's funny that they don't throw this exception for < Int32.MinValue
278 if (offset > (long) Int32.MaxValue)
279 throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
283 case SeekOrigin.Begin:
285 throw new IOException ("Attempted to seek before start of MemoryStream.");
286 refPoint = initialIndex;
288 case SeekOrigin.Current:
295 throw new ArgumentException ("loc", "Invalid SeekOrigin");
298 // LAMESPEC: My goodness, how may LAMESPECs are there in this
299 // class! :) In the spec for the Position property it's stated
300 // "The position must not be more than one byte beyond the end of the stream."
301 // In the spec for seek it says "Seeking to any location beyond the length of the
302 // stream is supported." That's a contradiction i'd say.
303 // I guess seek can go anywhere but if you use position it may get moved back.
305 refPoint += (int) offset;
306 if (refPoint < initialIndex)
307 throw new IOException ("Attempted to seek before start of MemoryStream.");
313 int CalculateNewCapacity (int minimum)
316 minimum = 256; // See GetBufferTwo test
318 if (minimum < capacity * 2)
319 minimum = capacity * 2;
324 void Expand (int newSize)
326 // We don't need to take into account the dirty bytes when incrementing the
327 // Capacity, as changing it will only preserve the valid clear region.
328 if (newSize > capacity)
329 Capacity = CalculateNewCapacity (newSize);
330 else if (dirty_bytes > 0) {
331 Array.Clear (internalBuffer, length, dirty_bytes);
336 public override void SetLength (long value)
338 if (!expandable && value > capacity)
339 throw new NotSupportedException ("Expanding this MemoryStream is not supported");
341 CheckIfClosedThrowDisposed ();
344 throw new NotSupportedException (Locale.GetText
345 ("Cannot write to this MemoryStream"));
348 // LAMESPEC: AGAIN! It says to throw this exception if value is
349 // greater than "the maximum length of the MemoryStream". I haven't
350 // seen anywhere mention what the maximum length of a MemoryStream is and
351 // since we're this far this memory stream is expandable.
352 if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
353 throw new ArgumentOutOfRangeException ();
355 int newSize = (int) value + initialIndex;
357 if (newSize > length)
359 else if (newSize < length) // Postpone the call to Array.Clear till expand time
360 dirty_bytes += length - newSize;
363 if (position > length)
367 public virtual byte [] ToArray ()
369 int l = length - initialIndex;
370 byte[] outBuffer = new byte [l];
372 if (internalBuffer != null)
373 Buffer.BlockCopy (internalBuffer, initialIndex, outBuffer, 0, l);
377 public override void Write (byte [] buffer, int offset, int count)
380 throw new ArgumentNullException ("buffer");
382 if (offset < 0 || count < 0)
383 throw new ArgumentOutOfRangeException ();
385 if (buffer.Length - offset < count)
386 throw new ArgumentException ("offset+count",
387 "The size of the buffer is less than offset + count.");
389 CheckIfClosedThrowDisposed ();
392 throw new NotSupportedException ("Cannot write to this stream.");
394 // reordered to avoid possible integer overflow
395 if (position > length - count)
396 Expand (position + count);
398 Buffer.BlockCopy (buffer, offset, internalBuffer, position, count);
400 if (position >= length)
404 public override void WriteByte (byte value)
406 CheckIfClosedThrowDisposed ();
408 throw new NotSupportedException ("Cannot write to this stream.");
410 if (position >= length) {
411 Expand (position + 1);
412 length = position + 1;
415 internalBuffer [position++] = value;
418 public virtual void WriteTo (Stream stream)
420 CheckIfClosedThrowDisposed ();
423 throw new ArgumentNullException ("stream");
425 stream.Write (internalBuffer, initialIndex, length - initialIndex);
430 public override Task CopyToAsync (Stream destination, int bufferSize, CancellationToken cancellationToken)
432 // TODO: Specialization but what for?
433 return base.CopyToAsync (destination, bufferSize, cancellationToken);
436 public override Task FlushAsync (CancellationToken cancellationToken)
438 if (cancellationToken.IsCancellationRequested)
439 return TaskConstants.Canceled;
443 return TaskConstants.Finished;
444 } catch (Exception ex) {
445 return Task<object>.FromException (ex);
449 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
452 throw new ArgumentNullException ("buffer");
454 if (offset < 0 || count < 0)
455 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
457 if (buffer.Length - offset < count )
458 throw new ArgumentException ("offset+count",
459 "The size of the buffer is less than offset + count.");
460 if (cancellationToken.IsCancellationRequested)
461 return TaskConstants<int>.Canceled;
464 count = Read (buffer, offset, count);
466 // Try not to allocate a new task for every buffer read
467 if (read_task == null || read_task.Result != count)
468 read_task = Task<int>.FromResult (count);
471 } catch (Exception ex) {
472 return Task<int>.FromException (ex);
476 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
479 throw new ArgumentNullException ("buffer");
481 if (offset < 0 || count < 0)
482 throw new ArgumentOutOfRangeException ();
484 if (buffer.Length - offset < count)
485 throw new ArgumentException ("offset+count",
486 "The size of the buffer is less than offset + count.");
488 if (cancellationToken.IsCancellationRequested)
489 return TaskConstants.Canceled;
492 Write (buffer, offset, count);
493 return TaskConstants.Finished;
494 } catch (Exception ex) {
495 return Task<object>.FromException (ex);