WriteOnlyBufferedStream.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using BestHTTP.PlatformSupport.Memory;
  2. using System;
  3. using System.IO;
  4. namespace BestHTTP.Extensions
  5. {
  6. /// <summary>
  7. /// A custom buffer stream implementation that will not close the underlying stream.
  8. /// </summary>
  9. public sealed class WriteOnlyBufferedStream : Stream
  10. {
  11. public override bool CanRead { get { return false; } }
  12. public override bool CanSeek { get { return false; } }
  13. public override bool CanWrite { get { return true; } }
  14. public override long Length { get { return this.buffer.Length; } }
  15. public override long Position { get { return this._position; } set { throw new NotImplementedException("Position set"); } }
  16. private int _position;
  17. private byte[] buffer;
  18. private Stream stream;
  19. public WriteOnlyBufferedStream(Stream stream, int bufferSize)
  20. {
  21. this.stream = stream;
  22. this.buffer = BufferPool.Get(bufferSize, true);
  23. this._position = 0;
  24. }
  25. public override void Flush()
  26. {
  27. if (this._position > 0)
  28. {
  29. this.stream.Write(this.buffer, 0, this._position);
  30. this.stream.Flush();
  31. //if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  32. // HTTPManager.Logger.Information("WriteOnlyBufferedStream", string.Format("Flushed {0:N0} bytes", this._position));
  33. this._position = 0;
  34. }
  35. }
  36. public override void Write(byte[] bufferFrom, int offset, int count)
  37. {
  38. while (count > 0)
  39. {
  40. int writeCount = Math.Min(count, this.buffer.Length - this._position);
  41. Array.Copy(bufferFrom, offset, this.buffer, this._position, writeCount);
  42. this._position += writeCount;
  43. offset += writeCount;
  44. count -= writeCount;
  45. if (this._position == this.buffer.Length)
  46. this.Flush();
  47. }
  48. }
  49. public override int Read(byte[] buffer, int offset, int count)
  50. {
  51. return 0;
  52. }
  53. public override long Seek(long offset, SeekOrigin origin)
  54. {
  55. return 0;
  56. }
  57. public override void SetLength(long value) { }
  58. protected override void Dispose(bool disposing)
  59. {
  60. base.Dispose(disposing);
  61. if (disposing && this.buffer != null)
  62. BufferPool.Release(this.buffer);
  63. this.buffer = null;
  64. }
  65. }
  66. }