2 // System.IO.MemoryStream.cs
4 // Authors: Marcin Szczepanski (marcins@zipworld.com.au)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2001,2002 Marcin Szczepanski, Patrik Torstensson
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright (C) 2004 Novell (http://www.novell.com)
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Globalization;
37 using System.Runtime.InteropServices;
43 [MonoLimitation ("Serialization format not compatible with .NET")]
44 public class MemoryStream : Stream
50 byte [] internalBuffer;
57 public MemoryStream () : this (0)
61 public MemoryStream (int capacity)
64 throw new ArgumentOutOfRangeException ("capacity");
68 this.capacity = capacity;
69 internalBuffer = new byte [capacity];
72 allowGetBuffer = true;
75 public MemoryStream (byte [] buffer)
78 throw new ArgumentNullException ("buffer");
80 InternalConstructor (buffer, 0, buffer.Length, true, false);
83 public MemoryStream (byte [] buffer, bool writable)
86 throw new ArgumentNullException ("buffer");
88 InternalConstructor (buffer, 0, buffer.Length, writable, false);
91 public MemoryStream (byte [] buffer, int index, int count)
93 InternalConstructor (buffer, index, count, true, false);
96 public MemoryStream (byte [] buffer, int index, int count, bool writable)
98 InternalConstructor (buffer, index, count, writable, false);
101 public MemoryStream (byte [] buffer, int index, int count, bool writable, bool publiclyVisible)
103 InternalConstructor (buffer, index, count, writable, publiclyVisible);
106 void InternalConstructor (byte [] buffer, int index, int count, bool writable, bool publicallyVisible)
109 throw new ArgumentNullException ("buffer");
111 if (index < 0 || count < 0)
112 throw new ArgumentOutOfRangeException ("index or count is less than 0.");
114 if (buffer.Length - index < count)
115 throw new ArgumentException ("index+count",
116 "The size of the buffer is less than index + count.");
120 internalBuffer = buffer;
121 capacity = count + index;
124 initialIndex = index;
126 allowGetBuffer = publicallyVisible;
130 void CheckIfClosedThrowDisposed ()
133 throw new ObjectDisposedException ("MemoryStream");
136 public override bool CanRead {
137 get { return !streamClosed; }
140 public override bool CanSeek {
141 get { return !streamClosed; }
144 public override bool CanWrite {
145 get { return (!streamClosed && canWrite); }
148 public virtual int Capacity {
150 CheckIfClosedThrowDisposed ();
151 return capacity - initialIndex;
155 CheckIfClosedThrowDisposed ();
158 throw new NotSupportedException ("Cannot expand this MemoryStream");
160 if (value < 0 || value < length)
161 throw new ArgumentOutOfRangeException ("value",
162 "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
164 if (internalBuffer != null && value == internalBuffer.Length)
167 byte [] newBuffer = null;
169 newBuffer = new byte [value];
170 if (internalBuffer != null)
171 Buffer.BlockCopy (internalBuffer, 0, newBuffer, 0, length);
174 dirty_bytes = 0; // discard any dirty area beyond previous length
175 internalBuffer = newBuffer; // It's null when capacity is set to 0
180 public override long Length {
182 // LAMESPEC: The spec says to throw an IOException if the
183 // stream is closed and an ObjectDisposedException if
184 // "methods were called after the stream was closed". What
185 // is the difference?
187 CheckIfClosedThrowDisposed ();
189 // This is ok for MemoryStreamTest.ConstructorFive
190 return length - initialIndex;
194 public override long Position {
196 CheckIfClosedThrowDisposed ();
197 return position - initialIndex;
201 CheckIfClosedThrowDisposed ();
203 throw new ArgumentOutOfRangeException ("value",
204 "Position cannot be negative" );
206 if (value > Int32.MaxValue)
207 throw new ArgumentOutOfRangeException ("value",
208 "Position must be non-negative and less than 2^31 - 1 - origin");
210 position = initialIndex + (int) value;
214 protected override void Dispose (bool disposing)
220 public override void Flush ()
225 public virtual byte [] GetBuffer ()
228 throw new UnauthorizedAccessException ();
230 return internalBuffer;
233 public override int Read ([In,Out] byte [] buffer, int offset, int count)
236 throw new ArgumentNullException ("buffer");
238 if (offset < 0 || count < 0)
239 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
241 if (buffer.Length - offset < count )
242 throw new ArgumentException ("offset+count",
243 "The size of the buffer is less than offset + count.");
245 CheckIfClosedThrowDisposed ();
247 if (position >= length || count == 0)
250 if (position > length - count)
251 count = length - position;
253 Buffer.BlockCopy (internalBuffer, position, buffer, offset, count);
258 public override int ReadByte ()
260 CheckIfClosedThrowDisposed ();
261 if (position >= length)
264 return internalBuffer [position++];
267 public override long Seek (long offset, SeekOrigin loc)
269 CheckIfClosedThrowDisposed ();
271 // It's funny that they don't throw this exception for < Int32.MinValue
272 if (offset > (long) Int32.MaxValue)
273 throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
277 case SeekOrigin.Begin:
279 throw new IOException ("Attempted to seek before start of MemoryStream.");
280 refPoint = initialIndex;
282 case SeekOrigin.Current:
289 throw new ArgumentException ("loc", "Invalid SeekOrigin");
292 // LAMESPEC: My goodness, how may LAMESPECs are there in this
293 // class! :) In the spec for the Position property it's stated
294 // "The position must not be more than one byte beyond the end of the stream."
295 // In the spec for seek it says "Seeking to any location beyond the length of the
296 // stream is supported." That's a contradiction i'd say.
297 // I guess seek can go anywhere but if you use position it may get moved back.
299 refPoint += (int) offset;
300 if (refPoint < initialIndex)
301 throw new IOException ("Attempted to seek before start of MemoryStream.");
307 int CalculateNewCapacity (int minimum)
310 minimum = 256; // See GetBufferTwo test
312 if (minimum < capacity * 2)
313 minimum = capacity * 2;
318 void Expand (int newSize)
320 // We don't need to take into account the dirty bytes when incrementing the
321 // Capacity, as changing it will only preserve the valid clear region.
322 if (newSize > capacity)
323 Capacity = CalculateNewCapacity (newSize);
324 else if (dirty_bytes > 0) {
325 Array.Clear (internalBuffer, length, dirty_bytes);
330 public override void SetLength (long value)
332 if (!expandable && value > capacity)
333 throw new NotSupportedException ("Expanding this MemoryStream is not supported");
335 CheckIfClosedThrowDisposed ();
338 throw new NotSupportedException (Locale.GetText
339 ("Cannot write to this MemoryStream"));
342 // LAMESPEC: AGAIN! It says to throw this exception if value is
343 // greater than "the maximum length of the MemoryStream". I haven't
344 // seen anywhere mention what the maximum length of a MemoryStream is and
345 // since we're this far this memory stream is expandable.
346 if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
347 throw new ArgumentOutOfRangeException ();
349 int newSize = (int) value + initialIndex;
351 if (newSize > length)
353 else if (newSize < length) // Postpone the call to Array.Clear till expand time
354 dirty_bytes += length - newSize;
357 if (position > length)
361 public virtual byte [] ToArray ()
363 int l = length - initialIndex;
364 byte[] outBuffer = new byte [l];
366 if (internalBuffer != null)
367 Buffer.BlockCopy (internalBuffer, initialIndex, outBuffer, 0, l);
371 public override void Write (byte [] buffer, int offset, int count)
374 throw new NotSupportedException ("Cannot write to this stream.");
377 throw new ArgumentNullException ("buffer");
379 if (offset < 0 || count < 0)
380 throw new ArgumentOutOfRangeException ();
382 if (buffer.Length - offset < count)
383 throw new ArgumentException ("offset+count",
384 "The size of the buffer is less than offset + count.");
386 CheckIfClosedThrowDisposed ();
388 // reordered to avoid possible integer overflow
389 if (position > length - count)
390 Expand (position + count);
392 Buffer.BlockCopy (buffer, offset, internalBuffer, position, count);
394 if (position >= length)
398 public override void WriteByte (byte value)
400 CheckIfClosedThrowDisposed ();
402 throw new NotSupportedException ("Cannot write to this stream.");
404 if (position >= length) {
405 Expand (position + 1);
406 length = position + 1;
409 internalBuffer [position++] = value;
412 public virtual void WriteTo (Stream stream)
414 CheckIfClosedThrowDisposed ();
417 throw new ArgumentNullException ("stream");
419 stream.Write (internalBuffer, initialIndex, length - initialIndex);
423 protected override void ObjectInvariant ()