1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-26 14:38:34 +01:00
MLEM/MLEM.Data/NetExtensions.cs

65 lines
2.2 KiB
C#
Raw Normal View History

2019-12-20 15:03:33 +01:00
using System;
using System.Collections.Generic;
2019-12-20 15:03:33 +01:00
using System.IO;
using System.IO.Compression;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using MLEM.Misc;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
namespace MLEM.Data {
public static class NetExtensions {
public static void Write(this NetBuffer buffer, Vector2 vector) {
buffer.Write(vector.X);
buffer.Write(vector.Y);
}
public static Vector2 ReadVector2(this NetBuffer buffer) {
return new Vector2(buffer.ReadFloat(), buffer.ReadFloat());
}
public static void Write(this NetBuffer buffer, Guid guid) {
buffer.Write(guid.ToByteArray());
}
public static Guid ReadGuid(this NetBuffer buffer) {
return new Guid(buffer.ReadBytes(16));
}
public static void Write(this NetBuffer buffer, Direction2 direction) {
buffer.Write((short) direction);
}
public static Direction2 ReadDirection(this NetBuffer buffer) {
return (Direction2) buffer.ReadInt16();
}
public static void WriteObject<T>(this NetBuffer buffer, T obj, JsonSerializer serializer) {
2019-12-20 23:35:38 +01:00
if (EqualityComparer<T>.Default.Equals(obj, default)) {
buffer.Write(0);
2019-12-20 23:35:38 +01:00
return;
}
2019-12-20 15:03:33 +01:00
using (var memory = new MemoryStream()) {
2019-12-20 17:58:56 +01:00
using (var gzip = new DeflateStream(memory, CompressionLevel.Fastest, true))
2019-12-20 15:03:33 +01:00
serializer.Serialize(new BsonDataWriter(gzip), obj, typeof(T));
2019-12-20 15:07:25 +01:00
var arr = memory.ToArray();
buffer.Write(arr.Length);
buffer.Write(arr);
2019-12-20 15:03:33 +01:00
}
}
public static T ReadObject<T>(this NetBuffer buffer, JsonSerializer serializer) {
2019-12-20 15:07:25 +01:00
var length = buffer.ReadInt32();
if (length <= 0)
return default;
2019-12-20 15:07:25 +01:00
var arr = buffer.ReadBytes(length);
using (var memory = new MemoryStream(arr)) {
2019-12-20 17:58:56 +01:00
using (var gzip = new DeflateStream(memory, CompressionMode.Decompress, true))
2019-12-20 15:03:33 +01:00
return serializer.Deserialize<T>(new BsonDataReader(gzip));
}
}
}
}