MemoryStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //
  2. // System.IO.MemoryStream.cs
  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. [ComVisible (true)]
  40. [MonoLimitation ("Serialization format not compatible with .NET")]
  41. public class MemoryStream : Stream
  42. {
  43. bool canWrite;
  44. bool allowGetBuffer;
  45. int capacity;
  46. int length;
  47. byte [] internalBuffer;
  48. int initialIndex;
  49. bool expandable;
  50. bool streamClosed;
  51. int position;
  52. public MemoryStream () : this (0)
  53. {
  54. }
  55. public MemoryStream (int capacity)
  56. {
  57. if (capacity < 0)
  58. throw new ArgumentOutOfRangeException ("capacity");
  59. canWrite = true;
  60. this.capacity = capacity;
  61. internalBuffer = new byte [capacity];
  62. expandable = true;
  63. allowGetBuffer = true;
  64. }
  65. public MemoryStream (byte [] buffer)
  66. {
  67. if (buffer == null)
  68. throw new ArgumentNullException ("buffer");
  69. InternalConstructor (buffer, 0, buffer.Length, true, false);
  70. }
  71. public MemoryStream (byte [] buffer, bool writable)
  72. {
  73. if (buffer == null)
  74. throw new ArgumentNullException ("buffer");
  75. InternalConstructor (buffer, 0, buffer.Length, writable, false);
  76. }
  77. public MemoryStream (byte [] buffer, int index, int count)
  78. {
  79. InternalConstructor (buffer, index, count, true, false);
  80. }
  81. public MemoryStream (byte [] buffer, int index, int count, bool writable)
  82. {
  83. InternalConstructor (buffer, index, count, writable, false);
  84. }
  85. public MemoryStream (byte [] buffer, int index, int count, bool writable, bool publiclyVisible)
  86. {
  87. InternalConstructor (buffer, index, count, writable, publiclyVisible);
  88. }
  89. void InternalConstructor (byte [] buffer, int index, int count, bool writable, bool publicallyVisible)
  90. {
  91. if (buffer == null)
  92. throw new ArgumentNullException ("buffer");
  93. if (index < 0 || count < 0)
  94. throw new ArgumentOutOfRangeException ("index or count is less than 0.");
  95. if (buffer.Length - index < count)
  96. throw new ArgumentException ("index+count",
  97. "The size of the buffer is less than index + count.");
  98. canWrite = writable;
  99. internalBuffer = buffer;
  100. capacity = count + index;
  101. length = capacity;
  102. position = index;
  103. initialIndex = index;
  104. allowGetBuffer = publicallyVisible;
  105. expandable = false;
  106. }
  107. void CheckIfClosedThrowDisposed ()
  108. {
  109. if (streamClosed)
  110. throw new ObjectDisposedException ("MemoryStream");
  111. }
  112. public override bool CanRead {
  113. get { return !streamClosed; }
  114. }
  115. public override bool CanSeek {
  116. get { return !streamClosed; }
  117. }
  118. public override bool CanWrite {
  119. get { return (!streamClosed && canWrite); }
  120. }
  121. public virtual int Capacity {
  122. get {
  123. CheckIfClosedThrowDisposed ();
  124. return capacity - initialIndex;
  125. }
  126. set {
  127. CheckIfClosedThrowDisposed ();
  128. if (value == capacity)
  129. return; // LAMENESS: see MemoryStreamTest.ConstructorFive
  130. if (!expandable)
  131. throw new NotSupportedException ("Cannot expand this MemoryStream");
  132. if (value < 0 || value < length)
  133. throw new ArgumentOutOfRangeException ("value",
  134. "New capacity cannot be negative or less than the current capacity " + value + " " + capacity);
  135. byte [] newBuffer = null;
  136. if (value != 0) {
  137. newBuffer = new byte [value];
  138. Buffer.BlockCopy (internalBuffer, 0, newBuffer, 0, length);
  139. }
  140. internalBuffer = newBuffer; // It's null when capacity is set to 0
  141. capacity = value;
  142. }
  143. }
  144. public override long Length {
  145. get {
  146. // LAMESPEC: The spec says to throw an IOException if the
  147. // stream is closed and an ObjectDisposedException if
  148. // "methods were called after the stream was closed". What
  149. // is the difference?
  150. CheckIfClosedThrowDisposed ();
  151. // This is ok for MemoryStreamTest.ConstructorFive
  152. return length - initialIndex;
  153. }
  154. }
  155. public override long Position {
  156. get {
  157. CheckIfClosedThrowDisposed ();
  158. return position - initialIndex;
  159. }
  160. set {
  161. CheckIfClosedThrowDisposed ();
  162. if (value < 0)
  163. throw new ArgumentOutOfRangeException ("value",
  164. "Position cannot be negative" );
  165. if (value > Int32.MaxValue)
  166. throw new ArgumentOutOfRangeException ("value",
  167. "Position must be non-negative and less than 2^31 - 1 - origin");
  168. position = initialIndex + (int) value;
  169. }
  170. }
  171. protected override void Dispose (bool disposing)
  172. {
  173. streamClosed = true;
  174. expandable = false;
  175. }
  176. public override void Flush ()
  177. {
  178. // Do nothing
  179. }
  180. public virtual byte [] GetBuffer ()
  181. {
  182. if (!allowGetBuffer)
  183. throw new UnauthorizedAccessException ();
  184. return internalBuffer;
  185. }
  186. public override int Read ([In,Out] byte [] buffer, int offset, int count)
  187. {
  188. CheckIfClosedThrowDisposed ();
  189. if (buffer == null)
  190. throw new ArgumentNullException ("buffer");
  191. if (offset < 0 || count < 0)
  192. throw new ArgumentOutOfRangeException ("offset or count less than zero.");
  193. if (buffer.Length - offset < count )
  194. throw new ArgumentException ("offset+count",
  195. "The size of the buffer is less than offset + count.");
  196. if (position >= length || count == 0)
  197. return 0;
  198. if (position > length - count)
  199. count = length - position;
  200. Buffer.BlockCopy (internalBuffer, position, buffer, offset, count);
  201. position += count;
  202. return count;
  203. }
  204. public override int ReadByte ()
  205. {
  206. CheckIfClosedThrowDisposed ();
  207. if (position >= length)
  208. return -1;
  209. return internalBuffer [position++];
  210. }
  211. public override long Seek (long offset, SeekOrigin loc)
  212. {
  213. CheckIfClosedThrowDisposed ();
  214. // It's funny that they don't throw this exception for < Int32.MinValue
  215. if (offset > (long) Int32.MaxValue)
  216. throw new ArgumentOutOfRangeException ("Offset out of range. " + offset);
  217. int refPoint;
  218. switch (loc) {
  219. case SeekOrigin.Begin:
  220. if (offset < 0)
  221. throw new IOException ("Attempted to seek before start of MemoryStream.");
  222. refPoint = initialIndex;
  223. break;
  224. case SeekOrigin.Current:
  225. refPoint = position;
  226. break;
  227. case SeekOrigin.End:
  228. refPoint = length;
  229. break;
  230. default:
  231. throw new ArgumentException ("loc", "Invalid SeekOrigin");
  232. }
  233. // LAMESPEC: My goodness, how may LAMESPECs are there in this
  234. // class! :) In the spec for the Position property it's stated
  235. // "The position must not be more than one byte beyond the end of the stream."
  236. // In the spec for seek it says "Seeking to any location beyond the length of the
  237. // stream is supported." That's a contradiction i'd say.
  238. // I guess seek can go anywhere but if you use position it may get moved back.
  239. refPoint += (int) offset;
  240. if (refPoint < initialIndex)
  241. throw new IOException ("Attempted to seek before start of MemoryStream.");
  242. position = refPoint;
  243. return position;
  244. }
  245. int CalculateNewCapacity (int minimum)
  246. {
  247. if (minimum < 256)
  248. minimum = 256; // See GetBufferTwo test
  249. if (minimum < capacity * 2)
  250. minimum = capacity * 2;
  251. return minimum;
  252. }
  253. public override void SetLength (long value)
  254. {
  255. if (!expandable && value > capacity)
  256. throw new NotSupportedException ("Expanding this MemoryStream is not supported");
  257. CheckIfClosedThrowDisposed ();
  258. if (!canWrite) {
  259. throw new NotSupportedException (Locale.GetText
  260. ("Cannot write to this MemoryStream"));
  261. }
  262. // LAMESPEC: AGAIN! It says to throw this exception if value is
  263. // greater than "the maximum length of the MemoryStream". I haven't
  264. // seen anywhere mention what the maximum length of a MemoryStream is and
  265. // since we're this far this memory stream is expandable.
  266. if (value < 0 || (value + initialIndex) > (long) Int32.MaxValue)
  267. throw new ArgumentOutOfRangeException ();
  268. int newSize = (int) value + initialIndex;
  269. if (newSize > capacity)
  270. Capacity = CalculateNewCapacity (newSize);
  271. else if (newSize < length)
  272. // zeroize present data (so we don't get it
  273. // back if we expand the stream using Seek)
  274. Array.Clear (internalBuffer, newSize, length - newSize);
  275. length = newSize;
  276. if (position > length)
  277. position = length;
  278. }
  279. public virtual byte [] ToArray ()
  280. {
  281. int l = length - initialIndex;
  282. byte[] outBuffer = new byte [l];
  283. if (internalBuffer != null)
  284. Buffer.BlockCopy (internalBuffer, initialIndex, outBuffer, 0, l);
  285. return outBuffer;
  286. }
  287. public override void Write (byte [] buffer, int offset, int count)
  288. {
  289. CheckIfClosedThrowDisposed ();
  290. if (!canWrite)
  291. throw new NotSupportedException ("Cannot write to this stream.");
  292. if (buffer == null)
  293. throw new ArgumentNullException ("buffer");
  294. if (offset < 0 || count < 0)
  295. throw new ArgumentOutOfRangeException ();
  296. if (buffer.Length - offset < count)
  297. throw new ArgumentException ("offset+count",
  298. "The size of the buffer is less than offset + count.");
  299. // reordered to avoid possible integer overflow
  300. if (position > capacity - count)
  301. Capacity = CalculateNewCapacity (position + count);
  302. Buffer.BlockCopy (buffer, offset, internalBuffer, position, count);
  303. position += count;
  304. if (position >= length)
  305. length = position;
  306. }
  307. public override void WriteByte (byte value)
  308. {
  309. CheckIfClosedThrowDisposed ();
  310. if (!canWrite)
  311. throw new NotSupportedException ("Cannot write to this stream.");
  312. if (position >= capacity)
  313. Capacity = CalculateNewCapacity (position + 1);
  314. if (position >= length)
  315. length = position + 1;
  316. internalBuffer [position++] = value;
  317. }
  318. public virtual void WriteTo (Stream stream)
  319. {
  320. CheckIfClosedThrowDisposed ();
  321. if (stream == null)
  322. throw new ArgumentNullException ("stream");
  323. stream.Write (internalBuffer, initialIndex, length - initialIndex);
  324. }
  325. #if NET_4_0
  326. public override void ObjectInvariant ()
  327. {
  328. }
  329. #endif
  330. }
  331. }