gajda-ltd

PipeStream

Mar 10th, 2016
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.91 KB | None | 0 0
  1. namespace Core
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Threading;
  7.  
  8. /// <summary>
  9. /// PipeStream is a thread-safe read/write data stream for use between two threads in a
  10. /// single-producer/single-consumer type problem.
  11. /// </summary>
  12. /// <version>2014/12/15 1.2</version>
  13. /// <remarks>2006/10/13 1.0 - initial version.</remarks>
  14. /// <remarks>Update on 2008/10/9 1.1 - uses Monitor instead of Manual Reset events for more elegant synchronicity.</remarks>
  15. /// <remarks>Update on 2014/12/15 1.2 - bugfix for read method not using offset - thanks JοΏ½rgen Sigvardsson, replace NotImplementedExceptions with NotSupportedException</remarks>
  16. /// <license>
  17. /// Copyright (c) 2006 James Kolpack (james dot kolpack at google mail)
  18. ///
  19. /// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  20. /// associated documentation files (the "Software"), to deal in the Software without restriction,
  21. /// including without limitation the rights to use, copy, modify, merge, publish, distribute,
  22. /// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  23. /// furnished to do so, subject to the following conditions:
  24. ///
  25. /// The above copyright notice and this permission notice shall be included in all copies or
  26. /// substantial portions of the Software.
  27. ///
  28. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  29. /// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  30. /// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  31. /// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
  32. /// OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  33. /// OTHER DEALINGS IN THE SOFTWARE.
  34. /// </license>
  35. public class PipeStream : Stream
  36. {
  37. #region Private members
  38.  
  39. /// <summary>
  40. /// Queue of bytes provides the datastructure for transmitting from an
  41. /// input stream to an output stream.
  42. /// </summary>
  43. /// <remarks>Possible more effecient ways to accomplish this.</remarks>
  44. private readonly Queue<byte> mBuffer = new Queue<byte>();
  45.  
  46. /// <summary>
  47. /// Indicates that the input stream has been flushed and that
  48. /// all remaining data should be written to the output stream.
  49. /// </summary>
  50. private bool mFlushed;
  51.  
  52. /// <summary>
  53. /// Maximum number of bytes to store in the buffer.
  54. /// </summary>
  55. private long mMaxBufferLength = 200 * MB;
  56.  
  57. /// <summary>
  58. /// Setting this to true will cause Read() to block if it appears
  59. /// that it will run out of data.
  60. /// </summary>
  61. private bool mBlockLastRead;
  62.  
  63. #endregion
  64.  
  65. #region Public Const members
  66.  
  67. /// <summary>
  68. /// Number of bytes in a kilobyte
  69. /// </summary>
  70. public const long KB = 1024;
  71.  
  72. /// <summary>
  73. /// Number of bytes in a megabyte
  74. /// </summary>
  75. public const long MB = KB * 1024;
  76.  
  77. #endregion
  78.  
  79. #region Public properties
  80.  
  81. /// <summary>
  82. /// Gets or sets the maximum number of bytes to store in the buffer.
  83. /// </summary>
  84. /// <value>The length of the max buffer.</value>
  85. public long MaxBufferLength
  86. {
  87. get
  88. {
  89. return this.mMaxBufferLength;
  90. }
  91. set
  92. {
  93. this.mMaxBufferLength = value;
  94. }
  95. }
  96.  
  97. /// <summary>
  98. /// Gets or sets a value indicating whether to block last read method before the buffer is empty.
  99. /// When true, Read() will block until it can fill the passed in buffer and count.
  100. /// When false, Read() will not block, returning all the available buffer data.
  101. /// </summary>
  102. /// <remarks>
  103. /// Setting to true will remove the possibility of ending a stream reader prematurely.
  104. /// </remarks>
  105. /// <value>
  106. /// <c>true</c> if block last read method before the buffer is empty; otherwise, <c>false</c>.
  107. /// </value>
  108. public bool BlockLastReadBuffer
  109. {
  110. get
  111. {
  112. return this.mBlockLastRead;
  113. }
  114. set
  115. {
  116. this.mBlockLastRead = value;
  117.  
  118. // when turning off the block last read, signal Read() that it may now read the rest of the buffer.
  119. if (!this.mBlockLastRead) lock (this.mBuffer) Monitor.Pulse(this.mBuffer);
  120. }
  121. }
  122.  
  123. #endregion
  124.  
  125. #region Stream overide methods
  126.  
  127. ///<summary>
  128. ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  129. ///</summary>
  130. ///<filterpriority>2</filterpriority>
  131. public new void Dispose()
  132. {
  133. // clear the internal buffer
  134. this.mBuffer.Clear();
  135. }
  136.  
  137. ///<summary>
  138. ///When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
  139. ///</summary>
  140. ///
  141. ///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception><filterpriority>2</filterpriority>
  142. public override void Flush()
  143. {
  144. this.mFlushed = true;
  145. lock (this.mBuffer) Monitor.Pulse(this.mBuffer);
  146. }
  147.  
  148. ///<summary>
  149. ///When overridden in a derived class, sets the position within the current stream.
  150. ///</summary>
  151. ///<returns>
  152. ///The new position within the current stream.
  153. ///</returns>
  154. ///<param name="offset">A byte offset relative to the origin parameter. </param>
  155. ///<param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"></see> indicating the reference point used to obtain the new position. </param>
  156. ///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  157. ///<exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
  158. ///<exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>
  159. public override long Seek(long offset, SeekOrigin origin)
  160. {
  161. throw new NotSupportedException();
  162. }
  163.  
  164. ///<summary>
  165. ///When overridden in a derived class, sets the length of the current stream.
  166. ///</summary>
  167. ///<param name="value">The desired length of the current stream in bytes. </param>
  168. ///<exception cref="T:System.NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception>
  169. ///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  170. ///<exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception><filterpriority>2</filterpriority>
  171. public override void SetLength(long value)
  172. {
  173. throw new NotSupportedException();
  174. }
  175.  
  176.  
  177. ///<summary>
  178. ///When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
  179. ///</summary>
  180. ///<returns>
  181. ///The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
  182. ///</returns>
  183. ///<param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param>
  184. ///<param name="count">The maximum number of bytes to be read from the current stream. </param>
  185. ///<param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. </param>
  186. ///<exception cref="T:System.ArgumentException">The sum of offset and count is larger than the buffer length. </exception>
  187. ///<exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  188. ///<exception cref="T:System.NotSupportedException">The stream does not support reading. </exception>
  189. ///<exception cref="T:System.ArgumentNullException">buffer is null. </exception>
  190. ///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  191. ///<exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception><filterpriority>1</filterpriority>
  192. public override int Read(byte[] buffer, int offset, int count)
  193. {
  194. if (offset != 0) throw new NotSupportedException("Offsets with value of non-zero are not supported");
  195. if (buffer == null) throw new ArgumentException("Buffer is null");
  196. if (offset + count > buffer.Length) throw new ArgumentException("The sum of offset and count is greater than the buffer length. ");
  197. if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException("offset", "offset or count is negative.");
  198. if (this.BlockLastReadBuffer && count >= this.mMaxBufferLength)
  199. throw new ArgumentException(
  200. string.Format("count({0}) > mMaxBufferLength({1})", count, this.mMaxBufferLength));
  201.  
  202. if (count == 0) return 0;
  203.  
  204. int readLength = 0;
  205.  
  206. lock (this.mBuffer)
  207. {
  208. while (!this.ReadAvailable(count)) Monitor.Wait(this.mBuffer);
  209.  
  210. // fill the read buffer
  211. for (; readLength < count && this.Length > 0; readLength++)
  212. {
  213. buffer[offset + readLength] = this.mBuffer.Dequeue();
  214. }
  215.  
  216. Monitor.Pulse(this.mBuffer);
  217. }
  218. return readLength;
  219. }
  220.  
  221. /// <summary>
  222. /// Returns true if there are
  223. /// </summary>
  224. /// <param name="count"></param>
  225. /// <returns></returns>
  226. private bool ReadAvailable(int count)
  227. {
  228. return (this.Length >= count || this.mFlushed) && (this.Length >= (count + 1) || !this.BlockLastReadBuffer);
  229. }
  230.  
  231. ///<summary>
  232. ///When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  233. ///</summary>
  234. ///<param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream. </param>
  235. ///<param name="count">The number of bytes to be written to the current stream. </param>
  236. ///<param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream. </param>
  237. ///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  238. ///<exception cref="T:System.NotSupportedException">The stream does not support writing. </exception>
  239. ///<exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  240. ///<exception cref="T:System.ArgumentNullException">buffer is null. </exception>
  241. ///<exception cref="T:System.ArgumentException">The sum of offset and count is greater than the buffer length. </exception>
  242. ///<exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception><filterpriority>1</filterpriority>
  243. public override void Write(byte[] buffer, int offset, int count)
  244. {
  245. if (buffer == null) throw new ArgumentException("Buffer is null");
  246. if (offset + count > buffer.Length) throw new ArgumentException("The sum of offset and count is greater than the buffer length. ");
  247. if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException("offset", "offset or count is negative.");
  248. if (count == 0) return;
  249.  
  250. lock (this.mBuffer)
  251. {
  252. // wait until the buffer isn't full
  253. while (this.Length >= this.mMaxBufferLength) Monitor.Wait(this.mBuffer);
  254.  
  255. this.mFlushed = false; // if it were flushed before, it soon will not be.
  256.  
  257. // queue up the buffer data
  258. for (int i = offset; i < offset + count; i++)
  259. {
  260. this.mBuffer.Enqueue(buffer[i]);
  261. }
  262.  
  263. Monitor.Pulse(this.mBuffer); // signal that write has occured
  264. }
  265. }
  266.  
  267. ///<summary>
  268. ///When overridden in a derived class, gets a value indicating whether the current stream supports reading.
  269. ///</summary>
  270. ///<returns>
  271. ///true if the stream supports reading; otherwise, false.
  272. ///</returns>
  273. ///<filterpriority>1</filterpriority>
  274. public override bool CanRead
  275. {
  276. get
  277. {
  278. return true;
  279. }
  280. }
  281.  
  282. ///<summary>
  283. ///When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
  284. ///</summary>
  285. ///<returns>
  286. ///true if the stream supports seeking; otherwise, false.
  287. ///</returns>
  288. ///<filterpriority>1</filterpriority>
  289. public override bool CanSeek
  290. {
  291. get
  292. {
  293. return false;
  294. }
  295. }
  296.  
  297. ///<summary>
  298. ///When overridden in a derived class, gets a value indicating whether the current stream supports writing.
  299. ///</summary>
  300. ///<returns>
  301. ///true if the stream supports writing; otherwise, false.
  302. ///</returns>
  303. ///<filterpriority>1</filterpriority>
  304. public override bool CanWrite
  305. {
  306. get
  307. {
  308. return true;
  309. }
  310. }
  311.  
  312. ///<summary>
  313. ///When overridden in a derived class, gets the length in bytes of the stream.
  314. ///</summary>
  315. ///<returns>
  316. ///A long value representing the length of the stream in bytes.
  317. ///</returns>
  318. ///
  319. ///<exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception>
  320. ///<exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>
  321. public override long Length
  322. {
  323. get
  324. {
  325. return this.mBuffer.Count;
  326. }
  327. }
  328.  
  329. ///<summary>
  330. ///When overridden in a derived class, gets or sets the position within the current stream.
  331. ///</summary>
  332. ///<returns>
  333. ///The current position within the stream.
  334. ///</returns>
  335. ///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  336. ///<exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception>
  337. ///<exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>
  338. public override long Position
  339. {
  340. get
  341. {
  342. return 0;
  343. }
  344. set
  345. {
  346. throw new NotSupportedException();
  347. }
  348. }
  349.  
  350. #endregion
  351. }
  352. }
Add Comment
Please, Sign In to add comment