BufferPoolMemoryStream.cs 15 KB

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