2023-02-12 22:06:57 +08:00
|
|
|
|
global using static RageCoop.Core.Shared;
|
|
|
|
|
using Newtonsoft.Json;
|
2023-02-27 11:54:02 +08:00
|
|
|
|
using Newtonsoft.Json.Serialization;
|
2023-02-12 22:06:57 +08:00
|
|
|
|
using System;
|
2023-02-27 11:54:02 +08:00
|
|
|
|
using System.Reflection;
|
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;
|
|
|
|
|
}
|
2023-02-12 22:06:57 +08:00
|
|
|
|
public static readonly JsonSerializerSettings JsonSettings = new();
|
|
|
|
|
static Shared()
|
|
|
|
|
{
|
|
|
|
|
JsonSettings.Converters.Add(new IPAddressConverter());
|
|
|
|
|
JsonSettings.Converters.Add(new IPEndPointConverter());
|
|
|
|
|
JsonSettings.Formatting = Formatting.Indented;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static object JsonDeserialize(string text, Type type)
|
|
|
|
|
{
|
2023-02-27 11:54:02 +08:00
|
|
|
|
return JsonConvert.DeserializeObject(text, JsonTypeCheck(type), JsonSettings);
|
2023-02-12 22:06:57 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static T JsonDeserialize<T>(string text) => (T)JsonDeserialize(text, typeof(T));
|
|
|
|
|
|
2023-02-27 11:54:02 +08:00
|
|
|
|
public static string JsonSerialize(object obj) => JsonConvert.SerializeObject(JsonTypeCheck(obj), JsonSettings);
|
2023-02-15 11:38:02 +08:00
|
|
|
|
|
|
|
|
|
/// <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)
|
2023-02-15 11:38:02 +08:00
|
|
|
|
{
|
|
|
|
|
var reader = BufferReader.ThreadLocal.Value;
|
2023-02-16 18:56:56 +08:00
|
|
|
|
reader.Initialise(data, cbData);
|
2023-02-15 11:38:02 +08:00
|
|
|
|
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;
|
2023-02-15 11:38:02 +08:00
|
|
|
|
if (reset)
|
|
|
|
|
{
|
|
|
|
|
writer.Reset();
|
|
|
|
|
}
|
|
|
|
|
return writer;
|
|
|
|
|
}
|
2023-02-12 22:06:57 +08:00
|
|
|
|
}
|
|
|
|
|
}
|