1
0
mirror of https://github.com/ppy/osu.git synced 2024-11-09 09:37:42 +08:00
osu-lazer/osu.Game/Online/API/ModSettingsDictionaryFormatter.cs
2021-04-12 03:37:03 +03:00

46 lines
1.5 KiB
C#

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Buffers;
using System.Collections.Generic;
using System.Text;
using MessagePack;
using MessagePack.Formatters;
using osu.Game.Utils;
namespace osu.Game.Online.API
{
public class ModSettingsDictionaryFormatter : IMessagePackFormatter<Dictionary<string, object>>
{
public void Serialize(ref MessagePackWriter writer, Dictionary<string, object> value, MessagePackSerializerOptions options)
{
var primitiveFormatter = PrimitiveObjectFormatter.Instance;
writer.WriteArrayHeader(value.Count);
foreach (var kvp in value)
{
var stringBytes = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes(kvp.Key));
writer.WriteString(in stringBytes);
primitiveFormatter.Serialize(ref writer, ModUtils.GetSettingUnderlyingValue(kvp.Value), options);
}
}
public Dictionary<string, object> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
var output = new Dictionary<string, object>();
int itemCount = reader.ReadArrayHeader();
for (int i = 0; i < itemCount; i++)
{
output[reader.ReadString()] =
PrimitiveObjectFormatter.Instance.Deserialize(ref reader, options);
}
return output;
}
}
}