diff --git a/plist-cil/ValuePreprocessor.cs b/plist-cil/ValuePreprocessor.cs new file mode 100644 index 0000000..498d48e --- /dev/null +++ b/plist-cil/ValuePreprocessor.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; + +namespace Claunia.PropertyList +{ + /// + /// Allows you to override the default value class initialization for the values found + /// in the parsed plists by registering your own preprocessing implementations. + /// + public static class ValuePreprocessor + { + public enum Types + { + BOOL, INTEGER, FLOATING_POINT, UNDEFINED_NUMBER, + STRING, DATA, DATE + }; + + private record struct TypeIdentifier(Types ValueType, Type ProcessingType); + private static T NullPreprocessor(T value) => value; + + private static readonly Dictionary _preprocessors = new() + { + { new(Types.BOOL, typeof(bool)), NullPreprocessor }, + { new(Types.BOOL, typeof(string)), NullPreprocessor }, + { new(Types.INTEGER, typeof(string)), NullPreprocessor }, + { new(Types.FLOATING_POINT, typeof(string)), NullPreprocessor }, + { new(Types.UNDEFINED_NUMBER, typeof(string)), NullPreprocessor }, + { new(Types.STRING, typeof(string)), NullPreprocessor }, + { new(Types.DATA, typeof(string)), NullPreprocessor }, + { new(Types.DATA, typeof(byte[])), NullPreprocessor }, + { new(Types.DATE, typeof(string)), NullPreprocessor }, + { new(Types.DATE, typeof(double)), NullPreprocessor }, + }; + + public static void Register(Func preprocessor, Types type) => + _preprocessors[new(type, typeof(T))] = preprocessor; + + public static T Preprocess(T value, Types type) => + TryGetPreprocessor(type, out Func preprocess) + ? preprocess(value) + : throw new ArgumentException($"Failed to find a preprocessor for value '{value}'."); + + private static bool TryGetPreprocessor(Types type, out Func preprocess) + { + if(_preprocessors.TryGetValue(new TypeIdentifier(type, typeof(T)), out Delegate preprocessor)) + { + preprocess = (Func) preprocessor; + return true; + } + + preprocess = default; + return false; + } + } + +} \ No newline at end of file