Segment.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 = new Kcp.SegmentHead() { len = 0 };
  33. this.SegHead = default;
  34. this.resendts = default;
  35. this.rto = default;
  36. this.fastack = default;
  37. this.xmit = default;
  38. }
  39. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  40. public void Encode(Span<byte> data, ref int size)
  41. {
  42. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(data),this.SegHead);
  43. size += Unsafe.SizeOf<Kcp.SegmentHead>();
  44. }
  45. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  46. public void Advance(int count)
  47. {
  48. this.WrittenCount += count;
  49. }
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. public void Dispose()
  52. {
  53. arrayPool.Return(this.buffer);
  54. }
  55. }
  56. }