2004-12-03 Lluis Sanchez Gual <lluis@novell.com>
[mono.git] / mcs / class / corlib / System.IO / MemoryStream.cs
1 //
2 // System.IO.MemoryStream 
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)
11 //
12
13 //
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
15 //
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.
34 //
35
36 using System.Globalization;
37 using System.Runtime.InteropServices;
38
39 namespace System.IO
40 {
41         [Serializable]
42         [MonoTODO ("Fix serialization compatibility with MS.NET")]
43         public class MemoryStream : Stream
44         {
45                 bool canWrite;
46                 bool allowGetBuffer;
47                 int capacity;
48                 int length;
49                 byte [] internalBuffer;
50                 int initialIndex;
51                 bool expandable;
52                 bool streamClosed;
53                 int position;
54
55                 public MemoryStream () : this (0)
56                 {
57                 }
58
59                 public MemoryStream (int capacity)
60                 {
61                         if (capacity < 0)
62                                 throw new ArgumentOutOfRangeException ("capacity");
63
64                         canWrite = true;
65
66                         this.capacity = capacity;
67                         internalBuffer = new byte [capacity];
68
69                         expandable = true;
70                         allowGetBuffer = true;
71                 }
72
73                 public MemoryStream (byte [] buffer)
74                 {
75                         if (buffer == null)
76                                 throw new ArgumentNullException ("buffer");
77                         
78                         InternalConstructor (buffer, 0, buffer.Length, true, false);                        
79                 }
80
81                 public MemoryStream (byte [] buffer, bool writeable)
82                 {
83                         if (buffer == null)
84                                 throw new ArgumentNullException ("buffer");
85                         
86                         InternalConstructor (buffer, 0, buffer.Length, writeable, false);
87                 }
88
89                 public MemoryStream (byte [] buffer, int index, int count)
90                 {
91                         InternalConstructor (buffer, index, count, true, false);
92                 }
93
94                 public MemoryStream (byte [] buffer, int index, int count, bool writeable)
95                 {
96                         InternalConstructor (buffer, index, count, writeable, false);
97                 }
98
99                 public MemoryStream (byte [] buffer, int index, int count, bool writeable, bool publicallyVisible)
100                 {
101                         InternalConstructor (buffer, index, count, writeable, publicallyVisible);
102                 }
103
104                 void InternalConstructor (byte [] buffer, int index, int count, bool writeable, bool publicallyVisible)
105                 {
106                         if (buffer == null)
107                                 throw new ArgumentNullException ("buffer");
108
109                         if (index < 0 || count < 0)
110                                 throw new ArgumentOutOfRangeException ("index or count is less than 0.");
111
112                         if (buffer.Length - index < count)
113                                 throw new ArgumentException ("index+count", 
114                                                              "The size of the buffer is less than index + count.");
115
116                         canWrite = writeable;
117
118                         internalBuffer = buffer;
119                         capacity = count + index;
120                         length = capacity;
121                         position = index;
122                         initialIndex = index;
123
124                         allowGetBuffer = publicallyVisible;
125                         expandable = false;                
126                 }
127
128                 void CheckIfClosedThrowDisposed ()
129                 {
130                         if (streamClosed)
131                                 throw new ObjectDisposedException ("MemoryStream");
132                 }
133                 
134                 void CheckIfClosedThrowIO ()
135                 {
136                         if (streamClosed)
137                                 throw new IOException ("MemoryStream is closed");
138                 }
139                 
140                 public override bool CanRead {
141                         get { return !streamClosed; }
142                 }
143
144                 public override bool CanSeek {
145                         get { return !streamClosed; }
146                 }
147
148                 public override bool CanWrite {
149                         get { return (!streamClosed && canWrite); }
150                 }
151
152                 public virtual int Capacity {
153                         get {
154                                 CheckIfClosedThrowDisposed ();
155                                 return capacity - initialIndex;
156                         }
157
158                         set {
159                                 CheckIfClosedThrowDisposed ();
160                                 if (value == capacity)
161                                         return; // LAMENESS: see MemoryStreamTest.ConstructorFive
162
163                                 if (!expandable)
164                                         throw new NotSupportedException ("Cannot expand this MemoryStream");
165
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);
169
170                                 byte [] newBuffer = null;
171                                 if (value != 0) {
172                                         newBuffer = new byte [value];
173                                         Buffer.BlockCopyInternal (internalBuffer, 0, newBuffer, 0, length);
174                                 }
175
176                                 internalBuffer = newBuffer; // It's null when capacity is set to 0
177                                 capacity = value;
178                         }
179                 }
180
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?
187
188                                 CheckIfClosedThrowDisposed ();
189
190                                 // This is ok for MemoryStreamTest.ConstructorFive
191                                 return length - initialIndex;
192                         }
193                 }
194
195                 public override long Position {
196                         get {
197                                 CheckIfClosedThrowDisposed ();
198                                 return position - initialIndex;
199                         }
200
201                         set {
202                                 CheckIfClosedThrowDisposed ();
203                                 if (value < 0)
204                                         throw new ArgumentOutOfRangeException ("value",
205                                                                 "Position cannot be negative" );
206
207                                 if (value > Int32.MaxValue)
208                                         throw new ArgumentOutOfRangeException ("value",
209                                         "Position must be non-negative and less than 2^31 - 1 - origin");
210
211                                 position = initialIndex + (int) value;
212                         }
213                 }
214
215                 public override void Close ()
216                 {
217                         streamClosed = true;
218                         expandable = false;
219                 }
220
221                 public override void Flush ()
222                 {
223                         // Do nothing
224                 }
225
226                 public virtual byte [] GetBuffer ()
227                 {
228                         if (!allowGetBuffer)
229                                 throw new UnauthorizedAccessException ();
230
231                         return internalBuffer;
232                 }
233
234                 public override int Read ([In,Out] byte [] buffer, int offset, int count)
235                 {
236                         CheckIfClosedThrowDisposed ();
237
238                         if (buffer == null)
239                                 throw new ArgumentNullException ("buffer");
240
241                         if (offset < 0 || count < 0)
242                                 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
243
244                         if (buffer.Length - offset < count )
245                                 throw new ArgumentException ("offset+count",
246                                                               "The size of the buffer is less than offset + count.");
247
248                         if (position >= length || count == 0)
249                                 return 0;
250
251                         if (position > length - count)
252                                 count = length - position;
253
254                         Buffer.BlockCopyInternal (internalBuffer, position, buffer, offset, count);
255                         position += count;
256                         return count;
257                 }
258
259                 public override int ReadByte ()
260                 {
261                         CheckIfClosedThrowDisposed ();
262                         if (position >= length)
263                                 return -1;
264
265                         return internalBuffer [position++];
266                 }
267
268                 public override long Seek (long offset, SeekOrigin loc)
269                 {
270                         CheckIfClosedThrowDisposed ();
271
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);
275
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");
291                         }
292
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.
299
300                         refPoint += (int) offset;
301                         if (refPoint < initialIndex)
302                                 throw new IOException ("Attempted to seek before start of MemoryStream.");
303
304                         position = refPoint;
305                         return position;
306                 }
307
308                 int CalculateNewCapacity (int minimum)
309                 {
310                         if (minimum < 256)
311                                 minimum = 256; // See GetBufferTwo test
312
313                         if (minimum < capacity * 2)
314                                 minimum = capacity * 2;
315
316                         return minimum;
317                 }
318
319                 public override void SetLength (long value)
320                 {
321                         if (!expandable && value > capacity)
322                                 throw new NotSupportedException ("Expanding this MemoryStream is not supported");
323
324                         CheckIfClosedThrowDisposed ();
325
326                         if (!canWrite) {
327                                 throw new NotSupportedException (Locale.GetText 
328                                         ("Cannot write to this MemoryStream"));
329                         }
330
331                         // LAMESPEC: AGAIN! It says to throw this exception if value is
332                         // greater than "the maximum length of the MemoryStream".  I haven't
333                         // seen anywhere mention what the maximum length of a MemoryStream is and
334                         // since we're this far this memory stream is expandable.
335                         if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
336                                 throw new ArgumentOutOfRangeException ();
337
338                         int newSize = (int) value + initialIndex;
339                         if (newSize > capacity)
340                                 Capacity = CalculateNewCapacity (newSize);
341                         else if (newSize < length)
342                                 // zeroize present data (so we don't get it 
343                                 // back if we expand the stream using Seek)
344                                 Array.Clear (internalBuffer, newSize, length - newSize);
345
346                         length = newSize;
347                         if (position > length)
348                                 position = length;
349                 }
350
351                 public virtual byte [] ToArray ()
352                 {
353                         int l = length - initialIndex;
354                         byte[] outBuffer = new byte [l];
355
356                         Buffer.BlockCopyInternal (internalBuffer, initialIndex, outBuffer, 0, l);
357                         return outBuffer; 
358                 }
359
360                 public override void Write (byte [] buffer, int offset, int count)
361                 {
362                         CheckIfClosedThrowDisposed ();
363
364                         if (!canWrite)
365                                 throw new NotSupportedException ("Cannot write to this stream.");
366
367                         if (buffer == null)
368                                 throw new ArgumentNullException ("buffer");
369                         
370                         if (offset < 0 || count < 0)
371                                 throw new ArgumentOutOfRangeException ();
372
373                         if (buffer.Length - offset < count)
374                                 throw new ArgumentException ("offset+count",
375                                                              "The size of the buffer is less than offset + count.");
376
377                         // reordered to avoid possible integer overflow
378                         if (position > capacity - count)
379                                 Capacity = CalculateNewCapacity (position + count);
380
381                         Buffer.BlockCopyInternal (buffer, offset, internalBuffer, position, count);
382                         position += count;
383                         if (position >= length)
384                                 length = position;
385                 }
386
387                 public override void WriteByte (byte value)
388                 {
389                         CheckIfClosedThrowDisposed ();
390                         if (!canWrite)
391                                 throw new NotSupportedException ("Cannot write to this stream.");
392
393                         if (position >= capacity)
394                                 Capacity = CalculateNewCapacity (position + 1);
395
396                         if (position >= length)
397                                 length = position + 1;
398
399                         internalBuffer [position++] = value;
400                 }
401
402                 public virtual void WriteTo (Stream stream)
403                 {
404                         CheckIfClosedThrowDisposed ();
405
406                         if (stream == null)
407                                 throw new ArgumentNullException ("stream");
408
409                         stream.Write (internalBuffer, initialIndex, length - initialIndex);
410                 }
411         }               
412 }