fix: use custom discriminator

This commit is contained in:
Anna 2024-06-17 14:20:33 -04:00
parent e9926fef67
commit ab4b5fbd7a
Signed by: anna
GPG Key ID: D0943384CD9F87D1
2 changed files with 13 additions and 24 deletions

View File

@ -1,6 +1,6 @@
using YamlDotNet.Core; using YamlDotNet.Core;
using YamlDotNet.Core.Events; using YamlDotNet.Core.Events;
using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
namespace TimePasses.Model; namespace TimePasses.Model;
@ -11,35 +11,28 @@ public interface IWhen {
bool IsValid(Plugin plugin); bool IsValid(Plugin plugin);
} }
public class WhenConverter : IYamlTypeConverter { public class WhenDiscriminator : ITypeDiscriminator {
public bool Accepts(Type type) { public Type BaseType => typeof(IWhen);
// FIXME? typeof(IWhen).IsAssignableFrom(type)
return typeof(IWhen) == type;
}
public object? ReadYaml(IParser parser, Type type) { public bool TryDiscriminate(IParser buffer, out Type? suggestedType) {
parser.Consume<MappingStart>(); buffer.Consume<MappingStart>();
var name = parser.Consume<Scalar>(); var name = buffer.Consume<Scalar>();
if (!name.IsKey) { if (!name.IsKey) {
throw new YamlException("invalid when: missing key"); suggestedType = null;
return false;
} }
IWhen when;
switch (name.Value) { switch (name.Value) {
case "quest": { case "quest": {
when = Plugin.Deserializer.Deserialize<WhenQuest>(parser); suggestedType = typeof(WhenQuest);
break; break;
} }
default: { default: {
throw new YamlException($"invalid when: unknown type {name.Value}"); suggestedType = null;
return false;
} }
} }
parser.Consume<MappingEnd>(); return true;
return when;
}
public void WriteYaml(IEmitter emitter, object? value, Type type) {
throw new NotImplementedException();
} }
} }

View File

@ -29,11 +29,7 @@ public class Plugin : IDalamudPlugin {
.WithNamingConvention(UnderscoredNamingConvention.Instance) .WithNamingConvention(UnderscoredNamingConvention.Instance)
// .WithTypeConverter(new WhenConverter()) // .WithTypeConverter(new WhenConverter())
.WithTypeDiscriminatingNodeDeserializer(o => { .WithTypeDiscriminatingNodeDeserializer(o => {
var keyMappings = new Dictionary<string, Type> { o.AddTypeDiscriminator(new WhenDiscriminator());
["quest"] = typeof(WhenQuest),
};
o.AddUniqueKeyTypeDiscriminator<IWhen>(keyMappings);
}) })
.Build(); .Build();