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 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)
{
if (type.GetCustomAttribute<JsonDontSerialize>() != null)
throw new TypeAccessException($"The type {type} cannot be serialized");
return type;
}
static object JsonTypeCheck(object obj)
{
JsonTypeCheck(obj.GetType());
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);
/// <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
}
}