Segment.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 (sent as 1 byte)
  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; // retransmit count
  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. // IMPORTANT kcp encodes 'frg' as 1 byte.
  31. // so we can only support up to 255 fragments.
  32. // (which limits max message size to around 288 KB)
  33. offset += Utils.Encode8u(ptr, offset, (byte)frg);
  34. offset += Utils.Encode16U(ptr, offset, (ushort)wnd);
  35. offset += Utils.Encode32U(ptr, offset, ts);
  36. offset += Utils.Encode32U(ptr, offset, sn);
  37. offset += Utils.Encode32U(ptr, offset, una);
  38. offset += Utils.Encode32U(ptr, offset, (uint)data.Position);
  39. return offset - offset_;
  40. }
  41. // reset to return a fresh segment to the pool
  42. internal void Reset()
  43. {
  44. conv = 0;
  45. cmd = 0;
  46. frg = 0;
  47. wnd = 0;
  48. ts = 0;
  49. sn = 0;
  50. una = 0;
  51. rto = 0;
  52. xmit = 0;
  53. resendts = 0;
  54. fastack = 0;
  55. // keep buffer for next pool usage, but reset length (= bytes written)
  56. data.SetLength(0);
  57. }
  58. }
  59. }