winipc-ua/Utils/PayloadHandler.cs
2025-08-02 20:18:00 +03:00

101 lines
3.5 KiB
C#

/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2024-2025 Gregory Lirent */
using Google.Protobuf;
using System.Reflection;
using WinIPC.Models;
namespace WinIPC.Utils
{
public static class PayloadHandler
{
public static byte[] Serialize<T>(T message) where T : IMessage<T>
{
if (message == null)
{
throw new ArgumentNullException(nameof(message), "Protobuf message cannot be null for serialization.");
}
return message.ToByteArray();
}
public static T Deserialize<T>(byte[] data) where T : IMessage<T>, new()
{
if (data == null)
{
throw new ArgumentNullException(nameof(data), "Byte array cannot be null for deserialization.");
}
PropertyInfo? parserProperty = typeof(T).GetProperty("Parser", BindingFlags.Static | BindingFlags.Public);
if (parserProperty == null)
{
throw new InvalidOperationException($"Type {typeof(T).Name} does not have a static 'Parser' property.");
}
MessageParser<T>? parser = parserProperty.GetValue(null) as MessageParser<T>;
if (parser == null)
{
throw new InvalidOperationException($"Could not get MessageParser for type {typeof(T).Name}.");
}
return parser.ParseFrom(data);
}
public static Request CreateRequest<T>(uint id, CommandType commandType, T payloadMessage) where T : IMessage<T>
{
return new Request
{
Id = id,
Type = commandType,
Payload = ByteString.CopyFrom(Serialize(payloadMessage))
};
}
public static Response CreateResponse<T>(uint id, bool success, string? errorMessage, T payloadMessage) where T : IMessage<T>
{
return new Response
{
Id = id,
Success = success,
Message = errorMessage ?? string.Empty,
Payload = ByteString.CopyFrom(Serialize(payloadMessage))
};
}
public static Response CreateErrorResponse(uint id, string errorMessage)
{
return new Response
{
Id = id,
Success = false,
Message = errorMessage
};
}
public static T ExtractPayload<T>(Request request) where T : IMessage<T>, new()
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), "Request cannot be null.");
}
if (request.Payload == null || request.Payload.IsEmpty)
{
throw new ArgumentNullException(nameof(request.Payload), "Request payload is null or empty.");
}
return Deserialize<T>(request.Payload.ToByteArray());
}
public static T ExtractPayload<T>(Response response) where T : IMessage<T>, new()
{
if (response == null)
{
throw new ArgumentNullException(nameof(response), "Response cannot be null.");
}
if (response.Payload == null || response.Payload.IsEmpty)
{
throw new ArgumentNullException(nameof(response.Payload), "Response payload is null or empty.");
}
return Deserialize<T>(response.Payload.ToByteArray());
}
}
}