2010-04-06 Jb Evain <jbevain@novell.com>
[mcs.git] / class / corlib / System.IO / MemoryStream.cs
blob45673b328e641e96a0c61075b8b759639c168322
1 //
2 // System.IO.MemoryStream.cs
3 //
4 // Authors: Marcin Szczepanski (marcins@zipworld.com.au)
5 // Patrik Torstensson
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
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:
23 //
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 //
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;
39 namespace System.IO
41 [Serializable]
42 [ComVisible (true)]
43 [MonoLimitation ("Serialization format not compatible with .NET")]
44 public class MemoryStream : Stream
46 bool canWrite;
47 bool allowGetBuffer;
48 int capacity;
49 int length;
50 byte [] internalBuffer;
51 int initialIndex;
52 bool expandable;
53 bool streamClosed;
54 int position;
55 int dirty_bytes;
57 public MemoryStream () : this (0)
61 public MemoryStream (int capacity)
63 if (capacity < 0)
64 throw new ArgumentOutOfRangeException ("capacity");
66 canWrite = true;
68 this.capacity = capacity;
69 internalBuffer = new byte [capacity];
71 expandable = true;
72 allowGetBuffer = true;
75 public MemoryStream (byte [] buffer)
77 if (buffer == null)
78 throw new ArgumentNullException ("buffer");
80 InternalConstructor (buffer, 0, buffer.Length, true, false);
83 public MemoryStream (byte [] buffer, bool writable)
85 if (buffer == null)
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)
108 if (buffer == null)
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.");
118 canWrite = writable;
120 internalBuffer = buffer;
121 capacity = count + index;
122 length = capacity;
123 position = index;
124 initialIndex = index;
126 allowGetBuffer = publicallyVisible;
127 expandable = false;
130 void CheckIfClosedThrowDisposed ()
132 if (streamClosed)
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 {
149 get {
150 CheckIfClosedThrowDisposed ();
151 return capacity - initialIndex;
154 set {
155 CheckIfClosedThrowDisposed ();
156 if (value == capacity)
157 return; // LAMENESS: see MemoryStreamTest.ConstructorFive
159 if (!expandable)
160 throw new NotSupportedException ("Cannot expand this MemoryStream");
162 if (value < 0 || value < length)
163 throw new ArgumentOutOfRangeException ("value",
164 "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
166 if (value == internalBuffer.Length)
167 return;
169 byte [] newBuffer = null;
170 if (value != 0) {
171 newBuffer = new byte [value];
172 Buffer.BlockCopy (internalBuffer, 0, newBuffer, 0, length);
175 dirty_bytes = 0; // discard any dirty area beyond previous length
176 internalBuffer = newBuffer; // It's null when capacity is set to 0
177 capacity = value;
181 public override long Length {
182 get {
183 // LAMESPEC: The spec says to throw an IOException if the
184 // stream is closed and an ObjectDisposedException if
185 // "methods were called after the stream was closed". What
186 // is the difference?
188 CheckIfClosedThrowDisposed ();
190 // This is ok for MemoryStreamTest.ConstructorFive
191 return length - initialIndex;
195 public override long Position {
196 get {
197 CheckIfClosedThrowDisposed ();
198 return position - initialIndex;
201 set {
202 CheckIfClosedThrowDisposed ();
203 if (value < 0)
204 throw new ArgumentOutOfRangeException ("value",
205 "Position cannot be negative" );
207 if (value > Int32.MaxValue)
208 throw new ArgumentOutOfRangeException ("value",
209 "Position must be non-negative and less than 2^31 - 1 - origin");
211 position = initialIndex + (int) value;
215 protected override void Dispose (bool disposing)
217 streamClosed = true;
218 expandable = false;
221 public override void Flush ()
223 // Do nothing
226 public virtual byte [] GetBuffer ()
228 if (!allowGetBuffer)
229 throw new UnauthorizedAccessException ();
231 return internalBuffer;
234 public override int Read ([In,Out] byte [] buffer, int offset, int count)
236 CheckIfClosedThrowDisposed ();
238 if (buffer == null)
239 throw new ArgumentNullException ("buffer");
241 if (offset < 0 || count < 0)
242 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
244 if (buffer.Length - offset < count )
245 throw new ArgumentException ("offset+count",
246 "The size of the buffer is less than offset + count.");
248 if (position >= length || count == 0)
249 return 0;
251 if (position > length - count)
252 count = length - position;
254 Buffer.BlockCopy (internalBuffer, position, buffer, offset, count);
255 position += count;
256 return count;
259 public override int ReadByte ()
261 CheckIfClosedThrowDisposed ();
262 if (position >= length)
263 return -1;
265 return internalBuffer [position++];
268 public override long Seek (long offset, SeekOrigin loc)
270 CheckIfClosedThrowDisposed ();
272 // It's funny that they don't throw this exception for < Int32.MinValue
273 if (offset > (long) Int32.MaxValue)
274 throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
276 int refPoint;
277 switch (loc) {
278 case SeekOrigin.Begin:
279 if (offset < 0)
280 throw new IOException ("Attempted to seek before start of MemoryStream.");
281 refPoint = initialIndex;
282 break;
283 case SeekOrigin.Current:
284 refPoint = position;
285 break;
286 case SeekOrigin.End:
287 refPoint = length;
288 break;
289 default:
290 throw new ArgumentException ("loc", "Invalid SeekOrigin");
293 // LAMESPEC: My goodness, how may LAMESPECs are there in this
294 // class! :) In the spec for the Position property it's stated
295 // "The position must not be more than one byte beyond the end of the stream."
296 // In the spec for seek it says "Seeking to any location beyond the length of the
297 // stream is supported." That's a contradiction i'd say.
298 // I guess seek can go anywhere but if you use position it may get moved back.
300 refPoint += (int) offset;
301 if (refPoint < initialIndex)
302 throw new IOException ("Attempted to seek before start of MemoryStream.");
304 position = refPoint;
305 return position;
308 int CalculateNewCapacity (int minimum)
310 if (minimum < 256)
311 minimum = 256; // See GetBufferTwo test
313 if (minimum < capacity * 2)
314 minimum = capacity * 2;
316 return minimum;
319 void Expand (int newSize)
321 // We don't need to take into account the dirty bytes when incrementing the
322 // Capacity, as changing it will only preserve the valid clear region.
323 if (newSize > capacity)
324 Capacity = CalculateNewCapacity (newSize);
325 else if (dirty_bytes > 0) {
326 Array.Clear (internalBuffer, length, dirty_bytes);
327 dirty_bytes = 0;
331 public override void SetLength (long value)
333 if (!expandable && value > capacity)
334 throw new NotSupportedException ("Expanding this MemoryStream is not supported");
336 CheckIfClosedThrowDisposed ();
338 if (!canWrite) {
339 throw new NotSupportedException (Locale.GetText
340 ("Cannot write to this MemoryStream"));
343 // LAMESPEC: AGAIN! It says to throw this exception if value is
344 // greater than "the maximum length of the MemoryStream". I haven't
345 // seen anywhere mention what the maximum length of a MemoryStream is and
346 // since we're this far this memory stream is expandable.
347 if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
348 throw new ArgumentOutOfRangeException ();
350 int newSize = (int) value + initialIndex;
352 if (newSize > length)
353 Expand (newSize);
354 else if (newSize < length) // Postpone the call to Array.Clear till expand time
355 dirty_bytes += length - newSize;
357 length = newSize;
358 if (position > length)
359 position = length;
362 public virtual byte [] ToArray ()
364 int l = length - initialIndex;
365 byte[] outBuffer = new byte [l];
367 if (internalBuffer != null)
368 Buffer.BlockCopy (internalBuffer, initialIndex, outBuffer, 0, l);
369 return outBuffer;
372 public override void Write (byte [] buffer, int offset, int count)
374 CheckIfClosedThrowDisposed ();
376 if (!canWrite)
377 throw new NotSupportedException ("Cannot write to this stream.");
379 if (buffer == null)
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 // reordered to avoid possible integer overflow
390 if (position > length - count)
391 Expand (position + count);
393 Buffer.BlockCopy (buffer, offset, internalBuffer, position, count);
394 position += count;
395 if (position >= length)
396 length = position;
399 public override void WriteByte (byte value)
401 CheckIfClosedThrowDisposed ();
402 if (!canWrite)
403 throw new NotSupportedException ("Cannot write to this stream.");
405 if (position >= length) {
406 Expand (position + 1);
407 length = position + 1;
410 internalBuffer [position++] = value;
413 public virtual void WriteTo (Stream stream)
415 CheckIfClosedThrowDisposed ();
417 if (stream == null)
418 throw new ArgumentNullException ("stream");
420 stream.Write (internalBuffer, initialIndex, length - initialIndex);
423 #if NET_4_0
424 protected override void ObjectInvariant ()
427 #endif