AsciiString.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace PlatformBenchmarks
  5. {
  6. public readonly struct AsciiString : IEquatable<AsciiString>
  7. {
  8. private readonly byte[] _data;
  9. public AsciiString(string s) => _data = Encoding.ASCII.GetBytes(s);
  10. public int Length => _data.Length;
  11. public byte[] Data => _data;
  12. public ReadOnlySpan<byte> AsSpan() => _data;
  13. public static implicit operator ReadOnlySpan<byte>(AsciiString str) => str._data;
  14. public static implicit operator byte[](AsciiString str) => str._data;
  15. public static implicit operator AsciiString(string str) => new AsciiString(str);
  16. public static explicit operator string(AsciiString str) => str.ToString();
  17. public bool Equals(AsciiString other) => ReferenceEquals(_data, other._data) || SequenceEqual(_data, other._data);
  18. private bool SequenceEqual(byte[] data1, byte[] data2) => new Span<byte>(data1).SequenceEqual(data2);
  19. public static bool operator ==(AsciiString a, AsciiString b) => a.Equals(b);
  20. public static bool operator !=(AsciiString a, AsciiString b) => !a.Equals(b);
  21. public override bool Equals(object other) => (other is AsciiString) && Equals((AsciiString)other);
  22. public override int GetHashCode()
  23. {
  24. // Copied from x64 version of string.GetLegacyNonRandomizedHashCode()
  25. // https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/String.Comparison.cs
  26. var data = _data;
  27. int hash1 = 5381;
  28. int hash2 = hash1;
  29. foreach (int b in data)
  30. {
  31. hash1 = ((hash1 << 5) + hash1) ^ b;
  32. }
  33. return hash1 + (hash2 * 1566083941);
  34. }
  35. }
  36. }