ファイル

46 行
1.4 KiB
C#

using System.Reflection;
using YukkuriMovieMaker.Json;
namespace UndoTree;
internal static class UndoTreeCodec
{
const int MaxCharacters = 1_000_000;
static readonly MethodInfo Load = typeof(Json).GetMethod(nameof(Json.LoadFromText))!;
public static bool IsPlain(Type type) => type.IsValueType || type == typeof(string);
public static string? Encode(object? value, Type declared)
{
try
{
var text = IsPlain(declared) ? Json.GetJsonText(value) : Json.GetJsonText(new[] { value });
return text.Length <= MaxCharacters ? text : null;
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
return null;
}
}
public static string? EncodeReplayable(object? value, Type declared)
=> Encode(value, declared) is { } text && TryDecode(text, declared, out _) ? text : null;
public static bool TryDecode(string text, Type declared, out object? value)
{
value = null;
try
{
value = IsPlain(declared)
? Load.MakeGenericMethod(declared).Invoke(null, [text])
: Json.LoadFromText<object?[]>(text) is [var single] ? single : throw new FormatException();
return true;
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
return false;
}
}
}