Files
RAGECOOP-V/Core/Shared.cs

71 lines
2.1 KiB
C#
Raw Normal View History

2023-02-12 22:06:57 +08:00
global using static RageCoop.Core.Shared;
using System;
2023-02-27 11:54:02 +08:00
using System.Reflection;
using System.Text.Json;
2023-02-12 22:06:57 +08:00
namespace RageCoop.Core
{
2023-02-27 11:54:02 +08:00
public class JsonDontSerialize : Attribute
{
}
2023-02-12 22:06:57 +08:00
internal class Shared
{
2023-02-27 11:54:02 +08:00
static Type JsonTypeCheck(Type type)
{
2023-03-06 21:54:41 +08:00
if (type?.GetCustomAttribute<JsonDontSerialize>() != null)
2023-02-27 11:54:02 +08:00
throw new TypeAccessException($"The type {type} cannot be serialized");
return type;
}
static object JsonTypeCheck(object obj)
{
2023-03-06 21:54:41 +08:00
JsonTypeCheck(obj?.GetType());
2023-02-27 11:54:02 +08:00
return obj;
}
public static readonly JsonSerializerOptions JsonSettings = new();
2023-02-12 22:06:57 +08:00
static Shared()
{
JsonSettings.Converters.Add(new IPAddressConverter());
JsonSettings.Converters.Add(new IPEndPointConverter());
JsonSettings.WriteIndented = true;
JsonSettings.IncludeFields = true;
2023-02-12 22:06:57 +08:00
}
public static object JsonDeserialize(string text, Type type)
{
return JsonSerializer.Deserialize(text, JsonTypeCheck(type), JsonSettings);
2023-02-12 22:06:57 +08:00
}
public static T JsonDeserialize<T>(string text) => (T)JsonDeserialize(text, typeof(T));
public static string JsonSerialize(object obj) => JsonSerializer.Serialize(JsonTypeCheck(obj), JsonSettings);
/// <summary>
/// Shortcut to <see cref="BufferReader.ThreadLocal"/>
/// </summary>
/// <returns></returns>
2023-02-16 18:56:56 +08:00
public static unsafe BufferReader GetReader(byte* data = null, int cbData = 0)
{
var reader = BufferReader.ThreadLocal.Value;
2023-02-16 18:56:56 +08:00
reader.Initialise(data, cbData);
return reader;
}
/// <summary>
/// Shortcut to <see cref="BufferWriter.ThreadLocal"/>
/// </summary>
/// <returns></returns>
2023-02-16 18:56:56 +08:00
public static BufferWriter GetWriter(bool reset = true)
{
var writer = BufferWriter.ThreadLocal.Value;
if (reset)
{
writer.Reset();
}
return writer;
}
2023-02-12 22:06:57 +08:00
}
}