Segment.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Buffers;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.IO;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. namespace ET
  8. {
  9. // KCP Segment Definition
  10. internal struct SegmentStruct:IDisposable
  11. {
  12. public Kcp.SegmentHead SegHead;
  13. public uint resendts;
  14. public int rto;
  15. public uint fastack;
  16. public uint xmit;
  17. private byte[] buffer;
  18. private ArrayPool<byte> arrayPool;
  19. public bool IsNull => this.buffer == null;
  20. public int WrittenCount
  21. {
  22. get => (int) this.SegHead.len;
  23. private set => this.SegHead.len = (uint) value;
  24. }
  25. public Span<byte> WrittenBuffer => this.buffer.AsSpan(0, (int) this.SegHead.len);
  26. public Span<byte> FreeBuffer => this.buffer.AsSpan(WrittenCount);
  27. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  28. public SegmentStruct(int size, ArrayPool<byte> arrayPool)
  29. {
  30. this.arrayPool = arrayPool;
  31. buffer = arrayPool.Rent(size);
  32. this.SegHead = default;
  33. this.resendts = default;
  34. this.rto = default;
  35. this.fastack = default;
  36. this.xmit = default;
  37. }
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public void Encode(Span<byte> data, ref int size)
  40. {
  41. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(data),this.SegHead);
  42. size += Unsafe.SizeOf<Kcp.SegmentHead>();
  43. }
  44. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  45. public void Advance(int count)
  46. {
  47. this.WrittenCount += count;
  48. }
  49. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  50. public void Dispose()
  51. {
  52. arrayPool.Return(this.buffer);
  53. }
  54. }
  55. }