MemoryStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. //
  2. // System.IO.MemoryStream
  3. //
  4. // Authors: Marcin Szczepanski ([email protected])
  5. // Patrik Torstensson
  6. // Gonzalo Paniagua Javier ([email protected])
  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. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  14. //
  15. // Permission is hereby granted, free of charge, to any person obtaining
  16. // a copy of this software and associated documentation files (the
  17. // "Software"), to deal in the Software without restriction, including
  18. // without limitation the rights to use, copy, modify, merge, publish,
  19. // distribute, sublicense, and/or sell copies of the Software, and to
  20. // permit persons to whom the Software is furnished to do so, subject to
  21. // the following conditions:
  22. //
  23. // The above copyright notice and this permission notice shall be
  24. // included in all copies or substantial portions of the Software.
  25. //
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  33. //
  34. using System.Globalization;
  35. using System.Runtime.InteropServices;
  36. namespace System.IO
  37. {
  38. [Serializable]
  39. #if NET_2_0
  40. [ComVisible (true)]
  41. #endif
  42. [MonoTODO ("Serialization format not compatible with .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. public MemoryStream () : this (0)
  55. {
  56. }
  57. public MemoryStream (int capacity)
  58. {
  59. if (capacity < 0)
  60. throw new ArgumentOutOfRangeException ("capacity");
  61. canWrite = true;
  62. this.capacity = capacity;
  63. internalBuffer = new byte [capacity];
  64. expandable = true;
  65. allowGetBuffer = true;
  66. }
  67. public MemoryStream (byte [] buffer)
  68. {
  69. if (buffer == null)
  70. throw new ArgumentNullException ("buffer");
  71. InternalConstructor (buffer, 0, buffer.Length, true, false);
  72. }
  73. public MemoryStream (byte [] buffer, bool writeable)
  74. {
  75. if (buffer == null)
  76. throw new ArgumentNullException ("buffer");
  77. InternalConstructor (buffer, 0, buffer.Length, writeable, false);
  78. }
  79. public MemoryStream (byte [] buffer, int index, int count)
  80. {
  81. InternalConstructor (buffer, index, count, true, false);
  82. }
  83. public MemoryStream (byte [] buffer, int index, int count, bool writeable)
  84. {
  85. InternalConstructor (buffer, index, count, writeable, false);
  86. }
  87. public MemoryStream (byte [] buffer, int index, int count, bool writeable, bool publicallyVisible)
  88. {
  89. InternalConstructor (buffer, index, count, writeable, publicallyVisible);
  90. }
  91. void InternalConstructor (byte [] buffer, int index, int count, bool writeable, bool publicallyVisible)
  92. {
  93. if (buffer == null)
  94. throw new ArgumentNullException ("buffer");
  95. if (index < 0 || count < 0)
  96. throw new ArgumentOutOfRangeException ("index or count is less than 0.");
  97. if (buffer.Length - index < count)
  98. throw new ArgumentException ("index+count",
  99. "The size of the buffer is less than index + count.");
  100. canWrite = writeable;
  101. internalBuffer = buffer;
  102. capacity = count + index;
  103. length = capacity;
  104. position = index;
  105. initialIndex = index;
  106. allowGetBuffer = publicallyVisible;
  107. expandable = false;
  108. }
  109. void CheckIfClosedThrowDisposed ()
  110. {
  111. if (streamClosed)
  112. throw new ObjectDisposedException ("MemoryStream");
  113. }
  114. void CheckIfClosedThrowIO ()
  115. {
  116. if (streamClosed)
  117. throw new IOException ("MemoryStream is closed");
  118. }
  119. public override bool CanRead {
  120. get { return !streamClosed; }
  121. }
  122. public override bool CanSeek {
  123. get { return !streamClosed; }
  124. }
  125. public override bool CanWrite {
  126. get { return (!streamClosed && canWrite); }
  127. }
  128. public virtual int Capacity {
  129. get {
  130. CheckIfClosedThrowDisposed ();
  131. return capacity - initialIndex;
  132. }
  133. set {
  134. CheckIfClosedThrowDisposed ();
  135. if (value == capacity)
  136. return; // LAMENESS: see MemoryStreamTest.ConstructorFive
  137. if (!expandable)
  138. throw new NotSupportedException ("Cannot expand this MemoryStream");
  139. if (value < 0 || value < length)
  140. throw new ArgumentOutOfRangeException ("value",
  141. "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
  142. byte [] newBuffer = null;
  143. if (value != 0) {
  144. newBuffer = new byte [value];
  145. Buffer.BlockCopyInternal (internalBuffer, 0, newBuffer, 0, length);
  146. }
  147. internalBuffer = newBuffer; // It's null when capacity is set to 0
  148. capacity = value;
  149. }
  150. }
  151. public override long Length {
  152. get {
  153. // LAMESPEC: The spec says to throw an IOException if the
  154. // stream is closed and an ObjectDisposedException if
  155. // "methods were called after the stream was closed". What
  156. // is the difference?
  157. CheckIfClosedThrowDisposed ();
  158. // This is ok for MemoryStreamTest.ConstructorFive
  159. return length - initialIndex;
  160. }
  161. }
  162. public override long Position {
  163. get {
  164. CheckIfClosedThrowDisposed ();
  165. return position - initialIndex;
  166. }
  167. set {
  168. CheckIfClosedThrowDisposed ();
  169. if (value < 0)
  170. throw new ArgumentOutOfRangeException ("value",
  171. "Position cannot be negative" );
  172. if (value > Int32.MaxValue)
  173. throw new ArgumentOutOfRangeException ("value",
  174. "Position must be non-negative and less than 2^31 - 1 - origin");
  175. position = initialIndex + (int) value;
  176. }
  177. }
  178. public override void Close ()
  179. {
  180. streamClosed = true;
  181. expandable = false;
  182. }
  183. public override void Flush ()
  184. {
  185. // Do nothing
  186. }
  187. public virtual byte [] GetBuffer ()
  188. {
  189. if (!allowGetBuffer)
  190. throw new UnauthorizedAccessException ();
  191. return internalBuffer;
  192. }
  193. public override int Read ([In,Out] byte [] buffer, int offset, int count)
  194. {
  195. CheckIfClosedThrowDisposed ();
  196. if (buffer == null)
  197. throw new ArgumentNullException ("buffer");
  198. if (offset < 0 || count < 0)
  199. throw new ArgumentOutOfRangeException ("offset or count less than zero.");
  200. if (buffer.Length - offset < count )
  201. throw new ArgumentException ("offset+count",
  202. "The size of the buffer is less than offset + count.");
  203. if (position >= length || count == 0)
  204. return 0;
  205. if (position > length - count)
  206. count = length - position;
  207. Buffer.BlockCopyInternal (internalBuffer, position, buffer, offset, count);
  208. position += count;
  209. return count;
  210. }
  211. public override int ReadByte ()
  212. {
  213. CheckIfClosedThrowDisposed ();
  214. if (position >= length)
  215. return -1;
  216. return internalBuffer [position++];
  217. }
  218. public override long Seek (long offset, SeekOrigin loc)
  219. {
  220. CheckIfClosedThrowDisposed ();
  221. // It's funny that they don't throw this exception for < Int32.MinValue
  222. if (offset > (long) Int32.MaxValue)
  223. throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
  224. int refPoint;
  225. switch (loc) {
  226. case SeekOrigin.Begin:
  227. if (offset < 0)
  228. throw new IOException ("Attempted to seek before start of MemoryStream.");
  229. refPoint = initialIndex;
  230. break;
  231. case SeekOrigin.Current:
  232. refPoint = position;
  233. break;
  234. case SeekOrigin.End:
  235. refPoint = length;
  236. break;
  237. default:
  238. throw new ArgumentException ("loc", "Invalid SeekOrigin");
  239. }
  240. // LAMESPEC: My goodness, how may LAMESPECs are there in this
  241. // class! :) In the spec for the Position property it's stated
  242. // "The position must not be more than one byte beyond the end of the stream."
  243. // In the spec for seek it says "Seeking to any location beyond the length of the
  244. // stream is supported." That's a contradiction i'd say.
  245. // I guess seek can go anywhere but if you use position it may get moved back.
  246. refPoint += (int) offset;
  247. if (refPoint < initialIndex)
  248. throw new IOException ("Attempted to seek before start of MemoryStream.");
  249. position = refPoint;
  250. return position;
  251. }
  252. int CalculateNewCapacity (int minimum)
  253. {
  254. if (minimum < 256)
  255. minimum = 256; // See GetBufferTwo test
  256. if (minimum < capacity * 2)
  257. minimum = capacity * 2;
  258. return minimum;
  259. }
  260. public override void SetLength (long value)
  261. {
  262. if (!expandable && value > capacity)
  263. throw new NotSupportedException ("Expanding this MemoryStream is not supported");
  264. CheckIfClosedThrowDisposed ();
  265. if (!canWrite) {
  266. throw new NotSupportedException (Locale.GetText
  267. ("Cannot write to this MemoryStream"));
  268. }
  269. // LAMESPEC: AGAIN! It says to throw this exception if value is
  270. // greater than "the maximum length of the MemoryStream". I haven't
  271. // seen anywhere mention what the maximum length of a MemoryStream is and
  272. // since we're this far this memory stream is expandable.
  273. if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
  274. throw new ArgumentOutOfRangeException ();
  275. int newSize = (int) value + initialIndex;
  276. if (newSize > capacity)
  277. Capacity = CalculateNewCapacity (newSize);
  278. else if (newSize < length)
  279. // zeroize present data (so we don't get it
  280. // back if we expand the stream using Seek)
  281. Array.Clear (internalBuffer, newSize, length - newSize);
  282. length = newSize;
  283. if (position > length)
  284. position = length;
  285. }
  286. public virtual byte [] ToArray ()
  287. {
  288. int l = length - initialIndex;
  289. byte[] outBuffer = new byte [l];
  290. Buffer.BlockCopyInternal (internalBuffer, initialIndex, outBuffer, 0, l);
  291. return outBuffer;
  292. }
  293. public override void Write (byte [] buffer, int offset, int count)
  294. {
  295. CheckIfClosedThrowDisposed ();
  296. if (!canWrite)
  297. throw new NotSupportedException ("Cannot write to this stream.");
  298. if (buffer == null)
  299. throw new ArgumentNullException ("buffer");
  300. if (offset < 0 || count < 0)
  301. throw new ArgumentOutOfRangeException ();
  302. if (buffer.Length - offset < count)
  303. throw new ArgumentException ("offset+count",
  304. "The size of the buffer is less than offset + count.");
  305. // reordered to avoid possible integer overflow
  306. if (position > capacity - count)
  307. Capacity = CalculateNewCapacity (position + count);
  308. Buffer.BlockCopyInternal (buffer, offset, internalBuffer, position, count);
  309. position += count;
  310. if (position >= length)
  311. length = position;
  312. }
  313. public override void WriteByte (byte value)
  314. {
  315. CheckIfClosedThrowDisposed ();
  316. if (!canWrite)
  317. throw new NotSupportedException ("Cannot write to this stream.");
  318. if (position >= capacity)
  319. Capacity = CalculateNewCapacity (position + 1);
  320. if (position >= length)
  321. length = position + 1;
  322. internalBuffer [position++] = value;
  323. }
  324. public virtual void WriteTo (Stream stream)
  325. {
  326. CheckIfClosedThrowDisposed ();
  327. if (stream == null)
  328. throw new ArgumentNullException ("stream");
  329. stream.Write (internalBuffer, initialIndex, length - initialIndex);
  330. }
  331. }
  332. }