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.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 SequenceEqual(this Memory<byte> m1, ReadOnlyMemory<byte> m2) => m1.Span.SequenceEqual(m2.Span);
  26. public static void SodiumIncrement(this Span<byte> salt)
  27. {
  28. for (var i = 0; i < salt.Length; ++i)
  29. {
  30. if (++salt[i] != 0)
  31. {
  32. break;
  33. }
  34. }
  35. }
  36. }
  37. }