You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Util.cs 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Globalization;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace Shadowsocks.Protocol
  6. {
  7. internal static class Util
  8. {
  9. private static readonly IdnMapping _idnMapping = new IdnMapping();
  10. public static string RestoreHostName(string punycode) => Encoding.UTF8.GetByteCount(punycode) != punycode.Length
  11. ? punycode.ToLowerInvariant()
  12. : _idnMapping.GetUnicode(punycode).ToLowerInvariant();
  13. public static string EncodeHostName(string unicode) => Encoding.UTF8.GetByteCount(unicode) != unicode.Length
  14. ? _idnMapping.GetAscii(unicode).ToLowerInvariant()
  15. : unicode.ToLowerInvariant();
  16. public static ArraySegment<byte> GetArray(ReadOnlyMemory<byte> m)
  17. {
  18. if (!MemoryMarshal.TryGetArray(m, out var arr))
  19. {
  20. throw new InvalidOperationException("Can't get base array");
  21. }
  22. return arr;
  23. }
  24. public static ArgumentException BufferTooSmall(int expected, int actual, string name) => new ArgumentException($"Require {expected} byte buffer, received {actual} byte", name);
  25. public static bool MemEqual(Memory<byte> m1, Memory<byte> m2)
  26. {
  27. if (m1.Length != m2.Length) return false;
  28. for (var i = 0; i < m1.Length; i++)
  29. {
  30. if (m1.Span[i] != m2.Span[i]) return false;
  31. }
  32. return true;
  33. }
  34. public static void SodiumIncrement(Span<byte> salt)
  35. {
  36. for (var i = 0; i < salt.Length; ++i)
  37. {
  38. if (++salt[i] != 0)
  39. {
  40. break;
  41. }
  42. }
  43. }
  44. }
  45. }