1 // Copyright 2013 The Flutter Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ 6 #define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ 7 8 #include <memory> 9 #include <string> 10 #include <vector> 11 12 namespace flutter { 13 14 // Translates between a binary message and higher-level method call and 15 // response/error objects. 16 template <typename T> 17 class MessageCodec { 18 public: 19 MessageCodec() = default; 20 21 virtual ~MessageCodec() = default; 22 23 // Prevent copying. 24 MessageCodec(MessageCodec<T> const&) = delete; 25 MessageCodec& operator=(MessageCodec<T> const&) = delete; 26 27 // Returns the message encoded in |binary_message|, or nullptr if it cannot be 28 // decoded by this codec. DecodeMessage(const uint8_t * binary_message,const size_t message_size)29 std::unique_ptr<T> DecodeMessage(const uint8_t* binary_message, 30 const size_t message_size) const { 31 return std::move(DecodeMessageInternal(binary_message, message_size)); 32 } 33 34 // Returns the message encoded in |binary_message|, or nullptr if it cannot be 35 // decoded by this codec. DecodeMessage(const std::vector<uint8_t> & binary_message)36 std::unique_ptr<T> DecodeMessage( 37 const std::vector<uint8_t>& binary_message) const { 38 size_t size = binary_message.size(); 39 const uint8_t* data = size > 0 ? &binary_message[0] : nullptr; 40 return std::move(DecodeMessageInternal(data, size)); 41 } 42 43 // Returns a binary encoding of the given |message|, or nullptr if the 44 // message cannot be serialized by this codec. EncodeMessage(const T & message)45 std::unique_ptr<std::vector<uint8_t>> EncodeMessage(const T& message) const { 46 return std::move(EncodeMessageInternal(message)); 47 } 48 49 protected: 50 // Implementation of the public interface, to be provided by subclasses. 51 virtual std::unique_ptr<T> DecodeMessageInternal( 52 const uint8_t* binary_message, 53 const size_t message_size) const = 0; 54 55 // Implementation of the public interface, to be provided by subclasses. 56 virtual std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal( 57 const T& message) const = 0; 58 }; 59 60 } // namespace flutter 61 62 #endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_ 63