TBuffer.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 LinkedList<byte[]> buffer = new LinkedList<byte[]>();
  9. private int writeIndex;
  10. private int readIndex;
  11. public int Count
  12. {
  13. get
  14. {
  15. if (buffer.Count == 0)
  16. {
  17. return 0;
  18. }
  19. return (buffer.Count - 1) * chunkSize + writeIndex - readIndex;
  20. }
  21. }
  22. public byte[] ReadFrom(int n)
  23. {
  24. if (this.Count < n || n <= 0)
  25. {
  26. throw new Exception(string.Format("buffer size < n, buffer: {0} n: {1}", this.Count, n));
  27. }
  28. byte[] bytes = new byte[n];
  29. int alreadyCopyCount = n;
  30. while (alreadyCopyCount < n)
  31. {
  32. if (chunkSize - readIndex > n - alreadyCopyCount)
  33. {
  34. Array.Copy(buffer.First.Value, readIndex, bytes, alreadyCopyCount, n - alreadyCopyCount);
  35. readIndex += n - alreadyCopyCount;
  36. alreadyCopyCount = n;
  37. }
  38. else
  39. {
  40. Array.Copy(buffer.First.Value, readIndex, bytes, alreadyCopyCount, chunkSize - readIndex);
  41. alreadyCopyCount += chunkSize - readIndex;
  42. readIndex = 0;
  43. this.buffer.RemoveFirst();
  44. }
  45. }
  46. return bytes;
  47. }
  48. public void WriteTo(byte[] bytes)
  49. {
  50. int alreadyCopyCount = 0;
  51. while (alreadyCopyCount < bytes.Length)
  52. {
  53. if (writeIndex == 0)
  54. {
  55. this.buffer.AddLast(new byte[chunkSize]);
  56. }
  57. if (chunkSize - writeIndex > alreadyCopyCount)
  58. {
  59. Array.Copy(bytes, alreadyCopyCount, buffer.Last.Value, writeIndex, alreadyCopyCount);
  60. writeIndex += alreadyCopyCount;
  61. alreadyCopyCount = 0;
  62. }
  63. else
  64. {
  65. Array.Copy(bytes, alreadyCopyCount, buffer.Last.Value, writeIndex, chunkSize - writeIndex);
  66. alreadyCopyCount -= chunkSize - writeIndex;
  67. writeIndex = 0;
  68. }
  69. }
  70. }
  71. }
  72. }