ExtProtocolConvert.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. namespace XUnity.AutoTranslator.Plugin.ExtProtocol
  7. {
  8. public static class ExtProtocolConvert
  9. {
  10. private static readonly Dictionary<string, Type> IdToType = new Dictionary<string, Type>();
  11. private static readonly Dictionary<Type, string> TypeToId = new Dictionary<Type, string>();
  12. static ExtProtocolConvert()
  13. {
  14. Register( TranslationRequest.Type, typeof( TranslationRequest ) );
  15. Register( TranslationResponse.Type, typeof( TranslationResponse ) );
  16. Register( TranslationError.Type, typeof( TranslationError ) );
  17. }
  18. internal static void Register( string id, Type type )
  19. {
  20. IdToType[ id ] = type;
  21. TypeToId[ type ] = id;
  22. }
  23. public static string Encode( ProtocolMessage message )
  24. {
  25. var writer = new StringWriter();
  26. var id = TypeToId[ message.GetType() ];
  27. writer.WriteLine( id );
  28. message.Encode( writer );
  29. return Convert.ToBase64String( Encoding.UTF8.GetBytes( writer.ToString() ) );
  30. }
  31. public static ProtocolMessage Decode( string message )
  32. {
  33. var payload = Encoding.UTF8.GetString( Convert.FromBase64String( message ) );
  34. var reader = new StringReader( payload );
  35. var id = reader.ReadLine();
  36. var type = IdToType[ id ];
  37. var protocolMessage = (ProtocolMessage)Activator.CreateInstance( type );
  38. protocolMessage.Decode( reader );
  39. return protocolMessage;
  40. }
  41. }
  42. }