TBuffer.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Collections.Generic;
  3. namespace TNet
  4. {
  5. public class TBuffer
  6. {
  7. public const int ChunkSize = 8096;
  8. private readonly LinkedList<byte[]> bufferList = new LinkedList<byte[]>();
  9. public int LastIndex { get; set; }
  10. public int FirstIndex { get; set; }
  11. public int Count
  12. {
  13. get
  14. {
  15. if (this.bufferList.Count == 0)
  16. {
  17. return 0;
  18. }
  19. return (this.bufferList.Count - 1) * ChunkSize + this.LastIndex - this.FirstIndex;
  20. }
  21. }
  22. public void AddLast()
  23. {
  24. this.bufferList.AddLast(new byte[ChunkSize]);
  25. }
  26. public void RemoveFirst()
  27. {
  28. this.bufferList.RemoveFirst();
  29. }
  30. public byte[] First
  31. {
  32. get
  33. {
  34. return this.bufferList.First.Value;
  35. }
  36. }
  37. public byte[] Last
  38. {
  39. get
  40. {
  41. return this.bufferList.Last.Value;
  42. }
  43. }
  44. public void RecvFrom(byte[] buffer)
  45. {
  46. int n = buffer.Length;
  47. if (this.Count < n || n <= 0)
  48. {
  49. throw new Exception(string.Format("bufferList size < n, bufferList: {0} n: {1}", this.Count, n));
  50. }
  51. int alreadyCopyCount = n;
  52. while (alreadyCopyCount < n)
  53. {
  54. if (ChunkSize - this.FirstIndex > n - alreadyCopyCount)
  55. {
  56. Array.Copy(this.bufferList.First.Value, this.FirstIndex, buffer, alreadyCopyCount,
  57. n - alreadyCopyCount);
  58. this.FirstIndex += n - alreadyCopyCount;
  59. alreadyCopyCount = n;
  60. }
  61. else
  62. {
  63. Array.Copy(this.bufferList.First.Value, this.FirstIndex, buffer, alreadyCopyCount,
  64. ChunkSize - this.FirstIndex);
  65. alreadyCopyCount += ChunkSize - this.FirstIndex;
  66. this.FirstIndex = 0;
  67. this.bufferList.RemoveFirst();
  68. }
  69. }
  70. }
  71. public void SendTo(byte[] buffer)
  72. {
  73. int alreadyCopyCount = 0;
  74. while (alreadyCopyCount < buffer.Length)
  75. {
  76. if (this.LastIndex == 0)
  77. {
  78. this.bufferList.AddLast(new byte[ChunkSize]);
  79. }
  80. if (ChunkSize - this.LastIndex > alreadyCopyCount)
  81. {
  82. Array.Copy(buffer, alreadyCopyCount, this.bufferList.Last.Value, this.LastIndex, alreadyCopyCount);
  83. this.LastIndex += alreadyCopyCount;
  84. alreadyCopyCount = 0;
  85. }
  86. else
  87. {
  88. Array.Copy(buffer, alreadyCopyCount, this.bufferList.Last.Value, this.LastIndex,
  89. ChunkSize - this.LastIndex);
  90. alreadyCopyCount -= ChunkSize - this.LastIndex;
  91. this.LastIndex = 0;
  92. }
  93. }
  94. }
  95. }
  96. }