Shims.cs 1003 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. namespace Jint;
  2. internal static class Shims
  3. {
  4. public static byte[] BytesFromHexString(this ReadOnlySpan<char> value)
  5. {
  6. #if NET6_0_OR_GREATER
  7. return Convert.FromHexString(value);
  8. #else
  9. if ((value.Length & 1) != 0)
  10. {
  11. throw new FormatException();
  12. }
  13. var byteCount = value.Length >> 1;
  14. var result = new byte[byteCount];
  15. var index = 0;
  16. for (var i = 0; i < byteCount; i++)
  17. {
  18. int hi, lo;
  19. if ((hi = GetDigitValue(value[index++])) < 0
  20. || (lo = GetDigitValue(value[index++])) < 0)
  21. {
  22. throw new FormatException();
  23. }
  24. result[i] = (byte) (hi << 4 | lo);
  25. }
  26. return result;
  27. static int GetDigitValue(char ch) => ch switch
  28. {
  29. >= '0' and <= '9' => ch - 0x30,
  30. >= 'a' and <= 'f' => ch - 0x57,
  31. >= 'A' and <= 'F' => ch - 0x37,
  32. _ => -1
  33. };
  34. #endif
  35. }
  36. }