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;
62 public MemoryStream () : this (0)
66 public MemoryStream (int capacity)
69 throw new ArgumentOutOfRangeException ("capacity");
73 this.capacity = capacity;
74 internalBuffer = new byte [capacity];
77 allowGetBuffer = true;
80 public MemoryStream (byte [] buffer)
83 throw new ArgumentNullException ("buffer");
85 InternalConstructor (buffer, 0, buffer.Length, true, false);
88 public MemoryStream (byte [] buffer, bool writable)
91 throw new ArgumentNullException ("buffer");
93 InternalConstructor (buffer, 0, buffer.Length, writable, false);
96 public MemoryStream (byte [] buffer, int index, int count)
98 InternalConstructor (buffer, index, count, true, false);
101 public MemoryStream (byte [] buffer, int index, int count, bool writable)
103 InternalConstructor (buffer, index, count, writable, false);
106 public MemoryStream (byte [] buffer, int index, int count, bool writable, bool publiclyVisible)
108 InternalConstructor (buffer, index, count, writable, publiclyVisible);
111 void InternalConstructor (byte [] buffer, int index, int count, bool writable, bool publicallyVisible)
114 throw new ArgumentNullException ("buffer");
116 if (index < 0 || count < 0)
117 throw new ArgumentOutOfRangeException ("index or count is less than 0.");
119 if (buffer.Length - index < count)
120 throw new ArgumentException ("index+count",
121 "The size of the buffer is less than index + count.");
125 internalBuffer = buffer;
126 capacity = count + index;
129 initialIndex = index;
131 allowGetBuffer = publicallyVisible;
135 void CheckIfClosedThrowDisposed ()
138 throw new ObjectDisposedException ("MemoryStream");
141 public override bool CanRead {
142 get { return !streamClosed; }
145 public override bool CanSeek {
146 get { return !streamClosed; }
149 public override bool CanWrite {
150 get { return (!streamClosed && canWrite); }
153 public virtual int Capacity {
155 CheckIfClosedThrowDisposed ();
156 return capacity - initialIndex;
160 CheckIfClosedThrowDisposed ();
163 throw new NotSupportedException ("Cannot expand this MemoryStream");
165 if (value < 0 || value < length)
166 throw new ArgumentOutOfRangeException ("value",
167 "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
169 if (internalBuffer != null && value == internalBuffer.Length)
172 byte [] newBuffer = null;
174 newBuffer = new byte [value];
175 if (internalBuffer != null)
176 Buffer.BlockCopy (internalBuffer, 0, newBuffer, 0, length);
179 dirty_bytes = 0; // discard any dirty area beyond previous length
180 internalBuffer = newBuffer; // It's null when capacity is set to 0
185 public override long Length {
187 // LAMESPEC: The spec says to throw an IOException if the
188 // stream is closed and an ObjectDisposedException if
189 // "methods were called after the stream was closed". What
190 // is the difference?
192 CheckIfClosedThrowDisposed ();
194 // This is ok for MemoryStreamTest.ConstructorFive
195 return length - initialIndex;
199 public override long Position {
201 CheckIfClosedThrowDisposed ();
202 return position - initialIndex;
206 CheckIfClosedThrowDisposed ();
208 throw new ArgumentOutOfRangeException ("value",
209 "Position cannot be negative" );
211 if (value > Int32.MaxValue)
212 throw new ArgumentOutOfRangeException ("value",
213 "Position must be non-negative and less than 2^31 - 1 - origin");
215 position = initialIndex + (int) value;
219 protected override void Dispose (bool disposing)
225 public override void Flush ()
230 public virtual byte [] GetBuffer ()
233 throw new UnauthorizedAccessException ();
235 return internalBuffer;
238 public override int Read ([In,Out] byte [] buffer, int offset, int count)
241 throw new ArgumentNullException ("buffer");
243 if (offset < 0 || count < 0)
244 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
246 if (buffer.Length - offset < count )
247 throw new ArgumentException ("offset+count",
248 "The size of the buffer is less than offset + count.");
250 CheckIfClosedThrowDisposed ();
252 if (position >= length || count == 0)
255 if (position > length - count)
256 count = length - position;
258 Buffer.BlockCopy (internalBuffer, position, buffer, offset, count);
263 public override int ReadByte ()
265 CheckIfClosedThrowDisposed ();
266 if (position >= length)
269 return internalBuffer [position++];
272 public override long Seek (long offset, SeekOrigin loc)
274 CheckIfClosedThrowDisposed ();
276 // It's funny that they don't throw this exception for < Int32.MinValue
277 if (offset > (long) Int32.MaxValue)
278 throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
282 case SeekOrigin.Begin:
284 throw new IOException ("Attempted to seek before start of MemoryStream.");
285 refPoint = initialIndex;
287 case SeekOrigin.Current:
294 throw new ArgumentException ("loc", "Invalid SeekOrigin");
297 // LAMESPEC: My goodness, how may LAMESPECs are there in this
298 // class! :) In the spec for the Position property it's stated
299 // "The position must not be more than one byte beyond the end of the stream."
300 // In the spec for seek it says "Seeking to any location beyond the length of the
301 // stream is supported." That's a contradiction i'd say.
302 // I guess seek can go anywhere but if you use position it may get moved back.
304 refPoint += (int) offset;
305 if (refPoint < initialIndex)
306 throw new IOException ("Attempted to seek before start of MemoryStream.");
312 int CalculateNewCapacity (int minimum)
315 minimum = 256; // See GetBufferTwo test
317 if (minimum < capacity * 2)
318 minimum = capacity * 2;
323 void Expand (int newSize)
325 // We don't need to take into account the dirty bytes when incrementing the
326 // Capacity, as changing it will only preserve the valid clear region.
327 if (newSize > capacity)
328 Capacity = CalculateNewCapacity (newSize);
329 else if (dirty_bytes > 0) {
330 Array.Clear (internalBuffer, length, dirty_bytes);
335 public override void SetLength (long value)
337 if (!expandable && value > capacity)
338 throw new NotSupportedException ("Expanding this MemoryStream is not supported");
340 CheckIfClosedThrowDisposed ();
343 throw new NotSupportedException (Locale.GetText
344 ("Cannot write to this MemoryStream"));
347 // LAMESPEC: AGAIN! It says to throw this exception if value is
348 // greater than "the maximum length of the MemoryStream". I haven't
349 // seen anywhere mention what the maximum length of a MemoryStream is and
350 // since we're this far this memory stream is expandable.
351 if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
352 throw new ArgumentOutOfRangeException ();
354 int newSize = (int) value + initialIndex;
356 if (newSize > length)
358 else if (newSize < length) // Postpone the call to Array.Clear till expand time
359 dirty_bytes += length - newSize;
362 if (position > length)
366 public virtual byte [] ToArray ()
368 int l = length - initialIndex;
369 byte[] outBuffer = new byte [l];
371 if (internalBuffer != null)
372 Buffer.BlockCopy (internalBuffer, initialIndex, outBuffer, 0, l);
376 public override void Write (byte [] buffer, int offset, int count)
379 throw new NotSupportedException ("Cannot write to this stream.");
382 throw new ArgumentNullException ("buffer");
384 if (offset < 0 || count < 0)
385 throw new ArgumentOutOfRangeException ();
387 if (buffer.Length - offset < count)
388 throw new ArgumentException ("offset+count",
389 "The size of the buffer is less than offset + count.");
391 CheckIfClosedThrowDisposed ();
393 // reordered to avoid possible integer overflow
394 if (position > length - count)
395 Expand (position + count);
397 Buffer.BlockCopy (buffer, offset, internalBuffer, position, count);
399 if (position >= length)
403 public override void WriteByte (byte value)
405 CheckIfClosedThrowDisposed ();
407 throw new NotSupportedException ("Cannot write to this stream.");
409 if (position >= length) {
410 Expand (position + 1);
411 length = position + 1;
414 internalBuffer [position++] = value;
417 public virtual void WriteTo (Stream stream)
419 CheckIfClosedThrowDisposed ();
422 throw new ArgumentNullException ("stream");
424 stream.Write (internalBuffer, initialIndex, length - initialIndex);
429 public override Task CopyToAsync (Stream destination, int bufferSize, CancellationToken cancellationToken)
431 // TODO: Specialization but what for?
432 return base.CopyToAsync (destination, bufferSize, cancellationToken);
435 public override Task FlushAsync (CancellationToken cancellationToken)
437 if (cancellationToken.IsCancellationRequested)
438 return TaskConstants<int>.Canceled;
441 return TaskConstants.Finished;
444 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
446 if (cancellationToken.IsCancellationRequested)
447 return TaskConstants<int>.Canceled;
449 count = Read (buffer, offset, count);
451 // Try not to allocate a new task for every buffer read
452 if (read_task == null || read_task.Result != count)
453 read_task = Task<int>.FromResult (count);
458 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
460 if (cancellationToken.IsCancellationRequested)
461 return TaskConstants<int>.Canceled;
463 Write (buffer, offset, count);
464 return TaskConstants.Finished;