NumberFormatter.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using Ryujinx.Graphics.Shader.Translation;
  2. using System;
  3. using System.Globalization;
  4. namespace Ryujinx.Graphics.Shader.CodeGen.Msl
  5. {
  6. static class NumberFormatter
  7. {
  8. private const int MaxDecimal = 256;
  9. public static bool TryFormat(int value, AggregateType dstType, out string formatted)
  10. {
  11. switch (dstType)
  12. {
  13. case AggregateType.FP32:
  14. return TryFormatFloat(BitConverter.Int32BitsToSingle(value), out formatted);
  15. case AggregateType.S32:
  16. formatted = FormatInt(value);
  17. break;
  18. case AggregateType.U32:
  19. formatted = FormatUint((uint)value);
  20. break;
  21. case AggregateType.Bool:
  22. formatted = value != 0 ? "true" : "false";
  23. break;
  24. default:
  25. throw new ArgumentException($"Invalid variable type \"{dstType}\".");
  26. }
  27. return true;
  28. }
  29. public static string FormatFloat(float value)
  30. {
  31. if (!TryFormatFloat(value, out string formatted))
  32. {
  33. throw new ArgumentException("Failed to convert float value to string.");
  34. }
  35. return formatted;
  36. }
  37. public static bool TryFormatFloat(float value, out string formatted)
  38. {
  39. if (float.IsNaN(value) || float.IsInfinity(value))
  40. {
  41. formatted = null;
  42. return false;
  43. }
  44. formatted = value.ToString("G9", CultureInfo.InvariantCulture);
  45. if (!(formatted.Contains('.') ||
  46. formatted.Contains('e') ||
  47. formatted.Contains('E')))
  48. {
  49. formatted += ".0f";
  50. }
  51. return true;
  52. }
  53. public static string FormatInt(int value, AggregateType dstType)
  54. {
  55. return dstType switch
  56. {
  57. AggregateType.S32 => FormatInt(value),
  58. AggregateType.U32 => FormatUint((uint)value),
  59. _ => throw new ArgumentException($"Invalid variable type \"{dstType}\".")
  60. };
  61. }
  62. public static string FormatInt(int value)
  63. {
  64. if (value <= MaxDecimal && value >= -MaxDecimal)
  65. {
  66. return value.ToString(CultureInfo.InvariantCulture);
  67. }
  68. return $"as_type<int>(0x{value.ToString("X", CultureInfo.InvariantCulture)})";
  69. }
  70. public static string FormatUint(uint value)
  71. {
  72. if (value <= MaxDecimal && value >= 0)
  73. {
  74. return value.ToString(CultureInfo.InvariantCulture) + "u";
  75. }
  76. return $"as_type<uint>(0x{value.ToString("X", CultureInfo.InvariantCulture)})";
  77. }
  78. }
  79. }