BufferSegmentStream.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using BestHTTP.PlatformSupport.Memory;
  5. namespace BestHTTP.Extensions
  6. {
  7. public class BufferSegmentStream : Stream
  8. {
  9. public override bool CanRead { get { return false; } }
  10. public override bool CanSeek { get { return false; } }
  11. public override bool CanWrite { get { return false; } }
  12. public override long Length { get { return this._length; } }
  13. protected long _length;
  14. public override long Position { get { return 0; } set { } }
  15. protected List<BufferSegment> bufferList = new List<BufferSegment>();
  16. private byte[] _tempByteArray = new byte[1];
  17. public override int ReadByte()
  18. {
  19. if (Read(this._tempByteArray, 0, 1) == 0)
  20. return -1;
  21. return this._tempByteArray[0];
  22. }
  23. public override int Read(byte[] buffer, int offset, int count)
  24. {
  25. int sumReadCount = 0;
  26. while (count > 0 && bufferList.Count > 0)
  27. {
  28. BufferSegment buff = this.bufferList[0];
  29. int readCount = Math.Min(count, buff.Count);
  30. Array.Copy(buff.Data, buff.Offset, buffer, offset, readCount);
  31. sumReadCount += readCount;
  32. offset += readCount;
  33. count -= readCount;
  34. if (readCount >= buff.Count)
  35. {
  36. this.bufferList.RemoveAt(0);
  37. BufferPool.Release(buff.Data);
  38. }
  39. else
  40. this.bufferList[0] = new BufferSegment(buff.Data, buff.Offset + readCount, buff.Count - readCount);
  41. }
  42. this._length -= sumReadCount;
  43. return sumReadCount;
  44. }
  45. public override void Write(byte[] buffer, int offset, int count)
  46. {
  47. Write(new BufferSegment(buffer, offset, count));
  48. }
  49. public virtual void Write(BufferSegment bufferSegment)
  50. {
  51. this.bufferList.Add(bufferSegment);
  52. this._length += bufferSegment.Count;
  53. }
  54. public virtual void Reset()
  55. {
  56. for (int i = 0; i < this.bufferList.Count; ++i)
  57. BufferPool.Release(this.bufferList[i]);
  58. this.bufferList.Clear();
  59. this._length = 0;
  60. }
  61. protected override void Dispose(bool disposing)
  62. {
  63. base.Dispose(disposing);
  64. this._length = 0;
  65. }
  66. public override void Flush() { }
  67. public override long Seek(long offset, SeekOrigin origin)
  68. {
  69. throw new NotImplementedException();
  70. }
  71. public override void SetLength(long value)
  72. {
  73. throw new NotImplementedException();
  74. }
  75. }
  76. }