BufferSegment.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using BestHTTP.PlatformSupport.Threading;
  6. using System.Collections.Concurrent;
  7. using BestHTTP.PlatformSupport.Text;
  8. #if NET_STANDARD_2_0 || NETFX_CORE
  9. using System.Runtime.CompilerServices;
  10. #endif
  11. namespace BestHTTP.PlatformSupport.Memory
  12. {
  13. [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute]
  14. public struct BufferSegment
  15. {
  16. private const int ToStringMaxDumpLength = 128;
  17. public static readonly BufferSegment Empty = new BufferSegment(null, 0, 0);
  18. public readonly byte[] Data;
  19. public readonly int Offset;
  20. public readonly int Count;
  21. public BufferSegment(byte[] data, int offset, int count)
  22. {
  23. this.Data = data;
  24. this.Offset = offset;
  25. this.Count = count;
  26. }
  27. public BufferSegment Slice(int newOffset)
  28. {
  29. int diff = newOffset - this.Offset;
  30. return new BufferSegment(this.Data, newOffset, this.Count - diff);
  31. }
  32. public BufferSegment Slice(int offset, int count)
  33. {
  34. return new BufferSegment(this.Data, offset, count);
  35. }
  36. public override bool Equals(object obj)
  37. {
  38. if (obj == null || !(obj is BufferSegment))
  39. return false;
  40. return Equals((BufferSegment)obj);
  41. }
  42. public bool Equals(BufferSegment other)
  43. {
  44. return this.Data == other.Data &&
  45. this.Offset == other.Offset &&
  46. this.Count == other.Count;
  47. }
  48. public override int GetHashCode()
  49. {
  50. return (this.Data != null ? this.Data.GetHashCode() : 0) * 21 + this.Offset + this.Count;
  51. }
  52. public static bool operator ==(BufferSegment left, BufferSegment right)
  53. {
  54. return left.Equals(right);
  55. }
  56. public static bool operator !=(BufferSegment left, BufferSegment right)
  57. {
  58. return !left.Equals(right);
  59. }
  60. public override string ToString()
  61. {
  62. var sb = StringBuilderPool.Get(this.Count + 5);
  63. sb.Append("[BufferSegment ");
  64. sb.AppendFormat("Offset: {0:N0} ", this.Offset);
  65. sb.AppendFormat("Count: {0:N0} ", this.Count);
  66. sb.Append("Data: [");
  67. if (this.Count > 0)
  68. {
  69. if (this.Count <= ToStringMaxDumpLength)
  70. {
  71. sb.AppendFormat("{0:X2}", this.Data[this.Offset]);
  72. for (int i = 1; i < this.Count; ++i)
  73. sb.AppendFormat(", {0:X2}", this.Data[this.Offset + i]);
  74. }
  75. else
  76. sb.Append("...");
  77. }
  78. sb.Append("]]");
  79. return StringBuilderPool.ReleaseAndGrab(sb);
  80. }
  81. }
  82. }