/tcpTrigger.Manager/Classes/CustomComparers.cs

https://github.com/R-Smith/tcpTrigger · C# · 63 lines · 50 code · 7 blank · 6 comment · 15 complexity · c4b7a1a0843ed597e41e59199ff3e519 MD5 · raw file

  1. using System.Collections.Generic;
  2. using System.Net;
  3. using System.Text.RegularExpressions;
  4. namespace tcpTrigger.Manager
  5. {
  6. public class IPAddressComparer : IComparer<IPAddress>
  7. {
  8. // Sort list of IP addresses so that IPv4 addresses appear sorted first
  9. // followed by sorted IPv6 addresses.
  10. public int Compare(IPAddress a, IPAddress b)
  11. {
  12. // Get byte array of each IP address.
  13. byte[] bytesA = a.GetAddressBytes();
  14. byte[] bytesB = b.GetAddressBytes();
  15. // Compare length of byte array. IPv4 addresses (smaller byte array) should be sorted first.
  16. if (bytesA.Length < bytesB.Length)
  17. return -1;
  18. if (bytesA.Length > bytesB.Length)
  19. return 1;
  20. // Byte arrays are equal length. Sort by comparing one byte at a time.
  21. int i = 0;
  22. while (i < bytesA.Length && i < bytesB.Length)
  23. {
  24. if (bytesA[i] > bytesB[i])
  25. return 1;
  26. else if (bytesA[i] < bytesB[i])
  27. return -1;
  28. else
  29. i++;
  30. }
  31. // All bytes in both arrays are equal.
  32. return 0;
  33. }
  34. }
  35. public class PortComparer : IComparer<string>
  36. {
  37. public int Compare(string x, string y)
  38. {
  39. if (string.IsNullOrWhiteSpace(x) && string.IsNullOrWhiteSpace(y))
  40. return 0;
  41. else if (string.IsNullOrWhiteSpace(y))
  42. return -1;
  43. else if (string.IsNullOrWhiteSpace(x))
  44. return 1;
  45. Regex regex = new Regex("^(\\d+)");
  46. Match xMatch = regex.Match(x);
  47. Match yMatch = regex.Match(y);
  48. if (xMatch.Success && yMatch.Success)
  49. {
  50. return int.Parse(xMatch.Groups[1].Value)
  51. .CompareTo(int.Parse(yMatch.Groups[1].Value));
  52. }
  53. return x.CompareTo(y);
  54. }
  55. }
  56. }