2
0

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