BufferSegmentStream.cs 2.7 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. this.bufferList[0] = buff = buff.Slice(buff.Offset + readCount);
  35. if (buff.Count == 0)
  36. {
  37. this.bufferList.RemoveAt(0);
  38. BufferPool.Release(buff.Data);
  39. }
  40. }
  41. this._length -= sumReadCount;
  42. return sumReadCount;
  43. }
  44. public override void Write(byte[] buffer, int offset, int count)
  45. {
  46. Write(new BufferSegment(buffer, offset, count));
  47. }
  48. public virtual void Write(BufferSegment bufferSegment)
  49. {
  50. this.bufferList.Add(bufferSegment);
  51. this._length += bufferSegment.Count;
  52. }
  53. public virtual void Reset()
  54. {
  55. for (int i = 0; i < this.bufferList.Count; ++i)
  56. BufferPool.Release(this.bufferList[i]);
  57. this.bufferList.Clear();
  58. this._length = 0;
  59. }
  60. protected override void Dispose(bool disposing)
  61. {
  62. base.Dispose(disposing);
  63. Reset();
  64. }
  65. public override void Flush() { }
  66. public override long Seek(long offset, SeekOrigin origin)
  67. {
  68. throw new NotImplementedException();
  69. }
  70. public override void SetLength(long value)
  71. {
  72. throw new NotImplementedException();
  73. }
  74. }
  75. }