DynamicObjectFormatter.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #nullable enable
  2. using System;
  3. using System.Reflection;
  4. using System.Text;
  5. namespace Ryujinx.Common.Logging
  6. {
  7. internal class DynamicObjectFormatter
  8. {
  9. private static readonly ObjectPool<StringBuilder> StringBuilderPool = SharedPools.Default<StringBuilder>();
  10. public static string? Format(object? dynamicObject)
  11. {
  12. if (dynamicObject is null)
  13. {
  14. return null;
  15. }
  16. StringBuilder sb = StringBuilderPool.Allocate();
  17. try
  18. {
  19. Format(sb, dynamicObject);
  20. return sb.ToString();
  21. }
  22. finally
  23. {
  24. StringBuilderPool.Release(sb);
  25. }
  26. }
  27. public static void Format(StringBuilder sb, object? dynamicObject)
  28. {
  29. if (dynamicObject is null)
  30. {
  31. return;
  32. }
  33. PropertyInfo[] props = dynamicObject.GetType().GetProperties();
  34. sb.Append('{');
  35. foreach (var prop in props)
  36. {
  37. sb.Append(prop.Name);
  38. sb.Append(": ");
  39. if (typeof(Array).IsAssignableFrom(prop.PropertyType))
  40. {
  41. Array? array = (Array?) prop.GetValue(dynamicObject);
  42. if (array is not null)
  43. {
  44. foreach (var item in array)
  45. {
  46. sb.Append(item);
  47. sb.Append(", ");
  48. }
  49. if (array.Length > 0)
  50. {
  51. sb.Remove(sb.Length - 2, 2);
  52. }
  53. }
  54. }
  55. else
  56. {
  57. sb.Append(prop.GetValue(dynamicObject));
  58. }
  59. sb.Append(" ; ");
  60. }
  61. // We remove the final ';' from the string
  62. if (props.Length > 0)
  63. {
  64. sb.Remove(sb.Length - 3, 3);
  65. }
  66. sb.Append('}');
  67. }
  68. }
  69. }