TOMLTypeConverter.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.ObjectModel;
  3. namespace BepInEx.Configuration
  4. {
  5. internal static class TomlTypeConverter
  6. {
  7. public static ReadOnlyCollection<Type> SupportedTypes { get; } = new ReadOnlyCollection<Type>(new[]
  8. {
  9. typeof(string),
  10. typeof(int),
  11. typeof(bool)
  12. });
  13. public static string ConvertToString(object value)
  14. {
  15. Type valueType = value.GetType();
  16. if (!SupportedTypes.Contains(valueType))
  17. throw new InvalidOperationException($"Cannot convert from type {valueType}");
  18. if (value is string s)
  19. {
  20. return s;
  21. }
  22. if (value is int i)
  23. {
  24. return i.ToString();
  25. }
  26. if (value is bool b)
  27. {
  28. return b.ToString().ToLowerInvariant();
  29. }
  30. throw new NotImplementedException("Supported type does not have a converter");
  31. }
  32. public static T ConvertToValue<T>(string value)
  33. {
  34. if (!SupportedTypes.Contains(typeof(T)))
  35. throw new InvalidOperationException($"Cannot convert to type {typeof(T)}");
  36. if (typeof(T) == typeof(string))
  37. {
  38. return (T)(object)value;
  39. }
  40. if (typeof(T) == typeof(int))
  41. {
  42. return (T)(object)int.Parse(value);
  43. }
  44. if (typeof(T) == typeof(bool))
  45. {
  46. return (T)(object)bool.Parse(value);
  47. }
  48. throw new NotImplementedException("Supported type does not have a converter");
  49. }
  50. }
  51. }