1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System;
- using System.IO;
- using System.Linq;
- using H.Formatters;
- public interface ICoreFormattable
- {
- void Write(BinaryWriter writer);
- void Read(BinaryReader reader);
- }
- namespace InABox.Formatters
- {
- public class CoreFormatter<T1> : FormatterBase where T1 : ICoreFormattable
- {
-
- protected override byte[] SerializeInternal(object obj)
- {
- if (obj is ICoreFormattable _formattable)
- {
- using (var ms = new MemoryStream())
- {
- using (var writer = new BinaryWriter(ms))
- _formattable.Write(writer);
- return ms.ToArray();
- }
- }
- return new byte[] { };
- }
- protected override T DeserializeInternal<T>(byte[] bytes)
- {
- if (bytes.Any() && Activator.CreateInstance<T>() is ICoreFormattable result)
- {
- using (var ms = new MemoryStream(bytes))
- {
- using (var reader = new BinaryReader(ms))
- result.Read(reader);
- return (T)result;
- }
- }
- return default;
- }
- }
- }
|