2using System.Collections.Generic;
11 internal static class TomlTypeConverter
31 private static Dictionary<Type, TypeConverter> TypeConverters =
new Dictionary<Type, TypeConverter>();
33 static TomlTypeConverter()
35 AddConverter(typeof(Enum),
new TypeConverter
37 ConvertToString = (obj, type) => obj.ToString(),
38 ConvertToObject = (str, type) => Enum.Parse(type, str,
true),
41 AddConverter(typeof(
Color),
new TypeConverter
43 ConvertToString = (obj, type) => ColorUtility.ToHtmlStringRGBA((
Color)obj),
44 ConvertToObject = (str, type) =>
47 if (!ColorUtility.TryParseHtmlString(
"#" + str.Trim(
'#',
' '), out c))
48 throw new FormatException(
"Invalid color string, expected hex #RRGGBBAA");
53 var jsonConverter =
new TypeConverter
55 ConvertToString = (obj, type) => JsonUtility.ToJson(obj),
56 ConvertToObject = (str, type) => JsonUtility.FromJson(type: type, json: str),
59 AddConverter(typeof(Vector2), jsonConverter);
60 AddConverter(typeof(Vector3), jsonConverter);
61 AddConverter(typeof(Vector4), jsonConverter);
62 AddConverter(typeof(Quaternion), jsonConverter);
68 public static string ConvertToString(
object value, Type valueType)
70 var conv = GetConverter(valueType);
72 throw new InvalidOperationException(
string.Format(
"Cannot convert from type {0}", valueType));
74 return conv.ConvertToString(value, valueType);
80 public static T ConvertToValue<T>(
string value)
82 return (T)ConvertToValue(value, typeof(T));
88 public static object ConvertToValue(
string value, Type valueType)
90 var conv = GetConverter(valueType);
92 throw new InvalidOperationException(
string.Format(
"Cannot convert to type {0}", valueType.Name));
94 return conv.ConvertToObject(value, valueType);
100 public static TypeConverter GetConverter(Type valueType)
102 if (valueType ==
null)
throw new ArgumentNullException();
104 if (valueType.IsEnum)
105 return TypeConverters[typeof(Enum)];
106 TypeConverter result;
107 TypeConverters.TryGetValue(valueType, out result);
115 public static bool AddConverter(Type type, TypeConverter converter)
117 if (type ==
null)
throw new ArgumentNullException();
118 if (converter ==
null)
throw new ArgumentNullException();
119 if (CanConvert(type))
121 RuntimeUnityEditorCore.Logger.Log(
LogLevel.Warning,
"Tried to add a TomlConverter when one already exists for type " + type.FullName);
125 TypeConverters.Add(type, converter);
132 public static bool CanConvert(Type type)
134 return GetConverter(type) !=
null;
140 public static IEnumerable<Type> GetSupportedTypes()
142 return TypeConverters.Keys;
RuntimeUnityEditor.Core.LogLevel LogLevel
A serializer/deserializer combo for some type(s). Used by the config system.
Func< string, Type, object > ConvertToObject
Used to deserialize the type from a string. String is the data to deserialize, Type is the object's t...
Func< object, Type, string > ConvertToString
Used to serialize the type into a (hopefully) human-readable string. Object is the instance to serial...