NumberFormatter.cs 2.9 KB

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