2 // System.IO.MemoryStream
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;
45 [MonoTODO ("Serialization format not compatible with .NET")]
46 public class MemoryStream : Stream
52 byte [] internalBuffer;
58 public MemoryStream () : this (0)
62 public MemoryStream (int capacity)
65 throw new ArgumentOutOfRangeException ("capacity");
69 this.capacity = capacity;
70 internalBuffer = new byte [capacity];
73 allowGetBuffer = true;
76 public MemoryStream (byte [] buffer)
79 throw new ArgumentNullException ("buffer");
81 InternalConstructor (buffer, 0, buffer.Length, true, false);
84 public MemoryStream (byte [] buffer, bool writeable)
87 throw new ArgumentNullException ("buffer");
89 InternalConstructor (buffer, 0, buffer.Length, writeable, false);
92 public MemoryStream (byte [] buffer, int index, int count)
94 InternalConstructor (buffer, index, count, true, false);
97 public MemoryStream (byte [] buffer, int index, int count, bool writeable)
99 InternalConstructor (buffer, index, count, writeable, false);
102 public MemoryStream (byte [] buffer, int index, int count, bool writeable, bool publicallyVisible)
104 InternalConstructor (buffer, index, count, writeable, publicallyVisible);
107 void InternalConstructor (byte [] buffer, int index, int count, bool writeable, bool publicallyVisible)
110 throw new ArgumentNullException ("buffer");
112 if (index < 0 || count < 0)
113 throw new ArgumentOutOfRangeException ("index or count is less than 0.");
115 if (buffer.Length - index < count)
116 throw new ArgumentException ("index+count",
117 "The size of the buffer is less than index + count.");
119 canWrite = writeable;
121 internalBuffer = buffer;
122 capacity = count + index;
125 initialIndex = index;
127 allowGetBuffer = publicallyVisible;
131 void CheckIfClosedThrowDisposed ()
134 throw new ObjectDisposedException ("MemoryStream");
137 public override bool CanRead {
138 get { return !streamClosed; }
141 public override bool CanSeek {
142 get { return !streamClosed; }
145 public override bool CanWrite {
146 get { return (!streamClosed && canWrite); }
149 public virtual int Capacity {
151 CheckIfClosedThrowDisposed ();
152 return capacity - initialIndex;
156 CheckIfClosedThrowDisposed ();
157 if (value == capacity)
158 return; // LAMENESS: see MemoryStreamTest.ConstructorFive
161 throw new NotSupportedException ("Cannot expand this MemoryStream");
163 if (value < 0 || value < length)
164 throw new ArgumentOutOfRangeException ("value",
165 "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
167 byte [] newBuffer = null;
169 newBuffer = new byte [value];
170 Buffer.BlockCopy (internalBuffer, 0, newBuffer, 0, length);
173 internalBuffer = newBuffer; // It's null when capacity is set to 0
178 public override long Length {
180 // LAMESPEC: The spec says to throw an IOException if the
181 // stream is closed and an ObjectDisposedException if
182 // "methods were called after the stream was closed". What
183 // is the difference?
185 CheckIfClosedThrowDisposed ();
187 // This is ok for MemoryStreamTest.ConstructorFive
188 return length - initialIndex;
192 public override long Position {
194 CheckIfClosedThrowDisposed ();
195 return position - initialIndex;
199 CheckIfClosedThrowDisposed ();
201 throw new ArgumentOutOfRangeException ("value",
202 "Position cannot be negative" );
204 if (value > Int32.MaxValue)
205 throw new ArgumentOutOfRangeException ("value",
206 "Position must be non-negative and less than 2^31 - 1 - origin");
208 position = initialIndex + (int) value;
213 protected override void Dispose (bool disposing)
215 public override void Close ()
222 public override void Flush ()
227 public virtual byte [] GetBuffer ()
230 throw new UnauthorizedAccessException ();
232 return internalBuffer;
235 public override int Read ([In,Out] byte [] buffer, int offset, int count)
237 CheckIfClosedThrowDisposed ();
240 throw new ArgumentNullException ("buffer");
242 if (offset < 0 || count < 0)
243 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
245 if (buffer.Length - offset < count )
246 throw new ArgumentException ("offset+count",
247 "The size of the buffer is less than offset + count.");
249 if (position >= length || count == 0)
252 if (position > length - count)
253 count = length - position;
255 Buffer.BlockCopy (internalBuffer, position, buffer, offset, count);
260 public override int ReadByte ()
262 CheckIfClosedThrowDisposed ();
263 if (position >= length)
266 return internalBuffer [position++];
269 public override long Seek (long offset, SeekOrigin loc)
271 CheckIfClosedThrowDisposed ();
273 // It's funny that they don't throw this exception for < Int32.MinValue
274 if (offset > (long) Int32.MaxValue)
275 throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
279 case SeekOrigin.Begin:
281 throw new IOException ("Attempted to seek before start of MemoryStream.");
282 refPoint = initialIndex;
284 case SeekOrigin.Current:
291 throw new ArgumentException ("loc", "Invalid SeekOrigin");
294 // LAMESPEC: My goodness, how may LAMESPECs are there in this
295 // class! :) In the spec for the Position property it's stated
296 // "The position must not be more than one byte beyond the end of the stream."
297 // In the spec for seek it says "Seeking to any location beyond the length of the
298 // stream is supported." That's a contradiction i'd say.
299 // I guess seek can go anywhere but if you use position it may get moved back.
301 refPoint += (int) offset;
302 if (refPoint < initialIndex)
303 throw new IOException ("Attempted to seek before start of MemoryStream.");
309 int CalculateNewCapacity (int minimum)
312 minimum = 256; // See GetBufferTwo test
314 if (minimum < capacity * 2)
315 minimum = capacity * 2;
320 public override void SetLength (long value)
322 if (!expandable && value > capacity)
323 throw new NotSupportedException ("Expanding this MemoryStream is not supported");
325 CheckIfClosedThrowDisposed ();
328 throw new NotSupportedException (Locale.GetText
329 ("Cannot write to this MemoryStream"));
332 // LAMESPEC: AGAIN! It says to throw this exception if value is
333 // greater than "the maximum length of the MemoryStream". I haven't
334 // seen anywhere mention what the maximum length of a MemoryStream is and
335 // since we're this far this memory stream is expandable.
336 if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
337 throw new ArgumentOutOfRangeException ();
339 int newSize = (int) value + initialIndex;
340 if (newSize > capacity)
341 Capacity = CalculateNewCapacity (newSize);
342 else if (newSize < length)
343 // zeroize present data (so we don't get it
344 // back if we expand the stream using Seek)
345 Array.Clear (internalBuffer, newSize, length - newSize);
348 if (position > length)
352 public virtual byte [] ToArray ()
354 int l = length - initialIndex;
355 byte[] outBuffer = new byte [l];
357 if (internalBuffer != null)
358 Buffer.BlockCopy (internalBuffer, initialIndex, outBuffer, 0, l);
362 public override void Write (byte [] buffer, int offset, int count)
364 CheckIfClosedThrowDisposed ();
367 throw new NotSupportedException ("Cannot write to this stream.");
370 throw new ArgumentNullException ("buffer");
372 if (offset < 0 || count < 0)
373 throw new ArgumentOutOfRangeException ();
375 if (buffer.Length - offset < count)
376 throw new ArgumentException ("offset+count",
377 "The size of the buffer is less than offset + count.");
379 // reordered to avoid possible integer overflow
380 if (position > capacity - count)
381 Capacity = CalculateNewCapacity (position + count);
383 Buffer.BlockCopy (buffer, offset, internalBuffer, position, count);
385 if (position >= length)
389 public override void WriteByte (byte value)
391 CheckIfClosedThrowDisposed ();
393 throw new NotSupportedException ("Cannot write to this stream.");
395 if (position >= capacity)
396 Capacity = CalculateNewCapacity (position + 1);
398 if (position >= length)
399 length = position + 1;
401 internalBuffer [position++] = value;
404 public virtual void WriteTo (Stream stream)
406 CheckIfClosedThrowDisposed ();
409 throw new ArgumentNullException ("stream");
411 stream.Write (internalBuffer, initialIndex, length - initialIndex);