Segment.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.IO;
  2. namespace kcp2k
  3. {
  4. // KCP Segment Definition
  5. internal class Segment
  6. {
  7. internal uint conv; // conversation
  8. internal uint cmd; // command, e.g. Kcp.CMD_ACK etc.
  9. internal uint frg; // fragment
  10. internal uint wnd; // window size that the receive can currently receive
  11. internal uint ts; // timestamp
  12. internal uint sn; // serial number
  13. internal uint una;
  14. internal uint resendts; // resend timestamp
  15. internal int rto;
  16. internal uint fastack;
  17. internal uint xmit;
  18. // we need an auto scaling byte[] with a WriteBytes function.
  19. // MemoryStream does that perfectly, no need to reinvent the wheel.
  20. // note: no need to pool it, because Segment is already pooled.
  21. // -> MTU as initial capacity to avoid most runtime resizing/allocations
  22. internal MemoryStream data = new MemoryStream(Kcp.MTU_DEF);
  23. // ikcp_encode_seg
  24. // encode a segment into buffer
  25. internal int Encode(byte[] ptr, int offset)
  26. {
  27. int offset_ = offset;
  28. offset += Utils.Encode32U(ptr, offset, conv);
  29. offset += Utils.Encode8u(ptr, offset, (byte)cmd);
  30. offset += Utils.Encode8u(ptr, offset, (byte)frg);
  31. offset += Utils.Encode16U(ptr, offset, (ushort)wnd);
  32. offset += Utils.Encode32U(ptr, offset, ts);
  33. offset += Utils.Encode32U(ptr, offset, sn);
  34. offset += Utils.Encode32U(ptr, offset, una);
  35. offset += Utils.Encode32U(ptr, offset, (uint)data.Position);
  36. return offset - offset_;
  37. }
  38. // reset to return a fresh segment to the pool
  39. internal void Reset()
  40. {
  41. conv = 0;
  42. cmd = 0;
  43. frg = 0;
  44. wnd = 0;
  45. ts = 0;
  46. sn = 0;
  47. una = 0;
  48. rto = 0;
  49. xmit = 0;
  50. resendts = 0;
  51. fastack = 0;
  52. // keep buffer for next pool usage, but reset length (= bytes written)
  53. data.SetLength(0);
  54. }
  55. }
  56. }