29 lines
970 B
C#

using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Syntriax.Engine.Core.Serialization;
public class Vector2DSerializer : IEngineTypeYamlSerializer
{
private static readonly int SUBSTRING_START_LENGTH = nameof(Vector2D).Length + 1;
public bool Accepts(Type type) => type == typeof(Vector2D);
public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
{
string value = parser.Consume<Scalar>().Value;
string insideParenthesis = value[SUBSTRING_START_LENGTH..^1];
string[] values = insideParenthesis.Split(", ");
return new Vector2D(float.Parse(values[0]), float.Parse(values[1]));
}
public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
{
Vector2D vector2D = (Vector2D)value!;
emitter.Emit(new Scalar($"{nameof(Vector2D)}({vector2D.X}, {vector2D.Y})"));
}
}