rocketmq-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ifplu...@apache.org
Subject [rocketmq-client-cpp] 05/29: refactor: replace MemoryBlock with ByteArray
Date Tue, 29 Dec 2020 03:36:22 GMT
This is an automated email from the ASF dual-hosted git repository.

ifplusor pushed a commit to branch re_dev
in repository https://gitbox.apache.org/repos/asf/rocketmq-client-cpp.git

commit f0cce4417da99d7274ba44301409e37deb2ac8c4
Author: James Yin <ywhjames@hotmail.com>
AuthorDate: Mon Jul 20 10:57:17 2020 +0800

    refactor: replace MemoryBlock with ByteArray
---
 example/AsyncProducer.cpp                          |  11 +-
 example/BatchProducer.cpp                          |   8 +-
 example/CMakeLists.txt                             |   2 +-
 example/OrderlyProducer.cpp                        |   2 +-
 example/OrderlyPushConsumer.cpp                    |   5 +-
 example/PullConsumer.cpp                           |  11 +-
 example/PushConsumer.cpp                           |  13 +-
 example/RequestReply.cpp                           |  14 +-
 example/SendDelayMsg.cpp                           |   2 +-
 example/SyncProducer.cpp                           |   2 +-
 example/TransactionProducer.cpp                    |   2 +-
 example/common.h                                   |   4 +-
 include/AllocateMQStrategy.h                       |  11 +-
 include/Array.h                                    |  85 ++++++
 include/{CommandCustomHeader.h => ByteArray.h}     |  34 ++-
 include/ClientRPCHook.h                            |  12 +-
 include/CommandCustomHeader.h                      |  12 +-
 include/DataBlock.h                                | 219 --------------
 include/DefaultMQProducer.h                        |   2 +-
 include/DefaultMQPushConsumer.h                    |   2 +-
 include/MQMessage.h                                |   9 +-
 include/MQMessageExt.h                             |   1 +
 include/MQMessageQueue.h                           |  43 ++-
 include/Message.h                                  |   1 -
 include/RPCHook.h                                  |  10 +-
 include/RemotingCommand.h                          | 107 +++----
 include/RocketMQClient.h                           |   2 +
 src/ClientRemotingProcessor.cpp                    |  44 +--
 src/MQClientAPIImpl.cpp                            | 108 ++++---
 src/common/ByteOrder.h                             | 319 ++++++++-------------
 src/common/ClientRPCHook.cpp                       |  21 +-
 src/common/DataBlock.cpp                           | 239 ---------------
 src/common/FilterAPI.h                             |   2 +-
 src/common/InputStream.cpp                         | 114 --------
 src/common/InputStream.h                           | 197 -------------
 src/common/MemoryInputStream.cpp                   |  82 ------
 src/common/MemoryInputStream.h                     |  98 -------
 src/common/MemoryOutputStream.cpp                  | 173 -----------
 src/common/MemoryOutputStream.h                    | 132 ---------
 src/common/MessageSysFlag.cpp                      |  22 +-
 src/common/MessageSysFlag.h                        |  24 +-
 src/common/OutputStream.cpp                        | 107 -------
 src/common/OutputStream.h                          | 150 ----------
 src/common/SendCallbackWrap.cpp                    |   2 +-
 src/common/UtilAll.cpp                             |  40 +--
 src/common/UtilAll.h                               |  32 ++-
 src/common/Validators.cpp                          |   2 +-
 src/common/big_endian.cpp                          |  96 -------
 src/common/big_endian.h                            | 101 -------
 src/consumer/DefaultMQPushConsumer.cpp             |  30 +-
 src/consumer/PullAPIWrapper.cpp                    |   6 +-
 src/consumer/PullRequest.cpp                       |   9 +
 src/consumer/PullRequest.h                         |   7 +-
 src/consumer/PullResultExt.h                       |  17 +-
 src/extern/CMessage.cpp                            |   5 +-
 src/io/Buffer.hpp                                  | 193 +++++++++++++
 src/io/ByteArray.cpp                               |  82 ++++++
 .../CommandCustomHeader.h => src/io/ByteBuffer.cpp |  35 ++-
 src/io/ByteBuffer.hpp                              | 184 ++++++++++++
 src/io/DefaultByteBuffer.hpp                       | 222 ++++++++++++++
 src/message/MQMessage.cpp                          |   8 +-
 src/message/MQMessageQueue.cpp                     |  78 ++---
 src/message/MessageClientIDSetter.cpp              |  10 +-
 src/message/MessageDecoder.cpp                     | 183 ++++++------
 src/message/MessageDecoder.h                       |  18 +-
 src/message/MessageExtImpl.cpp                     |   2 +-
 src/message/MessageImpl.cpp                        |   5 -
 src/message/MessageImpl.h                          |   1 -
 src/message/MessageUtil.cpp                        |   1 +
 src/producer/DefaultMQProducer.cpp                 |  55 ++--
 src/producer/DefaultMQProducerImpl.cpp             |  24 +-
 src/producer/TransactionMQProducer.cpp             |   6 +-
 src/protocol/RemotingCommand.cpp                   | 218 +++++++-------
 src/protocol/RemotingSerializable.cpp              |   6 +-
 src/protocol/RemotingSerializable.h                |   4 +-
 src/protocol/TopicList.h                           |  10 +-
 src/protocol/TopicRouteData.h                      |   6 +-
 src/protocol/body/LockBatchBody.cpp                |   4 +-
 src/protocol/body/LockBatchBody.h                  |   3 +-
 src/protocol/body/ResetOffsetBody.cpp              |   8 +-
 src/protocol/body/ResetOffsetBody.h                |   8 +-
 src/protocol/header/CommandHeader.cpp              |   4 +-
 src/protocol/header/CommandHeader.h                |   4 +-
 src/transport/SocketUtil.cpp                       |  25 +-
 src/transport/SocketUtil.h                         |   5 +-
 src/transport/TcpRemotingClient.cpp                |  36 +--
 src/transport/TcpRemotingClient.h                  |   4 +-
 src/transport/TcpTransport.cpp                     |  10 +-
 src/transport/TcpTransport.h                       |   6 +-
 test/src/common/BigEndianTest.cpp                  |  85 ------
 test/src/common/ClientRPCHookTest.cpp              |   2 +-
 test/src/common/MemoryBlockTest.cpp                | 150 ----------
 test/src/common/MemoryOutputStreamTest.cpp         | 197 -------------
 test/src/extern/CProducerTest.cpp                  |   8 +-
 test/src/extern/CPullConsumerTest.cpp              |   9 +-
 test/src/message/MQMessageExtTest.cpp              |  12 +-
 test/src/message/MQMessageTest.cpp                 |   4 -
 test/src/message/MessageBatchTest.cpp              |   1 +
 test/src/message/MessageDecoderTest.cpp            | 109 +++----
 test/src/protocol/CommandHeaderTest.cpp            |   9 +-
 test/src/protocol/LockBatchBodyTest.cpp            |  10 +-
 test/src/protocol/RemotingCommandTest.cpp          | 105 ++++---
 test/src/protocol/TopicRouteDataTest.cpp           |  10 +-
 test/src/transport/ClientRemotingProcessorTest.cpp |   4 +-
 test/src/transport/ResponseFutureTest.cpp          |   2 +-
 test/src/transport/SocketUtilTest.cpp              |   5 +-
 106 files changed, 1747 insertions(+), 3248 deletions(-)

diff --git a/example/AsyncProducer.cpp b/example/AsyncProducer.cpp
index 8f6c05f..87e7368 100644
--- a/example/AsyncProducer.cpp
+++ b/example/AsyncProducer.cpp
@@ -27,8 +27,7 @@ std::atomic<int> g_failed(0);
 
 class MyAutoDeleteSendCallback : public AutoDeleteSendCallback {
  public:
-  MyAutoDeleteSendCallback(MQMessage* msg) : m_msg(msg) {}
-  virtual ~MyAutoDeleteSendCallback() { delete m_msg; }
+  MyAutoDeleteSendCallback(MQMessage msg) : m_msg(std::move(msg)) {}
 
   void onSuccess(SendResult& sendResult) override {
     g_success++;
@@ -43,14 +42,14 @@ class MyAutoDeleteSendCallback : public AutoDeleteSendCallback {
   }
 
  private:
-  MQMessage* m_msg;
+  MQMessage m_msg;
 };
 
 void AsyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* producer) {
   while (g_msgCount.fetch_sub(1) > 0) {
-    auto* msg = new MQMessage(info->topic,  // topic
-                              "*",          // tag
-                              info->body);  // body
+    MQMessage msg(info->topic,  // topic
+                  "*",          // tag
+                  info->body);  // body
 
     SendCallback* callback = new MyAutoDeleteSendCallback(msg);
 
diff --git a/example/BatchProducer.cpp b/example/BatchProducer.cpp
index 4055d8a..e698b66 100644
--- a/example/BatchProducer.cpp
+++ b/example/BatchProducer.cpp
@@ -22,7 +22,7 @@ TpsReportService g_tps;
 
 void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* producer) {
   while (g_msgCount.fetch_sub(1) > 0) {
-    std::vector<MQMessage*> msgs;
+    std::vector<MQMessage> msgs;
     MQMessage msg1(info->topic, "*", info->body);
     msg1.putProperty("property1", "value1");
     MQMessage msg2(info->topic, "*", info->body);
@@ -32,9 +32,9 @@ void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* pr
     msg3.putProperty("property1", "value1");
     msg3.putProperty("property2", "value2");
     msg3.putProperty("property3", "value3");
-    msgs.push_back(&msg1);
-    msgs.push_back(&msg2);
-    msgs.push_back(&msg3);
+    msgs.push_back(std::move(msg1));
+    msgs.push_back(std::move(msg2));
+    msgs.push_back(std::move(msg3));
 
     try {
       auto start = std::chrono::system_clock::now();
diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt
index 8e445b1..cf75d06 100755
--- a/example/CMakeLists.txt
+++ b/example/CMakeLists.txt
@@ -17,7 +17,7 @@ project(example)
 
 set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin)
 
-file(GLOB files RELATIVE "${PROJECT_SOURCE_DIR}" "*.c*")
+file(GLOB files RELATIVE "${PROJECT_SOURCE_DIR}" "*.c" "*.cpp")
 list(REMOVE_ITEM files "ArgHelper.cpp")
 foreach(file ${files})
     get_filename_component(basename ${file} NAME_WE)
diff --git a/example/OrderlyProducer.cpp b/example/OrderlyProducer.cpp
index d50542e..f2ce9f6 100644
--- a/example/OrderlyProducer.cpp
+++ b/example/OrderlyProducer.cpp
@@ -39,7 +39,7 @@ void ProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* produc
     try {
       auto start = std::chrono::system_clock::now();
       int orderId = 1;
-      SendResult sendResult = producer->send(&msg, &g_mySelector, static_cast<void*>(&orderId), info->retrytimes);
+      SendResult sendResult = producer->send(msg, &g_mySelector, static_cast<void*>(&orderId), info->retrytimes);
       auto end = std::chrono::system_clock::now();
 
       g_tps.Increment();
diff --git a/example/OrderlyPushConsumer.cpp b/example/OrderlyPushConsumer.cpp
index 2d8a541..62959f1 100644
--- a/example/OrderlyPushConsumer.cpp
+++ b/example/OrderlyPushConsumer.cpp
@@ -27,13 +27,12 @@ class MyMsgListener : public MessageListenerOrderly {
   MyMsgListener() {}
   virtual ~MyMsgListener() {}
 
-  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt*>& msgs) {
+  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) override {
     auto old = g_msgCount.fetch_sub(msgs.size());
     if (old > 0) {
       for (size_t i = 0; i < msgs.size(); ++i) {
         g_tps.Increment();
-        // std::cout << msgs[i]->getMsgId() << std::endl;
-        // std::cout << "msg body: " << msgs[i].getBody() << std::endl;
+        std::cout << msgs[i].getMsgId() << ", body: " << msgs[i].getBody() << std::endl;
       }
       if (old <= msgs.size()) {
         g_finished.count_down();
diff --git a/example/PullConsumer.cpp b/example/PullConsumer.cpp
index e7472b3..d1eab5e 100644
--- a/example/PullConsumer.cpp
+++ b/example/PullConsumer.cpp
@@ -24,6 +24,7 @@
 #include <vector>
 
 #include "common.h"
+#include "DefaultMQPullConsumer.h"
 
 using namespace rocketmq;
 
@@ -77,18 +78,18 @@ int main(int argc, char* argv[]) {
     do {
       try {
         PullResult result = consumer.pull(mq, "*", getMessageQueueOffset(mq), 32);
-        g_msgCount += result.msg_found_list_.size();
-        std::cout << result.msg_found_list_.size() << std::endl;
+        g_msgCount += result.msg_found_list().size();
+        std::cout << result.msg_found_list().size() << std::endl;
         // if pull request timeout or received NULL response, pullStatus will be
         // setted to BROKER_TIMEOUT,
         // And nextBeginOffset/minOffset/MaxOffset will be setted to 0
-        if (result.pull_status_ != BROKER_TIMEOUT) {
-          putMessageQueueOffset(mq, result.next_begin_offset_);
+        if (result.pull_status() != BROKER_TIMEOUT) {
+          putMessageQueueOffset(mq, result.next_begin_offset());
           PrintPullResult(&result);
         } else {
           std::cout << "broker timeout occur" << std::endl;
         }
-        switch (result.pull_status_) {
+        switch (result.pull_status()) {
           case FOUND:
           case NO_MATCHED_MSG:
           case OFFSET_ILLEGAL:
diff --git a/example/PushConsumer.cpp b/example/PushConsumer.cpp
index 9f17979..0e7ccc9 100644
--- a/example/PushConsumer.cpp
+++ b/example/PushConsumer.cpp
@@ -16,6 +16,7 @@
  */
 #include "common.h"
 #include "concurrent/latch.hpp"
+#include "UtilAll.h"
 
 using namespace rocketmq;
 
@@ -24,16 +25,18 @@ latch g_finished(1);
 
 class MyMsgListener : public MessageListenerConcurrently {
  public:
-  MyMsgListener() {}
-  virtual ~MyMsgListener() {}
+  virtual ~MyMsgListener() = default;
 
-  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt*>& msgs) {
+  ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) override {
     auto old = g_msgCount.fetch_sub(msgs.size());
     if (old > 0) {
       for (size_t i = 0; i < msgs.size(); ++i) {
         g_tps.Increment();
-        // std::cout << msgs[i]->getMsgId() << std::endl;
-        // std::cout << "msg body: " << msgs[i].getBody() << std::endl;
+        if (msgs[i] == nullptr) {
+          std::cout << "error!!!" << std::endl;
+        } else {
+          std::cout << msgs[i].getMsgId() << ", body: " << msgs[i].getBody() << std::endl;
+        }
       }
       if (old <= msgs.size()) {
         g_finished.count_down();
diff --git a/example/RequestReply.cpp b/example/RequestReply.cpp
index 1ba3af8..ebb52e3 100644
--- a/example/RequestReply.cpp
+++ b/example/RequestReply.cpp
@@ -17,7 +17,7 @@
 #include <iostream>
 
 #include "../src/common/UtilAll.h"
-#include "../src/log/Logging.h"
+#include "common.h"
 #include "MessageUtil.h"
 #include "common.h"
 
@@ -28,17 +28,17 @@ class MyResponseMessageListener : public MessageListenerConcurrently {
   MyResponseMessageListener(DefaultMQProducer* replyProducer) : m_replyProducer(replyProducer) {}
   virtual ~MyResponseMessageListener() = default;
 
-  ConsumeStatus consumeMessage(const std::vector<MQMessageExt*>& msgs) override {
+  ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) override {
     for (const auto& msg : msgs) {
       try {
-        std::cout << "handle message: " << msg->toString() << std::endl;
+        std::cout << "handle message: " << msg.toString() << std::endl;
         const auto& replyTo = MessageUtil::getReplyToClient(msg);
 
         // create reply message with given util, do not create reply message by yourself
-        std::unique_ptr<MQMessage> replyMessage(MessageUtil::createReplyMessage(msg, "reply message contents."));
+        MQMessage replyMessage = MessageUtil::createReplyMessage(msg, "reply message contents.");
 
         // send reply message with producer
-        SendResult replyResult = m_replyProducer->send(replyMessage.get(), 10000);
+        SendResult replyResult = m_replyProducer->send(replyMessage, 10000);
         std::cout << "reply to " << replyTo << ", " << replyResult.toString() << std::endl;
       } catch (const std::exception& e) {
         std::cout << e.what() << std::endl;
@@ -98,10 +98,10 @@ int main(int argc, char* argv[]) {
       MQMessage msg(info.topic, "Hello world");
 
       auto begin = UtilAll::currentTimeMillis();
-      std::unique_ptr<MQMessage> retMsg(producer.request(&msg, 10000));
+      MQMessage retMsg = producer.request(msg, 10000);
       auto cost = UtilAll::currentTimeMillis() - begin;
       std::cout << count << " >>> request to <" << info.topic << "> cost: " << cost
-                << " replyMessage: " << retMsg->toString() << std::endl;
+                << " replyMessage: " << retMsg.toString() << std::endl;
     } catch (const std::exception& e) {
       std::cout << count << " >>> " << e.what() << std::endl;
     }
diff --git a/example/SendDelayMsg.cpp b/example/SendDelayMsg.cpp
index 3a5b6ce..a1ed150 100644
--- a/example/SendDelayMsg.cpp
+++ b/example/SendDelayMsg.cpp
@@ -40,7 +40,7 @@ int main(int argc, char* argv[]) {
   // messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
   msg.setDelayTimeLevel(5);  // 1m
   try {
-    SendResult sendResult = producer->send(&msg);
+    SendResult sendResult = producer->send(msg);
   } catch (const MQException& e) {
     std::cout << "send failed: " << std::endl;
   }
diff --git a/example/SyncProducer.cpp b/example/SyncProducer.cpp
index 994a519..c5bbaf1 100644
--- a/example/SyncProducer.cpp
+++ b/example/SyncProducer.cpp
@@ -27,7 +27,7 @@ void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* pr
                   info->body);  // body
     try {
       auto start = std::chrono::system_clock::now();
-      SendResult sendResult = producer->send(&msg);
+      SendResult sendResult = producer->send(msg);
       auto end = std::chrono::system_clock::now();
 
       g_tps.Increment();
diff --git a/example/TransactionProducer.cpp b/example/TransactionProducer.cpp
index 547a279..214d321 100644
--- a/example/TransactionProducer.cpp
+++ b/example/TransactionProducer.cpp
@@ -43,7 +43,7 @@ void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, TransactionMQProducer
     try {
       auto start = std::chrono::system_clock::now();
       intptr_t arg = old - 1;
-      TransactionSendResult sendResult = producer->sendMessageInTransaction(&msg, (void*)arg);
+      TransactionSendResult sendResult = producer->sendMessageInTransaction(msg, (void*)arg);
       auto end = std::chrono::system_clock::now();
 
       g_tps.Increment();
diff --git a/example/common.h b/example/common.h
index 90bff8e..3de4199 100644
--- a/example/common.h
+++ b/example/common.h
@@ -114,9 +114,9 @@ static void PrintResult(rocketmq::SendResult* result) {
 
 void PrintPullResult(rocketmq::PullResult* result) {
   std::cout << result->toString() << std::endl;
-  if (result->pull_status_ == rocketmq::FOUND) {
+  if (result->pull_status() == rocketmq::FOUND) {
     std::cout << result->toString() << std::endl;
-    for (auto& msg : result->msg_found_list_) {
+    for (auto msg : result->msg_found_list()) {
       std::cout << "=======================================================" << std::endl
                 << msg->toString() << std::endl;
     }
diff --git a/include/AllocateMQStrategy.h b/include/AllocateMQStrategy.h
index 0343654..4f60b29 100644
--- a/include/AllocateMQStrategy.h
+++ b/include/AllocateMQStrategy.h
@@ -14,16 +14,19 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __ALLOCATE_MQ_STRATEGY_H__
-#define __ALLOCATE_MQ_STRATEGY_H__
+#ifndef ROCKETMQ_ALLOCATEMQSTRATEGY_H_
+#define ROCKETMQ_ALLOCATEMQSTRATEGY_H_
 
-#include <string>
-#include <vector>
+#include <string>  // std::string
+#include <vector>  // std::vector
 
 #include "MQMessageQueue.h"
 
 namespace rocketmq {
 
+/**
+ * AllocateMQStrategy - Interface of allocate MessageQueue
+ */
 class ROCKETMQCLIENT_API AllocateMQStrategy {
  public:
   virtual ~AllocateMQStrategy() = default;
diff --git a/include/Array.h b/include/Array.h
new file mode 100644
index 0000000..daa4866
--- /dev/null
+++ b/include/Array.h
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef ROCKETMQ_ARRAY_H_
+#define ROCKETMQ_ARRAY_H_
+
+#include <cstdlib>  // std::calloc, std::free
+#include <cstring>  // std::memcpy
+
+#include <stdexcept>    // std::bad_alloc
+#include <type_traits>  // std::enable_if, std::is_arithmetic, std::is_pointer, std::is_class
+
+#include "RocketMQClient.h"
+
+namespace rocketmq {
+
+template <typename T, typename Enable = void>
+struct array_traits {};
+
+template <typename T>
+struct array_traits<T, typename std::enable_if<std::is_arithmetic<T>::value || std::is_pointer<T>::value>::type> {
+  typedef T element_type;
+};  // specialization for arithmetic and pointer types
+
+template <typename T>
+struct array_traits<T, typename std::enable_if<std::is_class<T>::value>::type> {
+  typedef T* element_type;
+};  // specialization for class types
+
+template <typename T>
+using array_element_t = typename array_traits<T>::element_type;
+
+template <typename T>
+class Array {
+ public:
+  using element_type = array_element_t<T>;
+
+ public:
+  Array(element_type* array, size_t size, bool auto_clean = false)
+      : array_(array), size_(size), auto_clean_(auto_clean) {}
+  Array(size_t size) : Array((element_type*)std::calloc(size, sizeof(element_type)), size, true) {
+    if (nullptr == array_) {
+      throw std::bad_alloc();
+    }
+  }
+
+  Array(const Array& other) : Array(other.size_) { std::memcpy(array_, other.array_, size_); }
+  Array(Array&& other) : Array(other.array_, other.size_, other.auto_clean_) { other.auto_clean_ = false; }
+
+  virtual ~Array() {
+    if (auto_clean_) {
+      std::free(array_);
+    }
+  }
+
+  element_type& operator[](size_t index) { return array_[index]; }
+  const element_type& operator[](size_t index) const { return array_[index]; }
+
+ public:
+  inline T* array() { return array_; }
+  inline const T* array() const { return array_; }
+  inline size_t size() const { return size_; }
+
+ protected:
+  element_type* array_;
+  size_t size_;
+  bool auto_clean_;
+};
+
+}  // namespace rocketmq
+
+#endif  // ROCKETMQ_ARRAY_H_
diff --git a/include/CommandCustomHeader.h b/include/ByteArray.h
similarity index 60%
copy from include/CommandCustomHeader.h
copy to include/ByteArray.h
index 66c1b56..5ce3aa0 100644
--- a/include/CommandCustomHeader.h
+++ b/include/ByteArray.h
@@ -14,30 +14,28 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __COMMAND_CUSTOM_HEADER_H__
-#define __COMMAND_CUSTOM_HEADER_H__
+#ifndef ROCKETMQ_BYTEARRAY_H_
+#define ROCKETMQ_BYTEARRAY_H_
 
-#include <map>
-#include <string>
+#include <memory>  // std::shared_ptr
 
-#include "RocketMQClient.h"
-
-namespace Json {
-class Value;
-}
+#include "Array.h"
 
 namespace rocketmq {
 
-class ROCKETMQCLIENT_API CommandCustomHeader {
- public:
-  virtual ~CommandCustomHeader() = default;
+typedef Array<char> ByteArray;
+typedef std::shared_ptr<Array<char>> ByteArrayRef;
+
+ByteArrayRef slice(ByteArrayRef ba, size_t offset);
+ByteArrayRef slice(ByteArrayRef ba, size_t offset, size_t size);
+
+ByteArrayRef stoba(const std::string& str);
+ByteArrayRef stoba(std::string&& str);
 
-  // write CustomHeader to extFields (map<string,string>)
-  virtual void Encode(Json::Value& extFields) {}
+ByteArrayRef catoba(const char* str, size_t len);
 
-  virtual void SetDeclaredFieldOfCommandHeader(std::map<std::string, std::string>& requestMap) {}
-};
+std::string batos(ByteArrayRef ba);
 
-}  // namespace rocketmq
+}  // namepace rocketmq
 
-#endif  // __COMMAND_CUSTOM_HEADER_H__
+#endif  // ROCKETMQ_BYTEARRAY_H_
diff --git a/include/ClientRPCHook.h b/include/ClientRPCHook.h
index e2a7d26..e185b1f 100644
--- a/include/ClientRPCHook.h
+++ b/include/ClientRPCHook.h
@@ -14,8 +14,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __CLIENT_RPC_HOOK_H__
-#define __CLIENT_RPC_HOOK_H__
+#ifndef ROCKETMQ_CLIENTRPCHOOK_H_
+#define ROCKETMQ_CLIENTRPCHOOK_H_
+
+#include <string>  // std::string
 
 #include "RPCHook.h"
 #include "SessionCredentials.h"
@@ -24,7 +26,7 @@ namespace rocketmq {
 
 class ROCKETMQCLIENT_API ClientRPCHook : public RPCHook {
  public:
-  ClientRPCHook(const SessionCredentials& sessionCredentials) : sessionCredentials_(sessionCredentials) {}
+  ClientRPCHook(const SessionCredentials& sessionCredentials) : session_credentials_(sessionCredentials) {}
   ~ClientRPCHook() override = default;
 
   void doBeforeRequest(const std::string& remoteAddr, RemotingCommand& request, bool toSent) override;
@@ -37,9 +39,9 @@ class ROCKETMQCLIENT_API ClientRPCHook : public RPCHook {
   void signCommand(RemotingCommand& command);
 
  private:
-  SessionCredentials sessionCredentials_;
+  SessionCredentials session_credentials_;
 };
 
 }  // namespace rocketmq
 
-#endif  // __CLIENT_RPC_HOOK_H__
+#endif  // ROCKETMQ_CLIENTRPCHOOK_H_
diff --git a/include/CommandCustomHeader.h b/include/CommandCustomHeader.h
index 66c1b56..a088c21 100644
--- a/include/CommandCustomHeader.h
+++ b/include/CommandCustomHeader.h
@@ -14,15 +14,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __COMMAND_CUSTOM_HEADER_H__
-#define __COMMAND_CUSTOM_HEADER_H__
+#ifndef ROCKETMQ_COMMANDCUSTOMHEADER_H_
+#define ROCKETMQ_COMMANDCUSTOMHEADER_H_
 
-#include <map>
-#include <string>
+#include <map>     // std::map
+#include <string>  // std::string
 
 #include "RocketMQClient.h"
 
-namespace Json {
+namespace Json {  // jsoncpp
 class Value;
 }
 
@@ -40,4 +40,4 @@ class ROCKETMQCLIENT_API CommandCustomHeader {
 
 }  // namespace rocketmq
 
-#endif  // __COMMAND_CUSTOM_HEADER_H__
+#endif  // ROCKETMQ_COMMANDCUSTOMHEADER_H_
diff --git a/include/DataBlock.h b/include/DataBlock.h
deleted file mode 100644
index 7976cd0..0000000
--- a/include/DataBlock.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef __DATA_BLOCK_H__
-#define __DATA_BLOCK_H__
-
-#include <memory>
-#include <string>
-
-#include "RocketMQClient.h"
-
-namespace rocketmq {
-
-class MemoryBlock;
-typedef std::unique_ptr<MemoryBlock> MemoryBlockPtr;
-typedef std::shared_ptr<MemoryBlock> MemoryBlockPtr2;
-
-class ROCKETMQCLIENT_API MemoryBlock {
- public:
-  MemoryBlock() : MemoryBlock(nullptr, 0) {}
-  explicit MemoryBlock(char* data, size_t size) : data_(data), size_(size) {}
-  virtual ~MemoryBlock() = default;
-
-  /** Returns a void pointer to the data.
-   *
-   *  Note that the pointer returned will probably become invalid when the block is resized.
-   */
-  char* getData() { return data_; }
-
-  const char* getData() const { return data_; }
-
-  /** Returns the block's current allocated size, in bytes. */
-  size_t getSize() const { return size_; }
-
-  /** Returns a byte from the memory block.
-   *  This returns a reference, so you can also use it to set a byte.
-   */
-  template <typename Type>
-  char& operator[](const Type offset) {
-    return data_[offset];
-  }
-
-  template <typename Type>
-  const char& operator[](const Type offset) const {
-    return data_[offset];
-  }
-
-  operator std::string() {
-    if (size_ > 0) {
-      return std::string(data_, size_);
-    } else {
-      return "";
-    }
-  }
-
-  /** Frees all the blocks data, setting its size to 0. */
-  virtual void reset() { reset(nullptr, 0); }
-
-  virtual void reset(char* data, size_t size) {
-    data_ = data;
-    size_ = size;
-  }
-
-  /** Copies data from this MemoryBlock to a memory address.
-   *
-   *  @param destData         the memory location to write to
-   *  @param sourceOffset     the offset within this block from which the copied data will be read
-   *  @param numBytes         how much to copy (if this extends beyond the limits of the memory block,
-   *                          zeros will be used for that portion of the data)
-   */
-  void copyTo(void* destData, ssize_t sourceOffset, size_t numBytes) const;
-
- protected:
-  char* data_;
-  size_t size_;
-};
-
-class ROCKETMQCLIENT_API MemoryPool : public MemoryBlock {
- public:
-  /** Create an uninitialised block with 0 size. */
-  MemoryPool();
-
-  /** Creates a memory block with a given initial size.
-   *
-   *  @param initialSize          the size of block to create
-   *  @param initialiseToZero     whether to clear the memory or just leave it uninitialised
-   */
-  explicit MemoryPool(size_t initialSize, bool initialiseToZero = false);
-
-  /** Creates a memory block using a copy of a block of data.
-   *
-   *  @param dataToInitialiseFrom     some data to copy into this block
-   *  @param sizeInBytes              how much space to use
-   */
-  explicit MemoryPool(const void* dataToInitialiseFrom, size_t sizeInBytes);
-
-  /** Creates a copy of another memory block. */
-  MemoryPool(const MemoryPool&);
-
-  MemoryPool(MemoryPool&&);
-
-  /** Destructor. */
-  ~MemoryPool();
-
-  /** Copies another memory block onto this one.
-   *  This block will be resized and copied to exactly match the other one.
-   */
-  MemoryPool& operator=(const MemoryPool&);
-
-  MemoryPool& operator=(MemoryPool&&);
-
-  /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in. */
-  bool matches(const void* data, size_t dataSize) const;
-
-  /** Compares two memory blocks.
-   *  @returns true only if the two blocks are the same size and have identical contents.
-   */
-  bool operator==(const MemoryPool& other) const;
-
-  /** Compares two memory blocks.
-   *  @returns true if the two blocks are different sizes or have different contents.
-   */
-  bool operator!=(const MemoryPool& other) const;
-
-  void reset() override;
-  void reset(char* data, size_t size) override;
-
-  /** Resizes the memory block.
-   *
-   *  Any data that is present in both the old and new sizes will be retained. When enlarging the block, the new
-   *  space that is allocated at the end can either be cleared, or left uninitialised.
-   *
-   *  @param newSize                      the new desired size for the block
-   *  @param initialiseNewSpaceToZero     if the block gets enlarged, this determines  whether to clear the new
-   *                                      section or just leave it uninitialised
-   *  @see ensureSize
-   */
-  void setSize(size_t newSize, bool initialiseNewSpaceToZero = false);
-
-  /** Increases the block's size only if it's smaller than a given size.
-   *
-   *  @param minimumSize                  if the block is already bigger than this size, no action will be taken;
-   *                                      otherwise it will be increased to this size
-   *  @param initialiseNewSpaceToZero     if the block gets enlarged, this determines whether to clear the new section
-   *                                      or just leave it uninitialised
-   *  @see setSize
-   */
-  void ensureSize(size_t minimumSize, bool initialiseNewSpaceToZero = false);
-
-  /** Fills the entire memory block with a repeated byte value.
-   *  This is handy for clearing a block of memory to zero.
-   */
-  void fillWith(int valueToUse);
-
-  /** Adds another block of data to the end of this one.
-   *  The data pointer must not be null. This block's size will be increasedaccordingly.
-   */
-  void append(const void* data, size_t numBytes);
-
-  /** Resizes this block to the given size and fills its contents from the supplied buffer.
-   *  The data pointer must not be null.
-   */
-  void replaceWith(const void* data, size_t numBytes);
-
-  /** Inserts some data into the block.
-   *  The dataToInsert pointer must not be null. This block's size will be increased accordingly.
-   *  If the insert position lies outside the valid range of the block, it will be clipped to within the range before
-   *  being used.
-   */
-  void insert(const void* dataToInsert, size_t numBytesToInsert, size_t insertPosition);
-
-  /** Chops out a section  of the block.
-   *
-   *  This will remove a section of the memory block and close the gap around it, shifting any subsequent data
-   *  downwards and reducing the size of the block.
-   *
-   *  If the range specified goes beyond the size of the block, it will be clipped.
-   */
-  void removeSection(size_t startByte, size_t numBytesToRemove);
-
-  /** Copies data into this MemoryBlock from a memory address.
-   *
-   *  @param srcData              the memory location of the data to copy into this block
-   *  @param destinationOffset    the offset in this block at which the data being copied should begin
-   *  @param numBytes             how much to copy in (if this goes beyond the size of the memory block,
-   *                              it will be clipped so not to do anything nasty)
-   */
-  void copyFrom(const void* srcData, ssize_t destinationOffset, size_t numBytes);
-};
-
-class ROCKETMQCLIENT_API MemoryView : public MemoryBlock {
- public:
-  MemoryView(MemoryBlockPtr2 origin, size_t offset) : MemoryView(origin, offset, origin->getSize() - offset) {}
-  MemoryView(MemoryBlockPtr2 origin, size_t offset, size_t size)
-      : MemoryBlock(origin->getData() + offset, size), origin_(origin) {}
-
-  void reset() override;
-  void reset(char* data, size_t size) override;
-
- private:
-  MemoryBlockPtr2 origin_;
-};
-
-}  // namespace rocketmq
-
-#endif  // __DATA_BLOCK_H__
diff --git a/include/DefaultMQProducer.h b/include/DefaultMQProducer.h
index 2219dfe..e34f94e 100644
--- a/include/DefaultMQProducer.h
+++ b/include/DefaultMQProducer.h
@@ -84,7 +84,7 @@ class ROCKETMQCLIENT_API DefaultMQProducer : public MQProducer, public DefaultMQ
   void setRPCHook(RPCHookPtr rpcHook);
 
  protected:
-  std::shared_ptr<MQProducer> m_producerDelegate;
+  std::shared_ptr<MQProducer> producer_impl_;
 };
 
 }  // namespace rocketmq
diff --git a/include/DefaultMQPushConsumer.h b/include/DefaultMQPushConsumer.h
index 83e4732..6505712 100755
--- a/include/DefaultMQPushConsumer.h
+++ b/include/DefaultMQPushConsumer.h
@@ -53,7 +53,7 @@ class ROCKETMQCLIENT_API DefaultMQPushConsumer : public MQPushConsumer, public D
   void setRPCHook(RPCHookPtr rpcHook);
 
  protected:
-  std::shared_ptr<MQPushConsumer> m_pushConsumerDelegate;
+  std::shared_ptr<MQPushConsumer> push_consumer_impl_;
 };
 
 }  // namespace rocketmq
diff --git a/include/MQMessage.h b/include/MQMessage.h
index 3016ec5..5fc5776 100644
--- a/include/MQMessage.h
+++ b/include/MQMessage.h
@@ -17,7 +17,7 @@
 #ifndef ROCKETMQ_MQMESSAGE_H_
 #define ROCKETMQ_MQMESSAGE_H_
 
-#include <cstddef>  // std::nullptr_t
+#include <algorithm>  // std::move
 
 #include "Message.h"
 #include "MQMessageConst.h"
@@ -47,6 +47,7 @@ class ROCKETMQCLIENT_API MQMessage : virtual public Message  // interface
 
   // copy constructor
   MQMessage(const MQMessage& other) : message_impl_(other.message_impl_) {}
+  MQMessage(MQMessage&& other) : message_impl_(std::move(other.message_impl_)) {}
 
   // assign operator
   MQMessage& operator=(const MQMessage& other) {
@@ -56,9 +57,8 @@ class ROCKETMQCLIENT_API MQMessage : virtual public Message  // interface
     return *this;
   }
 
-  bool operator==(std::nullptr_t) noexcept { return nullptr == message_impl_; }
-
-  friend bool operator==(std::nullptr_t, const MQMessage& message) noexcept { return nullptr == message.message_impl_; }
+  bool operator==(std::nullptr_t) const noexcept { return nullptr == message_impl_; }
+  friend bool operator==(std::nullptr_t, const MQMessage& message) noexcept;
 
   // convert to boolean
   operator bool() noexcept { return nullptr != message_impl_; }
@@ -92,7 +92,6 @@ class ROCKETMQCLIENT_API MQMessage : virtual public Message  // interface
   void setFlag(int32_t flag) override;
 
   const std::string& getBody() const override;
-  void setBody(const char* body, int len) override;
   void setBody(const std::string& body) override;
   void setBody(std::string&& body) override;
 
diff --git a/include/MQMessageExt.h b/include/MQMessageExt.h
index 0001f70..a6d8723 100644
--- a/include/MQMessageExt.h
+++ b/include/MQMessageExt.h
@@ -43,6 +43,7 @@ class ROCKETMQCLIENT_API MQMessageExt : public MQMessage,          // base
 
   // copy constructor
   MQMessageExt(const MQMessageExt& other) : MQMessage(other) {}
+  MQMessageExt(MQMessageExt&& other) : MQMessage(std::move(other)) {}
 
   // assign operator
   MQMessageExt& operator=(const MQMessageExt& other) {
diff --git a/include/MQMessageQueue.h b/include/MQMessageQueue.h
index 8fe5940..bfe9fb9 100644
--- a/include/MQMessageQueue.h
+++ b/include/MQMessageQueue.h
@@ -14,53 +14,50 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __MQ_MESSAGE_QUEUE_H__
-#define __MQ_MESSAGE_QUEUE_H__
+#ifndef ROCKETMQ_MQMESSAGEQUEUE_H_
+#define ROCKETMQ_MQMESSAGEQUEUE_H_
 
-#include <sstream>
-#include <string>
+#include <string>  // std::string
 
 #include "RocketMQClient.h"
 
 namespace rocketmq {
 
 /**
- * MQ(T,B,ID)
+ * MessageQueue(Topic, BrokerName, QueueId)
  */
 class ROCKETMQCLIENT_API MQMessageQueue {
  public:
   MQMessageQueue();
   MQMessageQueue(const std::string& topic, const std::string& brokerName, int queueId);
+
   MQMessageQueue(const MQMessageQueue& other);
   MQMessageQueue& operator=(const MQMessageQueue& other);
 
-  const std::string& getTopic() const;
-  void setTopic(const std::string& topic);
-
-  const std::string& getBrokerName() const;
-  void setBrokerName(const std::string& brokerName);
-
-  int getQueueId() const;
-  void setQueueId(int queueId);
-
   bool operator==(const MQMessageQueue& mq) const;
   bool operator!=(const MQMessageQueue& mq) const { return !operator==(mq); }
 
   bool operator<(const MQMessageQueue& mq) const;
   int compareTo(const MQMessageQueue& mq) const;
 
-  std::string toString() const {
-    std::stringstream ss;
-    ss << "MessageQueue [topic=" << m_topic << ", brokerName=" << m_brokerName << ", queueId=" << m_queueId << "]";
-    return ss.str();
-  }
+  std::string toString() const;
+
+ public:
+  inline const std::string& getTopic() const { return topic_; };
+  inline void setTopic(const std::string& topic) { topic_ = topic; };
+
+  inline const std::string& getBrokerName() const { return broker_name_; };
+  inline void setBrokerName(const std::string& broker_name) { broker_name_ = broker_name; };
+
+  inline int getQueueId() const { return queue_id_; };
+  inline void setQueueId(int queue_id) { queue_id_ = queue_id; };
 
  private:
-  std::string m_topic;
-  std::string m_brokerName;
-  int m_queueId;
+  std::string topic_;
+  std::string broker_name_;
+  int queue_id_;
 };
 
 }  // namespace rocketmq
 
-#endif  // __MQ_MESSAGE_QUEUE_H__
+#endif  // ROCKETMQ_MQMESSAGEQUEUE_H_
diff --git a/include/Message.h b/include/Message.h
index 0320c0e..e4f21c4 100644
--- a/include/Message.h
+++ b/include/Message.h
@@ -70,7 +70,6 @@ class ROCKETMQCLIENT_API Message {
 
   // body
   virtual const std::string& getBody() const = 0;
-  virtual void setBody(const char* body, int len) = 0;
   virtual void setBody(const std::string& body) = 0;
   virtual void setBody(std::string&& body) = 0;
 
diff --git a/include/RPCHook.h b/include/RPCHook.h
index 5ee88b6..515b2bc 100644
--- a/include/RPCHook.h
+++ b/include/RPCHook.h
@@ -14,11 +14,11 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __RPC_HOOK_H__
-#define __RPC_HOOK_H__
+#ifndef ROCKETMQ_RPCHOOK_H_
+#define ROCKETMQ_RPCHOOK_H_
 
-#include <memory>
-#include <string>
+#include <memory>  // std::shared_ptr
+#include <string>  // std::string
 
 #include "RemotingCommand.h"
 
@@ -41,4 +41,4 @@ class ROCKETMQCLIENT_API RPCHook {
 
 }  // namespace rocketmq
 
-#endif  // __RPC_HOOK_H__
+#endif  // ROCKETMQ_RPCHOOK_H_
diff --git a/include/RemotingCommand.h b/include/RemotingCommand.h
index 2fa8a27..6ad14e8 100644
--- a/include/RemotingCommand.h
+++ b/include/RemotingCommand.h
@@ -14,15 +14,17 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __REMOTING_COMMAND_H__
-#define __REMOTING_COMMAND_H__
+#ifndef ROCKETMQ_REMOTINGCOMMAND_H_
+#define ROCKETMQ_REMOTINGCOMMAND_H_
 
-#include <map>
-#include <memory>
-#include <typeindex>
+#include <exception>  // std::exception
+#include <map>        // std::map
+#include <memory>     // std::unique_ptr, std::shared_ptr
+#include <string>     // std::string
+#include <typeindex>  // std::type_index
 
+#include "ByteArray.h"
 #include "CommandCustomHeader.h"
-#include "DataBlock.h"
 #include "MQClientException.h"
 
 namespace rocketmq {
@@ -32,7 +34,7 @@ class ROCKETMQCLIENT_API RemotingCommand {
   static int32_t createNewRequestId();
 
  public:
-  RemotingCommand() : m_code(0) {}
+  RemotingCommand() : code_(0) {}
   RemotingCommand(int32_t code, CommandCustomHeader* customHeader = nullptr);
   RemotingCommand(int32_t code, const std::string& remark, CommandCustomHeader* customHeader = nullptr);
   RemotingCommand(int32_t code,
@@ -42,78 +44,77 @@ class ROCKETMQCLIENT_API RemotingCommand {
                   int32_t flag,
                   const std::string& remark,
                   CommandCustomHeader* customHeader);
+
   RemotingCommand(RemotingCommand&& command);
 
   virtual ~RemotingCommand();
 
-  int32_t getCode() const;
-  void setCode(int32_t code);
-
-  int32_t getVersion() const;
-
-  int32_t getOpaque() const;
-  void setOpaque(int32_t opaque);
-
-  int32_t getFlag() const;
-
-  const std::string& getRemark() const;
-  void setRemark(const std::string& mark);
-
+ public:
   bool isResponseType();
   void markResponseType();
 
   bool isOnewayRPC();
   void markOnewayRPC();
 
-  void addExtField(const std::string& key, const std::string& value);
-
   CommandCustomHeader* readCustomHeader() const;
 
-  MemoryBlockPtr2 getBody() const;
-  void setBody(MemoryBlock* body);
-  void setBody(MemoryBlockPtr2 body);
-  void setBody(const std::string& body);
-
  public:
-  MemoryBlockPtr encode() const;
+  ByteArrayRef encode() const;
 
   template <class H>
-  H* decodeCommandCustomHeader(bool useCache);
+  H* decodeCommandCustomHeader(bool useCache = true);
 
-  template <class H>
-  H* decodeCommandCustomHeader();
-
-  static RemotingCommand* Decode(MemoryBlockPtr2 package, bool havePackageLen = false);
+  static RemotingCommand* Decode(ByteArrayRef array, bool hasPackageLength = false);
 
   std::string toString() const;
 
+ public:
+  inline int32_t code() const { return code_; }
+  inline void set_code(int32_t code) { code_ = code; }
+
+  inline int32_t version() const { return version_; }
+
+  inline int32_t opaque() const { return opaque_; }
+  inline void set_opaque(int32_t opaque) { opaque_ = opaque; }
+
+  inline int32_t flag() const { return flag_; }
+
+  inline const std::string& remark() const { return remark_; }
+  inline void set_remark(const std::string& remark) { remark_ = remark; }
+
+  inline void set_ext_field(const std::string& name, const std::string& value) { ext_fields_[name] = value; }
+
+  inline ByteArrayRef body() const { return body_; }
+  inline void set_body(ByteArrayRef body) { body_ = std::move(body); }
+  inline void set_body(const std::string& body) { body_ = stoba(body); }
+  inline void set_body(std::string&& body) { body_ = stoba(std::move(body)); }
+
  private:
-  int32_t m_code;
-  std::string m_language;
-  int32_t m_version;
-  int32_t m_opaque;
-  int32_t m_flag;
-  std::string m_remark;
-  std::map<std::string, std::string> m_extFields;
-  std::unique_ptr<CommandCustomHeader> m_customHeader;  // transient
-
-  MemoryBlockPtr2 m_body;  // transient
+  int32_t code_;
+  std::string language_;
+  int32_t version_;
+  int32_t opaque_;
+  int32_t flag_;
+  std::string remark_;
+  std::map<std::string, std::string> ext_fields_;
+
+  std::unique_ptr<CommandCustomHeader> custom_header_;  // transient
+
+  ByteArrayRef body_;  // transient
 };
 
 template <class H>
 H* RemotingCommand::decodeCommandCustomHeader(bool useCache) {
-  auto* cache = m_customHeader.get();
-  if (cache != nullptr && useCache && std::type_index(typeid(*cache)) == std::type_index(typeid(H))) {
-    return static_cast<H*>(m_customHeader.get());
+  if (useCache) {
+    auto* cache = custom_header_.get();
+    if (cache != nullptr && std::type_index(typeid(*cache)) == std::type_index(typeid(H))) {
+      return static_cast<H*>(custom_header_.get());
+    }
   }
-  return decodeCommandCustomHeader<H>();
-}
 
-template <class H>
-H* RemotingCommand::decodeCommandCustomHeader() {
   try {
-    H* header = H::Decode(m_extFields);
-    m_customHeader.reset(header);
+    H* header = H::Decode(ext_fields_);
+    custom_header_.reset(header);
     return header;
   } catch (std::exception& e) {
     THROW_MQEXCEPTION(RemotingCommandException, e.what(), -1);
@@ -122,4 +123,4 @@ H* RemotingCommand::decodeCommandCustomHeader() {
 
 }  // namespace rocketmq
 
-#endif  // __REMOTING_COMMAND_H__
+#endif  // ROCKETMQ_REMOTINGCOMMAND_H_
diff --git a/include/RocketMQClient.h b/include/RocketMQClient.h
index d624793..39d5ccc 100644
--- a/include/RocketMQClient.h
+++ b/include/RocketMQClient.h
@@ -19,8 +19,10 @@
 
 #ifdef __cplusplus
 #include <cstdint>
+#include <cstddef>
 #else
 #include <stdint.h>
+#include <stddef.h>
 #endif
 
 #ifdef WIN32
diff --git a/src/ClientRemotingProcessor.cpp b/src/ClientRemotingProcessor.cpp
index 97286a1..6361628 100644
--- a/src/ClientRemotingProcessor.cpp
+++ b/src/ClientRemotingProcessor.cpp
@@ -35,8 +35,8 @@ ClientRemotingProcessor::~ClientRemotingProcessor() = default;
 
 RemotingCommand* ClientRemotingProcessor::processRequest(TcpTransportPtr channel, RemotingCommand* request) {
   const auto& addr = channel->getPeerAddrAndPort();
-  LOG_DEBUG_NEW("processRequest, code:{}, addr:{}", request->getCode(), addr);
-  switch (request->getCode()) {
+  LOG_DEBUG_NEW("processRequest, code:{}, addr:{}", request->code(), addr);
+  switch (request->code()) {
     case CHECK_TRANSACTION_STATE:
       return checkTransactionState(addr, request);
     case NOTIFY_CONSUMER_IDS_CHANGED:
@@ -63,9 +63,10 @@ RemotingCommand* ClientRemotingProcessor::checkTransactionState(const std::strin
   auto* requestHeader = request->decodeCommandCustomHeader<CheckTransactionStateRequestHeader>();
   assert(requestHeader != nullptr);
 
-  auto requestBody = request->getBody();
-  if (requestBody != nullptr && requestBody->getSize() > 0) {
-    MessageExtPtr messageExt = MessageDecoder::decode(*requestBody);
+  auto requestBody = request->body();
+  if (requestBody != nullptr && requestBody->size() > 0) {
+    std::unique_ptr<ByteBuffer> byteBuffer(ByteBuffer::wrap(requestBody));
+    MessageExtPtr messageExt = MessageDecoder::decode(*byteBuffer);
     if (messageExt != nullptr) {
       const auto& transactionId = messageExt->getProperty(MQMessageConst::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
       if (!transactionId.empty()) {
@@ -101,8 +102,8 @@ RemotingCommand* ClientRemotingProcessor::notifyConsumerIdsChanged(RemotingComma
 
 RemotingCommand* ClientRemotingProcessor::resetOffset(RemotingCommand* request) {
   auto* responseHeader = request->decodeCommandCustomHeader<ResetOffsetRequestHeader>();
-  auto requestBody = request->getBody();
-  if (requestBody != nullptr && requestBody->getSize() > 0) {
+  auto requestBody = request->body();
+  if (requestBody != nullptr && requestBody->size() > 0) {
     std::unique_ptr<ResetOffsetBody> body(ResetOffsetBody::Decode(*requestBody));
     if (body != nullptr) {
       m_clientInstance->resetOffset(responseHeader->getGroup(), responseHeader->getTopic(), body->getOffsetTable());
@@ -127,12 +128,11 @@ RemotingCommand* ClientRemotingProcessor::getConsumerRunningInfo(const std::stri
       /*string jstack = UtilAll::jstack();
        consumerRunningInfo->setJstack(jstack);*/
     }
-    response->setCode(SUCCESS);
-    auto body = runningInfo->encode();
-    response->setBody(body);
+    response->set_code(SUCCESS);
+    response->set_body(runningInfo->encode());
   } else {
-    response->setCode(SYSTEM_ERROR);
-    response->setRemark("The Consumer Group not exist in this consumer");
+    response->set_code(SYSTEM_ERROR);
+    response->set_remark("The Consumer Group not exist in this consumer");
   }
 
   return response.release();
@@ -160,16 +160,16 @@ RemotingCommand* ClientRemotingProcessor::receiveReplyMessage(RemotingCommand* r
       msg->setStoreHost(string2SocketAddress(requestHeader->getStoreHost()));
     }
 
-    auto body = request->getBody();
-    if ((requestHeader->getSysFlag() & MessageSysFlag::CompressedFlag) == MessageSysFlag::CompressedFlag) {
-      std::string outbody;
-      if (UtilAll::inflate(body->getData(), body->getSize(), outbody)) {
-        msg->setBody(std::move(outbody));
+    auto body = request->body();
+    if ((requestHeader->getSysFlag() & MessageSysFlag::COMPRESSED_FLAG) == MessageSysFlag::COMPRESSED_FLAG) {
+      std::string origin_body;
+      if (UtilAll::inflate(*body, origin_body)) {
+        msg->setBody(std::move(origin_body));
       } else {
         LOG_WARN_NEW("err when uncompress constant");
       }
     } else {
-      msg->setBody(body->getData(), body->getSize());
+      msg->setBody(std::string(body->array(), body->size()));
     }
 
     msg->setFlag(requestHeader->getFlag());
@@ -182,12 +182,12 @@ RemotingCommand* ClientRemotingProcessor::receiveReplyMessage(RemotingCommand* r
 
     processReplyMessage(std::move(msg));
 
-    response->setCode(MQResponseCode::SUCCESS);
-    response->setRemark(null);
+    response->set_code(MQResponseCode::SUCCESS);
+    response->set_remark(null);
   } catch (const std::exception& e) {
     LOG_WARN_NEW("unknown err when receiveReplyMsg, {}", e.what());
-    response->setCode(MQResponseCode::SYSTEM_ERROR);
-    response->setRemark("process reply message fail");
+    response->set_code(MQResponseCode::SYSTEM_ERROR);
+    response->set_remark("process reply message fail");
   }
 
   return response.release();
diff --git a/src/MQClientAPIImpl.cpp b/src/MQClientAPIImpl.cpp
index 1dcc163..a1868b6 100644
--- a/src/MQClientAPIImpl.cpp
+++ b/src/MQClientAPIImpl.cpp
@@ -74,7 +74,7 @@ void MQClientAPIImpl::createTopic(const std::string& addr, const std::string& de
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       return;
     }
@@ -82,7 +82,7 @@ void MQClientAPIImpl::createTopic(const std::string& addr, const std::string& de
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 SendResult* MQClientAPIImpl::sendMessage(const std::string& addr,
@@ -127,7 +127,7 @@ SendResult* MQClientAPIImpl::sendMessage(const std::string& addr,
   }
 
   RemotingCommand request(code, header.release());
-  request.setBody(msg->getBody());
+  request.set_body(msg->getBody());
 
   switch (communicationMode) {
     case ComMode_ONEWAY:
@@ -190,7 +190,7 @@ SendResult* MQClientAPIImpl::processSendResponse(const std::string& brokerName,
                                                  const MessagePtr msg,
                                                  RemotingCommand* response) {
   SendStatus sendStatus = SEND_OK;
-  switch (response->getCode()) {
+  switch (response->code()) {
     case FLUSH_DISK_TIMEOUT:
       sendStatus = SEND_FLUSH_DISK_TIMEOUT;
       break;
@@ -204,7 +204,7 @@ SendResult* MQClientAPIImpl::processSendResponse(const std::string& brokerName,
       sendStatus = SEND_OK;
       break;
     default:
-      THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+      THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
       return nullptr;
   }
 
@@ -278,7 +278,7 @@ PullResult* MQClientAPIImpl::pullMessageSync(const std::string& addr, RemotingCo
 
 PullResult* MQClientAPIImpl::processPullResponse(RemotingCommand* response) {
   PullStatus pullStatus = NO_NEW_MSG;
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS:
       pullStatus = FOUND;
       break;
@@ -286,7 +286,7 @@ PullResult* MQClientAPIImpl::processPullResponse(RemotingCommand* response) {
       pullStatus = NO_NEW_MSG;
       break;
     case PULL_RETRY_IMMEDIATELY:
-      if ("OFFSET_OVERFLOW_BADLY" == response->getRemark()) {
+      if ("OFFSET_OVERFLOW_BADLY" == response->remark()) {
         pullStatus = NO_LATEST_MSG;
       } else {
         pullStatus = NO_MATCHED_MSG;
@@ -296,7 +296,7 @@ PullResult* MQClientAPIImpl::processPullResponse(RemotingCommand* response) {
       pullStatus = OFFSET_ILLEGAL;
       break;
     default:
-      THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+      THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
   }
 
   // return of decodeCommandCustomHeader is non-null
@@ -304,7 +304,7 @@ PullResult* MQClientAPIImpl::processPullResponse(RemotingCommand* response) {
   assert(responseHeader != nullptr);
 
   return new PullResultExt(pullStatus, responseHeader->nextBeginOffset, responseHeader->minOffset,
-                           responseHeader->maxOffset, (int)responseHeader->suggestWhichBrokerId, response->getBody());
+                           responseHeader->maxOffset, (int)responseHeader->suggestWhichBrokerId, response->body());
 }
 
 MQMessageExt MQClientAPIImpl::viewMessage(const std::string& addr, int64_t phyoffset, int timeoutMillis) {
@@ -315,7 +315,7 @@ MQMessageExt MQClientAPIImpl::viewMessage(const std::string& addr, int64_t phyof
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       // TODO: ...
     }
@@ -323,7 +323,7 @@ MQMessageExt MQClientAPIImpl::viewMessage(const std::string& addr, int64_t phyof
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 int64_t MQClientAPIImpl::searchOffset(const std::string& addr,
@@ -340,7 +340,7 @@ int64_t MQClientAPIImpl::searchOffset(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       auto* responseHeader = response->decodeCommandCustomHeader<SearchOffsetResponseHeader>();
       assert(responseHeader != nullptr);
@@ -350,7 +350,7 @@ int64_t MQClientAPIImpl::searchOffset(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 int64_t MQClientAPIImpl::getMaxOffset(const std::string& addr,
@@ -365,7 +365,7 @@ int64_t MQClientAPIImpl::getMaxOffset(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       auto* responseHeader = response->decodeCommandCustomHeader<GetMaxOffsetResponseHeader>(GET_MAX_OFFSET);
       return responseHeader->offset;
@@ -374,7 +374,7 @@ int64_t MQClientAPIImpl::getMaxOffset(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 int64_t MQClientAPIImpl::getMinOffset(const std::string& addr,
@@ -389,7 +389,7 @@ int64_t MQClientAPIImpl::getMinOffset(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       auto* responseHeader = response->decodeCommandCustomHeader<GetMinOffsetResponseHeader>();
       assert(responseHeader != nullptr);
@@ -399,7 +399,7 @@ int64_t MQClientAPIImpl::getMinOffset(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 int64_t MQClientAPIImpl::getEarliestMsgStoretime(const std::string& addr,
@@ -414,7 +414,7 @@ int64_t MQClientAPIImpl::getEarliestMsgStoretime(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       auto* responseHeader = response->decodeCommandCustomHeader<GetEarliestMsgStoretimeResponseHeader>();
       assert(responseHeader != nullptr);
@@ -424,7 +424,7 @@ int64_t MQClientAPIImpl::getEarliestMsgStoretime(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::getConsumerIdListByGroup(const std::string& addr,
@@ -438,10 +438,10 @@ void MQClientAPIImpl::getConsumerIdListByGroup(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
-      auto responseBody = response->getBody();
-      if (responseBody != nullptr && responseBody->getSize() > 0) {
+      auto responseBody = response->body();
+      if (responseBody != nullptr && responseBody->size() > 0) {
         std::unique_ptr<GetConsumerListByGroupResponseBody> body(
             GetConsumerListByGroupResponseBody::Decode(*responseBody));
         cids = std::move(body->consumerIdList);
@@ -454,7 +454,7 @@ void MQClientAPIImpl::getConsumerIdListByGroup(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 int64_t MQClientAPIImpl::queryConsumerOffset(const std::string& addr,
@@ -464,7 +464,7 @@ int64_t MQClientAPIImpl::queryConsumerOffset(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       auto* responseHeader = response->decodeCommandCustomHeader<QueryConsumerOffsetResponseHeader>();
       assert(responseHeader != nullptr);
@@ -474,7 +474,7 @@ int64_t MQClientAPIImpl::queryConsumerOffset(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::updateConsumerOffset(const std::string& addr,
@@ -484,7 +484,7 @@ void MQClientAPIImpl::updateConsumerOffset(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       return;
     }
@@ -492,7 +492,7 @@ void MQClientAPIImpl::updateConsumerOffset(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::updateConsumerOffsetOneway(const std::string& addr,
@@ -505,11 +505,11 @@ void MQClientAPIImpl::updateConsumerOffsetOneway(const std::string& addr,
 
 void MQClientAPIImpl::sendHearbeat(const std::string& addr, HeartbeatData* heartbeatData, long timeoutMillis) {
   RemotingCommand request(HEART_BEAT, nullptr);
-  request.setBody(heartbeatData->encode());
+  request.set_body(heartbeatData->encode());
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       LOG_DEBUG_NEW("sendHeartbeat to broker:{} success", addr);
       return;
@@ -518,7 +518,7 @@ void MQClientAPIImpl::sendHearbeat(const std::string& addr, HeartbeatData* heart
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::unregisterClient(const std::string& addr,
@@ -530,7 +530,7 @@ void MQClientAPIImpl::unregisterClient(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS:
       LOG_INFO("unregisterClient to:%s success", addr.c_str());
       return;
@@ -538,15 +538,15 @@ void MQClientAPIImpl::unregisterClient(const std::string& addr,
       break;
   }
 
-  LOG_WARN("unregisterClient fail:%s, %d", response->getRemark().c_str(), response->getCode());
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  LOG_WARN("unregisterClient fail:%s, %d", response->remark().c_str(), response->code());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::endTransactionOneway(const std::string& addr,
                                            EndTransactionRequestHeader* requestHeader,
                                            const std::string& remark) {
   RemotingCommand request(END_TRANSACTION, requestHeader);
-  request.setRemark(remark);
+  request.set_remark(remark);
 
   m_remotingClient->invokeOneway(addr, request);
 }
@@ -569,7 +569,7 @@ void MQClientAPIImpl::consumerSendMessageBack(const std::string& addr,
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
       return;
     }
@@ -577,7 +577,7 @@ void MQClientAPIImpl::consumerSendMessageBack(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::lockBatchMQ(const std::string& addr,
@@ -585,14 +585,14 @@ void MQClientAPIImpl::lockBatchMQ(const std::string& addr,
                                   std::vector<MQMessageQueue>& mqs,
                                   int timeoutMillis) {
   RemotingCommand request(LOCK_BATCH_MQ, nullptr);
-  request.setBody(requestBody->encode());
+  request.set_body(requestBody->encode());
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
-      auto requestBody = response->getBody();
-      if (requestBody != nullptr && requestBody->getSize() > 0) {
+      auto requestBody = response->body();
+      if (requestBody != nullptr && requestBody->size() > 0) {
         std::unique_ptr<LockBatchResponseBody> body(LockBatchResponseBody::Decode(*requestBody));
         mqs = body->getLockOKMQSet();
       } else {
@@ -604,7 +604,7 @@ void MQClientAPIImpl::lockBatchMQ(const std::string& addr,
       break;
   }
 
-  THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
 }
 
 void MQClientAPIImpl::unlockBatchMQ(const std::string& addr,
@@ -612,14 +612,14 @@ void MQClientAPIImpl::unlockBatchMQ(const std::string& addr,
                                     int timeoutMillis,
                                     bool oneway) {
   RemotingCommand request(UNLOCK_BATCH_MQ, nullptr);
-  request.setBody(requestBody->encode());
+  request.set_body(requestBody->encode());
 
   if (oneway) {
     m_remotingClient->invokeOneway(addr, request);
   } else {
     std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(addr, request, timeoutMillis));
     assert(response != nullptr);
-    switch (response->getCode()) {
+    switch (response->code()) {
       case SUCCESS: {
         return;
       } break;
@@ -627,7 +627,7 @@ void MQClientAPIImpl::unlockBatchMQ(const std::string& addr,
         break;
     }
 
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->remark(), response->code());
   }
 }
 
@@ -636,21 +636,19 @@ TopicRouteData* MQClientAPIImpl::getTopicRouteInfoFromNameServer(const std::stri
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(null, request, timeoutMillis));
   assert(response != nullptr);
-  switch (response->getCode()) {
-    case TOPIC_NOT_EXIST: {
-      break;
-    }
+  switch (response->code()) {
     case SUCCESS: {
-      auto responseBody = response->getBody();
-      if (responseBody != nullptr && responseBody->getSize() > 0) {
+      auto responseBody = response->body();
+      if (responseBody != nullptr && responseBody->size() > 0) {
         return TopicRouteData::Decode(*responseBody);
       }
     }
+    case TOPIC_NOT_EXIST:
     default:
       break;
   }
 
-  THROW_MQEXCEPTION(MQClientException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQClientException, response->remark(), response->code());
 }
 
 TopicList* MQClientAPIImpl::getTopicListFromNameServer() {
@@ -658,10 +656,10 @@ TopicList* MQClientAPIImpl::getTopicListFromNameServer() {
 
   std::unique_ptr<RemotingCommand> response(m_remotingClient->invokeSync(null, request));
   assert(response != nullptr);
-  switch (response->getCode()) {
+  switch (response->code()) {
     case SUCCESS: {
-      auto responseBody = response->getBody();
-      if (responseBody != nullptr && responseBody->getSize() > 0) {
+      auto responseBody = response->body();
+      if (responseBody != nullptr && responseBody->size() > 0) {
         return TopicList::Decode(*responseBody);
       }
     }
@@ -669,7 +667,7 @@ TopicList* MQClientAPIImpl::getTopicListFromNameServer() {
       break;
   }
 
-  THROW_MQEXCEPTION(MQClientException, response->getRemark(), response->getCode());
+  THROW_MQEXCEPTION(MQClientException, response->remark(), response->code());
 }
 
 int MQClientAPIImpl::wipeWritePermOfBroker(const std::string& namesrvAddr,
diff --git a/src/common/ByteOrder.h b/src/common/ByteOrder.h
index cdc52a9..24744fa 100644
--- a/src/common/ByteOrder.h
+++ b/src/common/ByteOrder.h
@@ -17,234 +17,163 @@
 #ifndef ROCKETMQ_COMMON_BYTEORDER_H_
 #define ROCKETMQ_COMMON_BYTEORDER_H_
 
-#include <RocketMQClient.h>
+#include <cstdlib>  // std::memcpy
+
+#include <type_traits>  // std::enable_if, std::is_integral, std::make_unsigned, std::add_pointer
+
+#include "RocketMQClient.h"
 
 namespace rocketmq {
 
+enum ByteOrder { BO_BIG_ENDIAN, BO_LITTLE_ENDIAN };
+
 /**
  * Contains static methods for converting the byte order between different endiannesses.
  */
-class ByteOrder {
+class ByteOrderUtil {
  public:
-  //==============================================================================
+  static constexpr ByteOrder native_order() {
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__  // __BYTE_ORDER__ is defined by GCC
+    return ByteOrder::BO_LITTLE_ENDIAN;
+#else
+    return ByteOrder::BO_BIG_ENDIAN;
+#endif
+  }
 
-  /** Swaps the upper and lower bytes of a 16-bit integer. */
-  static uint16_t swap(uint16_t value);
-
-  /** Reverses the order of the 4 bytes in a 32-bit integer. */
-  static uint32_t swap(uint32_t value);
-
-  /** Reverses the order of the 8 bytes in a 64-bit integer. */
-  static uint64_t swap(uint64_t value);
+  /** Returns true if the current CPU is big-endian. */
+  static constexpr bool isBigEndian() { return native_order() == ByteOrder::BO_BIG_ENDIAN; }
 
   //==============================================================================
 
-  /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
-  static uint16_t swapIfBigEndian(uint16_t value);
+  template <typename T, typename F, typename std::enable_if<sizeof(T) == sizeof(F), int>::type = 0>
+  static inline T ReinterpretRawBits(F value) {
+    return *reinterpret_cast<T*>(&value);
+  }
 
-  /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
-  static uint32_t swapIfBigEndian(uint32_t value);
+  static inline uint8_t swap(uint8_t n) { return n; }
 
-  /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
-  static uint64_t swapIfBigEndian(uint64_t value);
-
-  /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
-  static uint16_t swapIfLittleEndian(uint16_t value);
+  /** Swaps the upper and lower bytes of a 16-bit integer. */
+  static inline uint16_t swap(uint16_t n) { return static_cast<uint16_t>((n << 8) | (n >> 8)); }
 
-  /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
-  static uint32_t swapIfLittleEndian(uint32_t value);
+  /** Reverses the order of the 4 bytes in a 32-bit integer. */
+  static inline uint32_t swap(uint32_t n) {
+    return (n << 24) | (n >> 24) | ((n & 0x0000ff00) << 8) | ((n & 0x00ff0000) >> 8);
+  }
 
-  /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
-  static uint64_t swapIfLittleEndian(uint64_t value);
+  /** Reverses the order of the 8 bytes in a 64-bit integer. */
+  static inline uint64_t swap(uint64_t value) {
+    return (((uint64_t)swap((uint32_t)value)) << 32) | swap((uint32_t)(value >> 32));
+  }
 
   //==============================================================================
 
-  /** Turns 4 bytes into a little-endian integer. */
-  static uint32_t littleEndianInt(const void* bytes);
+  /** convert integer to little-endian */
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline typename std::make_unsigned<T>::type NorminalLittleEndian(T value) {
+#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+    return swap(static_cast<typename std::make_unsigned<T>::type>(value));
+#else
+    return static_cast<typename std::make_unsigned<T>::type>(value);
+#endif
+  }
+
+  /** convert integer to big-endian */
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline typename std::make_unsigned<T>::type NorminalBigEndian(T value) {
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+    return swap(static_cast<typename std::make_unsigned<T>::type>(value));
+#else
+    return static_cast<typename std::make_unsigned<T>::type>(value);
+#endif
+  }
 
-  /** Turns 8 bytes into a little-endian integer. */
-  static uint64_t littleEndianInt64(const void* bytes);
+  //==============================================================================
 
-  /** Turns 2 bytes into a little-endian integer. */
-  static uint16_t littleEndianShort(const void* bytes);
+  template <typename T, int Enable = 0>
+  static inline T Read(const char* bytes) {
+    T value;
+    std::memcpy(&value, bytes, sizeof(T));
+    return value;
+  }
+
+  template <typename T, typename std::enable_if<sizeof(T) <= 8, int>::value = 0>
+  static inline T Read(const char* bytes) {
+    T value;
+    for (size_t i = 0; i < sizeof(T); i++) {
+      ((char*)&value)[i] = bytes[i];
+    }
+    return value;
+  }
+
+  template <typename T, int Enable = 0>
+  static inline void Read(T* value, const char* bytes) {
+    std::memcpy(value, bytes, sizeof(T));
+  }
+
+  template <typename T, typename std::enable_if<sizeof(T) <= 8, int>::value = 0>
+  static inline void Read(T* value, const char* bytes) {
+    for (size_t i = 0; i < sizeof(T); i++) {
+      ((char*)value)[i] = bytes[i];
+    }
+  }
 
-  /** Turns 4 bytes into a big-endian integer. */
-  static uint32_t bigEndianInt(const void* bytes);
+  //==============================================================================
 
-  /** Turns 8 bytes into a big-endian integer. */
-  static uint64_t bigEndianInt64(const void* bytes);
+  template <typename T, int Enable = 0>
+  static inline void Write(char* bytes, T value) {
+    std::memcpy(bytes, &value, sizeof(T));
+  }
 
-  /** Turns 2 bytes into a big-endian integer. */
-  static uint16_t bigEndianShort(const void* bytes);
+  template <typename T, typename std::enable_if<sizeof(T) <= 8, int>::value = 0>
+  static inline void Write(char* bytes, T value) {
+    for (size_t i = 0; i < sizeof(T); i++) {
+      bytes[i] = ((char*)&value)[i];
+    }
+  }
 
   //==============================================================================
 
-  /** Converts 3 little-endian bytes into a signed 24-bit value (which is
-   * sign-extended to 32 bits). */
-  static int littleEndian24Bit(const void* bytes);
-
-  /** Converts 3 big-endian bytes into a signed 24-bit value (which is
-   * sign-extended to 32 bits). */
-  static int bigEndian24Bit(const void* bytes);
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline T ReadLittleEndian(const char* bytes) {
+    auto value = Read<T>(bytes);
+    return NorminalLittleEndian(value);
+  }
 
-  /** Copies a 24-bit number to 3 little-endian bytes. */
-  static void littleEndian24BitToChars(int value, void* destBytes);
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline T ReadBigEndian(const char* bytes) {
+    auto value = Read<T>(bytes);
+    return NorminalBigEndian(value);
+  }
 
-  /** Copies a 24-bit number to 3 big-endian bytes. */
-  static void bigEndian24BitToChars(int value, void* destBytes);
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline T Read(const char* bytes, bool big_endian) {
+    return big_endian ? ReadBigEndian<T>(bytes) : ReadLittleEndian<T>(bytes);
+  }
 
   //==============================================================================
 
-  /** Returns true if the current CPU is big-endian. */
-  static bool isBigEndian();
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline void WriteLittleEndian(char* bytes, T value) {
+    value = NorminalLittleEndian(value);
+    Write(bytes, value);
+  }
+
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline void WriteBigEndian(char* bytes, T value) {
+    value = NorminalBigEndian(value);
+    Write(bytes, value);
+  }
+
+  template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
+  static inline void Write(char* bytes, T value, bool big_endian) {
+    if (big_endian) {
+      WriteBigEndian(bytes, value);
+    } else {
+      WriteLittleEndian(bytes, value);
+    }
+  }
 };
 
-//==============================================================================
-
-inline uint16_t ByteOrder::swap(uint16_t n) {
-  return static_cast<uint16_t>((n << 8) | (n >> 8));
-}
-
-inline uint32_t ByteOrder::swap(uint32_t n) {
-  return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
-}
-
-inline uint64_t ByteOrder::swap(uint64_t value) {
-  return (((uint64_t)swap((uint32_t)value)) << 32) | swap((uint32_t)(value >> 32));
-}
-
-#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__  //__BYTE_ORDER__ is defined by GCC
-
-inline uint16_t ByteOrder::swapIfBigEndian(const uint16_t v) {
-  return v;
-}
-
-inline uint32_t ByteOrder::swapIfBigEndian(const uint32_t v) {
-  return v;
-}
-
-inline uint64_t ByteOrder::swapIfBigEndian(const uint64_t v) {
-  return v;
-}
-
-inline uint16_t ByteOrder::swapIfLittleEndian(const uint16_t v) {
-  return swap(v);
-}
-
-inline uint32_t ByteOrder::swapIfLittleEndian(const uint32_t v) {
-  return swap(v);
-}
-
-inline uint64_t ByteOrder::swapIfLittleEndian(const uint64_t v) {
-  return swap(v);
-}
-
-inline uint32_t ByteOrder::littleEndianInt(const void* const bytes) {
-  return *static_cast<const uint32_t*>(bytes);
-}
-
-inline uint64_t ByteOrder::littleEndianInt64(const void* const bytes) {
-  return *static_cast<const uint64_t*>(bytes);
-}
-
-inline uint16_t ByteOrder::littleEndianShort(const void* const bytes) {
-  return *static_cast<const uint16_t*>(bytes);
-}
-
-inline uint32_t ByteOrder::bigEndianInt(const void* const bytes) {
-  return swap(*static_cast<const uint32_t*>(bytes));
-}
-
-inline uint64_t ByteOrder::bigEndianInt64(const void* const bytes) {
-  return swap(*static_cast<const uint64_t*>(bytes));
-}
-
-inline uint16_t ByteOrder::bigEndianShort(const void* const bytes) {
-  return swap(*static_cast<const uint16_t*>(bytes));
-}
-
-inline bool ByteOrder::isBigEndian() {
-  return false;
-}
-
-#else  // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-
-inline uint16_t ByteOrder::swapIfBigEndian(const uint16_t v) {
-  return swap(v);
-}
-
-inline uint32_t ByteOrder::swapIfBigEndian(const uint32_t v) {
-  return swap(v);
-}
-
-inline uint64_t ByteOrder::swapIfBigEndian(const uint64_t v) {
-  return swap(v);
-}
-
-inline uint16_t ByteOrder::swapIfLittleEndian(const uint16_t v) {
-  return v;
-}
-
-inline uint32_t ByteOrder::swapIfLittleEndian(const uint32_t v) {
-  return v;
-}
-
-inline uint64_t ByteOrder::swapIfLittleEndian(const uint64_t v) {
-  return v;
-}
-
-inline uint32_t ByteOrder::littleEndianInt(const void* const bytes) {
-  return swap(*static_cast<const uint32_t*>(bytes));
-}
-
-inline uint64_t ByteOrder::littleEndianInt64(const void* const bytes) {
-  return swap(*static_cast<const uint64_t*>(bytes));
-}
-
-inline uint16_t ByteOrder::littleEndianShort(const void* const bytes) {
-  return swap(*static_cast<const uint16_t*>(bytes));
-}
-
-inline uint32_t ByteOrder::bigEndianInt(const void* const bytes) {
-  return *static_cast<const uint32_t*>(bytes);
-}
-
-inline uint64_t ByteOrder::bigEndianInt64(const void* const bytes) {
-  return *static_cast<const uint64_t*>(bytes);
-}
-
-inline uint16_t ByteOrder::bigEndianShort(const void* const bytes) {
-  return *static_cast<const uint16_t*>(bytes);
-}
-
-inline bool ByteOrder::isBigEndian() {
-  return true;
-}
-
-#endif  // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-
-inline int ByteOrder::littleEndian24Bit(const void* const bytes) {
-  return (((int)static_cast<const int8_t*>(bytes)[2]) << 16) | (((int)static_cast<const uint8_t*>(bytes)[1]) << 8) |
-         ((int)static_cast<const uint8_t*>(bytes)[0]);
-}
-
-inline int ByteOrder::bigEndian24Bit(const void* const bytes) {
-  return (((int)static_cast<const int8_t*>(bytes)[0]) << 16) | (((int)static_cast<const uint8_t*>(bytes)[1]) << 8) |
-         ((int)static_cast<const uint8_t*>(bytes)[2]);
-}
-
-inline void ByteOrder::littleEndian24BitToChars(const int value, void* const destBytes) {
-  static_cast<uint8_t*>(destBytes)[0] = (uint8_t)value;
-  static_cast<uint8_t*>(destBytes)[1] = (uint8_t)(value >> 8);
-  static_cast<uint8_t*>(destBytes)[2] = (uint8_t)(value >> 16);
-}
-
-inline void ByteOrder::bigEndian24BitToChars(const int value, void* const destBytes) {
-  static_cast<uint8_t*>(destBytes)[0] = (uint8_t)(value >> 16);
-  static_cast<uint8_t*>(destBytes)[1] = (uint8_t)(value >> 8);
-  static_cast<uint8_t*>(destBytes)[2] = (uint8_t)value;
-}
-
 }  // namespace rocketmq
 
 #endif  // ROCKETMQ_COMMON_BYTEORDER_H_
diff --git a/src/common/ClientRPCHook.cpp b/src/common/ClientRPCHook.cpp
index 356b0cf..6c34852 100644
--- a/src/common/ClientRPCHook.cpp
+++ b/src/common/ClientRPCHook.cpp
@@ -18,7 +18,6 @@
 
 #include <string>
 
-#include "DataBlock.h"
 #include "Logging.h"
 #include "RemotingCommand.h"
 #include "protocol/header/CommandHeader.h"
@@ -51,8 +50,8 @@ void ClientRPCHook::doAfterResponse(const std::string& remoteAddr,
 
 void ClientRPCHook::signCommand(RemotingCommand& command) {
   std::map<std::string, std::string> headerMap;
-  headerMap.insert(std::make_pair(SessionCredentials::AccessKey, sessionCredentials_.getAccessKey()));
-  headerMap.insert(std::make_pair(SessionCredentials::ONSChannelKey, sessionCredentials_.getAuthChannel()));
+  headerMap.insert(std::make_pair(SessionCredentials::AccessKey, session_credentials_.getAccessKey()));
+  headerMap.insert(std::make_pair(SessionCredentials::ONSChannelKey, session_credentials_.getAuthChannel()));
 
   LOG_DEBUG_NEW("before insert declared filed, MAP SIZE is:{}", headerMap.size());
   auto* header = command.readCustomHeader();
@@ -65,20 +64,20 @@ void ClientRPCHook::signCommand(RemotingCommand& command) {
   for (const auto& it : headerMap) {
     totalMsg.append(it.second);
   }
-  auto body = command.getBody();
-  if (body != nullptr && body->getSize() > 0) {
-    LOG_DEBUG_NEW("request have msgBody, length is:{}", body->getSize());
-    totalMsg.append(body->getData(), body->getSize());
+  auto body = command.body();
+  if (body != nullptr && body->size() > 0) {
+    LOG_DEBUG_NEW("request have msgBody, length is:{}", body->size());
+    totalMsg.append(body->array(), body->size());
   }
   LOG_DEBUG_NEW("total msg info are:{}, size is:{}", totalMsg, totalMsg.size());
 
   char* sign =
-      rocketmqSignature::spas_sign(totalMsg.c_str(), totalMsg.size(), sessionCredentials_.getSecretKey().c_str());
+      rocketmqSignature::spas_sign(totalMsg.c_str(), totalMsg.size(), session_credentials_.getSecretKey().c_str());
   if (sign != nullptr) {
     std::string signature(static_cast<const char*>(sign));
-    command.addExtField(SessionCredentials::Signature, signature);
-    command.addExtField(SessionCredentials::AccessKey, sessionCredentials_.getAccessKey());
-    command.addExtField(SessionCredentials::ONSChannelKey, sessionCredentials_.getAuthChannel());
+    command.set_ext_field(SessionCredentials::Signature, signature);
+    command.set_ext_field(SessionCredentials::AccessKey, session_credentials_.getAccessKey());
+    command.set_ext_field(SessionCredentials::ONSChannelKey, session_credentials_.getAuthChannel());
     rocketmqSignature::spas_mem_free(sign);
   } else {
     LOG_ERROR_NEW("signature for request failed");
diff --git a/src/common/DataBlock.cpp b/src/common/DataBlock.cpp
deleted file mode 100644
index 6592b85..0000000
--- a/src/common/DataBlock.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "DataBlock.h"
-
-#include <algorithm>
-#include <cstring>
-#include <stdexcept>
-
-namespace rocketmq {
-
-//######################################
-// MemoryBlock
-//######################################
-
-void MemoryBlock::copyTo(void* dst, ssize_t offset, size_t num) const {
-  char* d = static_cast<char*>(dst);
-
-  if (offset < 0) {
-    memset(d, 0, -offset);
-    d += (-offset);
-    num -= (-offset);
-    offset = 0;
-  }
-
-  if (offset + num > size_) {
-    size_t newNum = size_ - offset;
-    memset(d + newNum, 0, num - newNum);
-    num = newNum;
-  }
-
-  if (num > 0) {
-    memcpy(d, data_ + offset, num);
-  }
-}
-
-//######################################
-// MemoryPool
-//######################################
-
-MemoryPool::MemoryPool() : MemoryBlock() {}
-
-MemoryPool::MemoryPool(size_t initialSize, bool initialiseToZero) : MemoryBlock(nullptr, initialSize) {
-  if (size_ > 0) {
-    data_ = static_cast<char*>(initialiseToZero ? std::calloc(initialSize, sizeof(char))
-                                                : std::malloc(initialSize * sizeof(char)));
-  }
-}
-
-MemoryPool::MemoryPool(const void* const dataToInitialiseFrom, size_t sizeInBytes) : MemoryBlock(nullptr, sizeInBytes) {
-  if (size_ > 0) {
-    data_ = static_cast<char*>(std::malloc(size_ * sizeof(char)));
-
-    if (dataToInitialiseFrom != nullptr) {
-      memcpy(data_, dataToInitialiseFrom, size_);
-    }
-  }
-}
-
-MemoryPool::MemoryPool(const MemoryPool& other) : MemoryBlock(nullptr, other.size_) {
-  if (size_ > 0) {
-    data_ = static_cast<char*>(std::malloc(size_ * sizeof(char)));
-    memcpy(data_, other.data_, size_);
-  }
-}
-
-MemoryPool::MemoryPool(MemoryPool&& other) : MemoryBlock(other.data_, other.size_) {
-  other.size_ = 0;
-  other.data_ = nullptr;
-}
-
-MemoryPool::~MemoryPool() {
-  std::free(data_);
-}
-
-MemoryPool& MemoryPool::operator=(const MemoryPool& other) {
-  if (this != &other) {
-    setSize(other.size_, false);
-    memcpy(data_, other.data_, size_);
-  }
-  return *this;
-}
-
-MemoryPool& MemoryPool::operator=(MemoryPool&& other) {
-  if (this != &other) {
-    std::free(data_);
-
-    size_ = other.size_;
-    data_ = other.data_;
-
-    other.size_ = 0;
-    other.data_ = nullptr;
-  }
-  return *this;
-}
-
-//==============================================================================
-bool MemoryPool::matches(const void* dataToCompare, size_t dataSize) const {
-  return size_ == dataSize && memcmp(data_, dataToCompare, size_) == 0;
-}
-
-bool MemoryPool::operator==(const MemoryPool& other) const {
-  return matches(other.data_, other.size_);
-}
-
-bool MemoryPool::operator!=(const MemoryPool& other) const {
-  return !operator==(other);
-}
-
-//==============================================================================
-void MemoryPool::reset() {
-  reset(nullptr, 0);
-}
-
-void MemoryPool::reset(char* data, size_t size) {
-  if (size != 0) {
-    throw std::runtime_error("MemoryPool can't set external pointer as data.");
-  }
-
-  std::free(data_);
-  data_ = nullptr;
-  size_ = 0;
-}
-
-// this will resize the block to this size_
-void MemoryPool::setSize(size_t newSize, bool initialiseToZero) {
-  if (size_ != newSize) {
-    if (newSize <= 0) {
-      reset();
-    } else {
-      if (data_ != nullptr) {
-        data_ = static_cast<char*>(std::realloc(data_, newSize * sizeof(char)));
-
-        if (initialiseToZero && (newSize > size_)) {
-          memset(data_ + size_, 0, newSize - size_);
-        }
-      } else {
-        data_ = static_cast<char*>(initialiseToZero ? std::calloc(newSize, sizeof(char))
-                                                    : std::malloc(newSize * sizeof(char)));
-      }
-
-      size_ = newSize;
-    }
-  }
-}
-
-void MemoryPool::ensureSize(size_t minimumSize, bool initialiseToZero) {
-  if (size_ < minimumSize) {
-    setSize(minimumSize, initialiseToZero);
-  }
-}
-
-//==============================================================================
-void MemoryPool::fillWith(int value) {
-  memset(data_, value, size_);
-}
-
-void MemoryPool::append(const void* const srcData, size_t numBytes) {
-  if (numBytes > 0) {
-    size_t oldSize = size_;
-    setSize(size_ + numBytes);
-    memcpy(data_ + oldSize, srcData, numBytes);
-  }
-}
-
-void MemoryPool::replaceWith(const void* const srcData, size_t numBytes) {
-  if (numBytes > 0) {
-    setSize(numBytes);
-    memcpy(data_, srcData, numBytes);
-  }
-}
-
-void MemoryPool::insert(const void* const srcData, size_t numBytes, size_t insertPosition) {
-  if (numBytes > 0) {
-    insertPosition = std::min(insertPosition, size_);
-    size_t trailingDataSize = size_ - insertPosition;
-    setSize(size_ + numBytes, false);
-
-    if (trailingDataSize > 0) {
-      memmove(data_ + insertPosition + numBytes, data_ + insertPosition, trailingDataSize);
-    }
-
-    memcpy(data_ + insertPosition, srcData, numBytes);
-  }
-}
-
-void MemoryPool::removeSection(size_t startByte, size_t numBytesToRemove) {
-  if (startByte + numBytesToRemove >= size_) {
-    setSize(startByte);
-  } else if (numBytesToRemove > 0) {
-    memmove(data_ + startByte, data_ + startByte + numBytesToRemove, size_ - (startByte + numBytesToRemove));
-    setSize(size_ - numBytesToRemove);
-  }
-}
-
-void MemoryPool::copyFrom(const void* src, ssize_t offset, size_t num) {
-  const char* d = static_cast<const char*>(src);
-
-  if (offset < 0) {
-    d += (-offset);
-    num -= (-offset);
-    offset = 0;
-  }
-
-  if (offset + num > size_) {
-    num = size_ - offset;
-  }
-
-  if (num > 0) {
-    memcpy(data_ + offset, d, num);
-  }
-}
-
-//######################################
-// MemoryView
-//######################################
-
-void MemoryView::reset() {
-  reset(nullptr, 0);
-}
-
-void MemoryView::reset(char* data, size_t size) {
-  throw std::runtime_error("MemoryView can't reset().");
-}
-
-}  // namespace rocketmq
diff --git a/src/common/FilterAPI.h b/src/common/FilterAPI.h
index 86e89a8..3ca8b31 100644
--- a/src/common/FilterAPI.h
+++ b/src/common/FilterAPI.h
@@ -43,7 +43,7 @@ class FilterAPI {
             UtilAll::Trim(tag);
             if (!tag.empty()) {
               subscriptionData->putTagsSet(tag);
-              subscriptionData->putCodeSet(UtilAll::HashCode(tag));
+              subscriptionData->putCodeSet(UtilAll::hash_code(tag));
             }
           }
         }
diff --git a/src/common/InputStream.cpp b/src/common/InputStream.cpp
deleted file mode 100644
index 5a53819..0000000
--- a/src/common/InputStream.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "InputStream.h"
-
-#include <algorithm>
-
-#include "MemoryOutputStream.h"
-#include "big_endian.h"
-
-namespace rocketmq {
-
-int64_t InputStream::getNumBytesRemaining() {
-  int64_t len = getTotalLength();
-
-  if (len >= 0)
-    len -= getPosition();
-
-  return len;
-}
-
-char InputStream::readByte() {
-  char temp = 0;
-  read(&temp, 1);
-  return temp;
-}
-
-bool InputStream::readBool() {
-  return readByte() != 0;
-}
-
-short InputStream::readShortBigEndian() {
-  char temp[2];
-
-  if (read(temp, 2) == 2) {
-    short int v;
-    ReadBigEndian(temp, &v);
-    return v;
-  }
-
-  return 0;
-}
-
-int InputStream::readIntBigEndian() {
-  char temp[4];
-
-  if (read(temp, 4) == 4) {
-    int v;
-    ReadBigEndian(temp, &v);
-    return v;
-  }
-  return 0;
-}
-
-int64_t InputStream::readInt64BigEndian() {
-  char asBytes[8];
-  uint64_t asInt64;
-
-  if (read(asBytes, 8) == 8) {
-    ReadBigEndian(asBytes, &asInt64);
-    return asInt64;
-  }
-  return 0;
-}
-
-float InputStream::readFloatBigEndian() {
-  union {
-    int32_t asInt;
-    float asFloat;
-  } n;
-  n.asInt = (int32_t)readIntBigEndian();
-  return n.asFloat;
-}
-
-double InputStream::readDoubleBigEndian() {
-  union {
-    int64_t asInt;
-    double asDouble;
-  } n;
-  n.asInt = readInt64BigEndian();
-  return n.asDouble;
-}
-
-size_t InputStream::readIntoMemoryBlock(MemoryPool& block, size_t numBytes) {
-  MemoryOutputStream mo(block, true);
-  return (size_t)mo.writeFromInputStream(*this, numBytes);
-}
-
-//==============================================================================
-void InputStream::skipNextBytes(int64_t numBytesToSkip) {
-  if (numBytesToSkip > 0) {
-    const int skipBufferSize = (int)std::min(numBytesToSkip, (int64_t)16384);
-    char* temp = static_cast<char*>(std::malloc(skipBufferSize * sizeof(char)));
-
-    while (numBytesToSkip > 0 && !isExhausted())
-      numBytesToSkip -= read(temp, (int)std::min(numBytesToSkip, (int64_t)skipBufferSize));
-
-    std::free(temp);
-  }
-}
-}  // namespace rocketmq
diff --git a/src/common/InputStream.h b/src/common/InputStream.h
deleted file mode 100644
index 1a29bc8..0000000
--- a/src/common/InputStream.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef __INPUT_STREAM_H__
-#define __INPUT_STREAM_H__
-
-#include "DataBlock.h"
-
-//==============================================================================
-/** The base class for streams that read data.
-
-    Input and output streams are used throughout the library - subclasses can
-   override
-    some or all of the virtual functions to implement their behaviour.
-
-    @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
-*/
-namespace rocketmq {
-
-class ROCKETMQCLIENT_API InputStream {
- public:
-  /** Destructor. */
-  virtual ~InputStream() {}
-
-  //==============================================================================
-  /** Returns the total number of bytes available for reading in this stream.
-
-      Note that this is the number of bytes available from the start of the
-      stream, not from the current position.
-
-      If the size of the stream isn't actually known, this will return -1.
-
-      @see getNumBytesRemaining
-  */
-  virtual int64_t getTotalLength() = 0;
-
-  /** Returns the number of bytes available for reading, or a negative value if
-      the remaining length is not known.
-      @see getTotalLength
-  */
-  int64_t getNumBytesRemaining();
-
-  /** Returns true if the stream has no more data to read. */
-  virtual bool isExhausted() = 0;
-
-  //==============================================================================
-  /** Reads some data from the stream into a memory buffer.
-
-      This is the only read method that subclasses actually need to implement,
-     as the
-      InputStream base class implements the other read methods in terms of this
-     one (although
-      it's often more efficient for subclasses to implement them directly).
-
-      @param destBuffer       the destination buffer for the data. This must not
-     be null.
-      @param maxBytesToRead   the maximum number of bytes to read - make sure
-     the
-                              memory block passed in is big enough to contain
-     this
-                              many bytes. This value must not be negative.
-
-      @returns    the actual number of bytes that were read, which may be less
-     than
-                  maxBytesToRead if the stream is exhausted before it gets that
-     far
-  */
-  virtual int read(void* destBuffer, int maxBytesToRead) = 0;
-
-  /** Reads a byte from the stream.
-      If the stream is exhausted, this will return zero.
-      @see OutputStream::writeByte
-  */
-  virtual char readByte();
-
-  /** Reads a boolean from the stream.
-      The bool is encoded as a single byte - non-zero for true, 0 for false.
-      If the stream is exhausted, this will return false.
-      @see OutputStream::writeBool
-  */
-  virtual bool readBool();
-
-  /** Reads two bytes from the stream as a little-endian 16-bit value.
-      If the next two bytes read are byte1 and byte2, this returns (byte2 |
-     (byte1 << 8)).
-      If the stream is exhausted partway through reading the bytes, this will
-     return zero.
-      @see OutputStream::writeShortBigEndian, readShort
-  */
-  virtual short readShortBigEndian();
-
-  /** Reads four bytes from the stream as a big-endian 32-bit value.
-
-      If the next four bytes are byte1 to byte4, this returns
-      (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
-
-      If the stream is exhausted partway through reading the bytes, this will
-     return zero.
-
-      @see OutputStream::writeIntBigEndian, readInt
-  */
-  virtual int readIntBigEndian();
-
-  /** Reads eight bytes from the stream as a big-endian 64-bit value.
-
-      If the next eight bytes are byte1 to byte8, this returns
-      (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) |
-     (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
-
-      If the stream is exhausted partway through reading the bytes, this will
-     return zero.
-
-      @see OutputStream::writeInt64BigEndian, readInt64
-  */
-  virtual int64_t readInt64BigEndian();
-
-  /** Reads four bytes as a 32-bit floating point value.
-      The raw 32-bit encoding of the float is read from the stream as a
-     big-endian int.
-      If the stream is exhausted partway through reading the bytes, this will
-     return zero.
-      @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
-  */
-  virtual float readFloatBigEndian();
-
-  /** Reads eight bytes as a 64-bit floating point value.
-      The raw 64-bit encoding of the double is read from the stream as a
-     big-endian int64_t.
-      If the stream is exhausted partway through reading the bytes, this will
-     return zero.
-      @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
-  */
-  virtual double readDoubleBigEndian();
-
-  //==============================================================================whole
-  // stream and turn it into a string.
-  /** Reads from the stream and appends the data to a MemoryBlock.
-
-      @param destBlock            the block to append the data onto
-      @param maxNumBytesToRead    if this is a positive value, it sets a limit
-     to the number
-                                  of bytes that will be read - if it's negative,
-     data
-                                  will be read until the stream is exhausted.
-      @returns the number of bytes that were added to the memory block
-  */
-  virtual size_t readIntoMemoryBlock(MemoryPool& destBlock, size_t maxNumBytesToRead = -1);
-
-  //==============================================================================
-  /** Returns the offset of the next byte that will be read from the stream.
-      @see setPosition
-  */
-  virtual int64_t getPosition() = 0;
-
-  /** Tries to move the current read position of the stream.
-
-      The position is an absolute number of bytes from the stream's start.
-
-      Some streams might not be able to do this, in which case they should do
-      nothing and return false. Others might be able to manage it by resetting
-      themselves and skipping to the correct position, although this is
-      obviously a bit slow.
-
-      @returns  true if the stream manages to reposition itself correctly
-      @see getPosition
-  */
-  virtual bool setPosition(int64_t newPosition) = 0;
-
-  /** Reads and discards a number of bytes from the stream.
-
-      Some input streams might implement this efficiently, but the base
-      class will just keep reading data until the requisite number of bytes
-      have been done.
-  */
-  virtual void skipNextBytes(int64_t numBytesToSkip);
-
- protected:
-  //==============================================================================
-  InputStream() {}
-};
-
-}  // namespace rocketmq
-
-#endif  // __INPUT_STREAM_H__
diff --git a/src/common/MemoryInputStream.cpp b/src/common/MemoryInputStream.cpp
deleted file mode 100644
index 057b811..0000000
--- a/src/common/MemoryInputStream.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "MemoryInputStream.h"
-
-#include <algorithm>
-#include <cstring>
-
-namespace rocketmq {
-
-MemoryInputStream::MemoryInputStream(const void* const sourceData,
-                                     const size_t sourceDataSize,
-                                     const bool keepInternalCopy)
-    : data(sourceData), dataSize(sourceDataSize), position(0), internalCopy(NULL) {
-  if (keepInternalCopy) {
-    createInternalCopy();
-  }
-}
-
-MemoryInputStream::MemoryInputStream(const MemoryBlock& sourceData, const bool keepInternalCopy)
-    : data(sourceData.getData()), dataSize(sourceData.getSize()), position(0), internalCopy(nullptr) {
-  if (keepInternalCopy) {
-    createInternalCopy();
-  }
-}
-
-void MemoryInputStream::createInternalCopy() {
-  std::free(internalCopy);
-  internalCopy = static_cast<char*>(std::malloc(dataSize));
-  memcpy(internalCopy, data, dataSize);
-  data = internalCopy;
-}
-
-MemoryInputStream::~MemoryInputStream() {
-  std::free(internalCopy);
-}
-
-int64_t MemoryInputStream::getTotalLength() {
-  return (int64_t)dataSize;
-}
-
-int MemoryInputStream::read(void* const buffer, const int howMany) {
-  const int num = std::min(howMany, (int)(dataSize - position));
-  if (num <= 0)
-    return 0;
-
-  memcpy((char*)buffer, (char*)data + position, (size_t)num);
-  position += (unsigned int)num;
-  return num;
-}
-
-bool MemoryInputStream::isExhausted() {
-  return position >= dataSize;
-}
-
-bool MemoryInputStream::setPosition(const int64_t pos) {
-  if (pos < 0)
-    position = 0;
-  else
-    position = (int64_t)dataSize < pos ? (int64_t)dataSize : pos;
-
-  return true;
-}
-
-int64_t MemoryInputStream::getPosition() {
-  return (int64_t)position;
-}
-
-}  // namespace rocketmq
diff --git a/src/common/MemoryInputStream.h b/src/common/MemoryInputStream.h
deleted file mode 100644
index 2097ec6..0000000
--- a/src/common/MemoryInputStream.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef __MEMORY_INTPUT_STREAM_H__
-#define __MEMORY_INTPUT_STREAM_H__
-
-#include "InputStream.h"
-
-namespace rocketmq {
-
-//==============================================================================
-/**
-    Allows a block of data to be accessed as a stream.
-
-    This can either be used to refer to a shared block of memory, or can make
-   its
-    own internal copy of the data when the MemoryInputStream is created.
-*/
-class ROCKETMQCLIENT_API MemoryInputStream : public InputStream {
- public:
-  //==============================================================================
-  /** Creates a MemoryInputStream.
-
-      @param sourceData               the block of data to use as the stream's
-     source
-      @param sourceDataSize           the number of bytes in the source data
-     block
-      @param keepInternalCopyOfData   if false, the stream will just keep a
-     pointer to
-                                      the source data, so this data shouldn't be
-     changed
-                                      for the lifetime of the stream; if this
-     parameter is
-                                      true, the stream will make its own copy of
-     the
-                                      data and use that.
-  */
-  MemoryInputStream(const void* sourceData, size_t sourceDataSize, bool keepInternalCopyOfData);
-
-  /** Creates a MemoryInputStream.
-
-      @param data                     a block of data to use as the stream's
-     source
-      @param keepInternalCopyOfData   if false, the stream will just keep a
-     reference to
-                                      the source data, so this data shouldn't be
-     changed
-                                      for the lifetime of the stream; if this
-     parameter is
-                                      true, the stream will make its own copy of
-     the
-                                      data and use that.
-  */
-  MemoryInputStream(const MemoryBlock& data, bool keepInternalCopyOfData);
-
-  /** Destructor. */
-  ~MemoryInputStream();
-
-  /** Returns a pointer to the source data block from which this stream is
-   * reading. */
-  const void* getData() const { return data; }
-
-  /** Returns the number of bytes of source data in the block from which this
-   * stream is reading. */
-  size_t getDataSize() const { return dataSize; }
-
-  //==============================================================================
-  int64_t getPosition();
-  bool setPosition(int64_t pos);
-  int64_t getTotalLength();
-  bool isExhausted();
-  int read(void* destBuffer, int maxBytesToRead);
-
- private:
-  //==============================================================================
-  const void* data;
-  size_t dataSize, position;
-  char* internalCopy;
-
-  void createInternalCopy();
-};
-
-}  // namespace rocketmq
-
-#endif  // __MEMORY_INTPUT_STREAM_H__
diff --git a/src/common/MemoryOutputStream.cpp b/src/common/MemoryOutputStream.cpp
deleted file mode 100644
index 1c4f4da..0000000
--- a/src/common/MemoryOutputStream.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "MemoryOutputStream.h"
-
-#include <algorithm>
-#include <cstring>
-
-namespace rocketmq {
-
-MemoryOutputStream::MemoryOutputStream(const size_t initialSize)
-    : poolToUse(&internalPool), externalData(nullptr), position(0), size(0), availableSize(0) {
-  internalPool.setSize(initialSize, false);
-}
-
-MemoryOutputStream::MemoryOutputStream(MemoryPool& memoryBlockToWriteTo, const bool appendToExistingBlockContent)
-    : poolToUse(&memoryBlockToWriteTo), externalData(NULL), position(0), size(0), availableSize(0) {
-  if (appendToExistingBlockContent) {
-    position = size = memoryBlockToWriteTo.getSize();
-  }
-}
-
-MemoryOutputStream::MemoryOutputStream(void* destBuffer, size_t destBufferSize)
-    : poolToUse(NULL), externalData(destBuffer), position(0), size(0), availableSize(destBufferSize) {}
-
-MemoryOutputStream::~MemoryOutputStream() {
-  trimExternalBlockSize();
-}
-
-void MemoryOutputStream::flush() {
-  trimExternalBlockSize();
-}
-
-void MemoryOutputStream::trimExternalBlockSize() {
-  if (poolToUse != &internalPool && poolToUse != NULL) {
-    poolToUse->setSize(size, false);
-  }
-}
-
-void MemoryOutputStream::preallocate(const size_t bytesToPreallocate) {
-  if (poolToUse != NULL) {
-    poolToUse->ensureSize(bytesToPreallocate + 1);
-  }
-}
-
-void MemoryOutputStream::reset() {
-  position = 0;
-  size = 0;
-}
-
-char* MemoryOutputStream::prepareToWrite(size_t numBytes) {
-  size_t storageNeeded = position + numBytes;
-
-  char* data;
-
-  if (poolToUse != NULL) {
-    if (storageNeeded >= (unsigned int)(poolToUse->getSize())) {
-      poolToUse->ensureSize((storageNeeded + std::min(storageNeeded / 2, (size_t)(1024 * 1024)) + 32) & ~31u);
-    }
-
-    data = static_cast<char*>(poolToUse->getData());
-  } else {
-    if (storageNeeded > availableSize) {
-      return NULL;
-    }
-
-    data = static_cast<char*>(externalData);
-  }
-
-  char* const writePointer = data + position;
-  position += numBytes;
-  size = std::max(size, position);
-  return writePointer;
-}
-
-bool MemoryOutputStream::write(const void* const buffer, size_t howMany) {
-  if (howMany == 0) {
-    return true;
-  }
-
-  if (char* dest = prepareToWrite(howMany)) {
-    memcpy(dest, buffer, howMany);
-    return true;
-  }
-
-  return false;
-}
-
-bool MemoryOutputStream::writeRepeatedByte(uint8_t byte, size_t howMany) {
-  if (howMany == 0) {
-    return true;
-  }
-
-  if (char* dest = prepareToWrite(howMany)) {
-    memset(dest, byte, howMany);
-    return true;
-  }
-
-  return false;
-}
-
-MemoryPool MemoryOutputStream::getMemoryBlock() const {
-  return MemoryPool(getData(), getDataSize());
-}
-
-const void* MemoryOutputStream::getData() const {
-  if (poolToUse == NULL) {
-    return externalData;
-  }
-
-  if (poolToUse->getSize() > size) {
-    poolToUse->getData()[size] = 0;
-  }
-
-  return poolToUse->getData();
-}
-
-bool MemoryOutputStream::setPosition(int64_t newPosition) {
-  if (newPosition <= (int64_t)size) {
-    // ok to seek backwards
-    if (newPosition < 0) {
-      position = 0;
-    } else {
-      position = (int64_t)size < newPosition ? size : newPosition;
-    }
-    return true;
-  }
-
-  // can't move beyond the end of the stream..
-  return false;
-}
-
-int64_t MemoryOutputStream::writeFromInputStream(InputStream& source, int64_t maxNumBytesToWrite) {
-  // before writing from an input, see if we can preallocate to make it more efficient..
-  int64_t availableData = source.getTotalLength() - source.getPosition();
-
-  if (availableData > 0) {
-    if (maxNumBytesToWrite > availableData || maxNumBytesToWrite < 0) {
-      maxNumBytesToWrite = availableData;
-    }
-
-    if (poolToUse != NULL) {
-      preallocate(poolToUse->getSize() + (size_t)maxNumBytesToWrite);
-    }
-  }
-
-  return OutputStream::writeFromInputStream(source, maxNumBytesToWrite);
-}
-
-OutputStream& operator<<(OutputStream& stream, const MemoryOutputStream& streamToRead) {
-  const size_t dataSize = streamToRead.getDataSize();
-
-  if (dataSize > 0) {
-    stream.write(streamToRead.getData(), dataSize);
-  }
-
-  return stream;
-}
-
-}  // namespace rocketmq
diff --git a/src/common/MemoryOutputStream.h b/src/common/MemoryOutputStream.h
deleted file mode 100644
index ece1a19..0000000
--- a/src/common/MemoryOutputStream.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef __MEMORY_OUTPUT_STREAM_H__
-#define __MEMORY_OUTPUT_STREAM_H__
-
-#include "OutputStream.h"
-
-namespace rocketmq {
-
-//==============================================================================
-/**
-    Writes data to an internal memory buffer, which grows as required.
-
-    The data that was written into the stream can then be accessed later as
-    a contiguous block of memory.
-*/
-class ROCKETMQCLIENT_API MemoryOutputStream : public OutputStream {
- public:
-  //==============================================================================
-  /** Creates an empty memory stream, ready to be written into.
-      @param initialSize  the intial amount of capacity to allocate for writing
-     into
-  */
-  MemoryOutputStream(size_t initialSize = 256);
-
-  /** Creates a memory stream for writing into into a pre-existing MemoryBlock
-     object.
-
-      Note that the destination block will always be larger than the amount of
-     data
-      that has been written to the stream, because the MemoryOutputStream keeps
-     some
-      spare capactity at its end. To trim the block's size down to fit the
-     actual
-      data, call flush(), or delete the MemoryOutputStream.
-
-      @param memoryBlockToWriteTo             the block into which new data will
-     be written.
-      @param appendToExistingBlockContent     if this is true, the contents of
-     the block will be
-                                              kept, and new data will be
-     appended to it. If false,
-                                              the block will be cleared before
-     use
-  */
-  MemoryOutputStream(MemoryPool& memoryBlockToWriteTo, bool appendToExistingBlockContent);
-
-  /** Creates a MemoryOutputStream that will write into a user-supplied,
-     fixed-size
-      block of memory.
-      When using this mode, the stream will write directly into this memory area
-     until
-      it's full, at which point write operations will fail.
-  */
-  MemoryOutputStream(void* destBuffer, size_t destBufferSize);
-
-  /** Destructor.
-      This will free any data that was written to it.
-  */
-  ~MemoryOutputStream();
-
-  //==============================================================================
-  /** Returns a pointer to the data that has been written to the stream.
-      @see getDataSize
-  */
-  const void* getData() const;
-
-  /** Returns the number of bytes of data that have been written to the stream.
-      @see getData
-  */
-  size_t getDataSize() const { return size; }
-
-  /** Resets the stream, clearing any data that has been written to it so far.
-   */
-  void reset();
-
-  /** Increases the internal storage capacity to be able to contain at least the
-     specified
-      amount of data without needing to be resized.
-  */
-  void preallocate(size_t bytesToPreallocate);
-
-  /** Returns a copy of the stream's data as a memory block. */
-  MemoryPool getMemoryBlock() const;
-
-  //==============================================================================
-  /** If the stream is writing to a user-supplied MemoryBlock, this will trim
-     any excess
-      capacity off the block, so that its length matches the amount of actual
-     data that
-      has been written so far.
-  */
-  void flush();
-
-  bool write(const void*, size_t);
-  int64_t getPosition() { return (int64_t)position; }
-  bool setPosition(int64_t);
-  int64_t writeFromInputStream(InputStream&, int64_t maxNumBytesToWrite);
-  bool writeRepeatedByte(uint8_t byte, size_t numTimesToRepeat);
-
- private:
-  //==============================================================================
-  MemoryPool* const poolToUse;
-  MemoryPool internalPool;
-  void* externalData;
-  size_t position, size, availableSize;
-
-  void trimExternalBlockSize();
-  char* prepareToWrite(size_t);
-};
-
-/** Copies all the data that has been written to a MemoryOutputStream into
- * another stream. */
-OutputStream& operator<<(OutputStream& stream, const MemoryOutputStream& streamToRead);
-
-}  // namespace rocketmq
-
-#endif  // __MEMORY_OUTPUT_STREAM_H__
diff --git a/src/common/MessageSysFlag.cpp b/src/common/MessageSysFlag.cpp
index a61d36c..cded96c 100644
--- a/src/common/MessageSysFlag.cpp
+++ b/src/common/MessageSysFlag.cpp
@@ -18,27 +18,27 @@
 
 namespace rocketmq {
 
-const int MessageSysFlag::CompressedFlag = 0x1 << 0;
-const int MessageSysFlag::MultiTagsFlag = 0x1 << 1;
+const int MessageSysFlag::COMPRESSED_FLAG = 0x1 << 0;
+const int MessageSysFlag::MULTI_TAGS_FLAG = 0x1 << 1;
 
-const int MessageSysFlag::TransactionNotType = 0x0;
-const int MessageSysFlag::TransactionPreparedType = 0x1 << 2;
-const int MessageSysFlag::TransactionCommitType = 0x2 << 2;
-const int MessageSysFlag::TransactionRollbackType = 0x3 << 2;
+const int MessageSysFlag::TRANSACTION_NOT_TYPE = 0x0;
+const int MessageSysFlag::TRANSACTION_PREPARED_TYPE = 0x1 << 2;
+const int MessageSysFlag::TRANSACTION_COMMIT_TYPE = 0x2 << 2;
+const int MessageSysFlag::TRANSACTION_ROLLBACK_TYPE = 0x3 << 2;
 
-const int MessageSysFlag::BronhostV6Flag = 0x1 << 4;
-const int MessageSysFlag::StorehostV6Flag = 0x1 << 5;
+const int MessageSysFlag::BORNHOST_V6_FLAG = 0x1 << 4;
+const int MessageSysFlag::STOREHOST_V6_FLAG = 0x1 << 5;
 
 int MessageSysFlag::getTransactionValue(int flag) {
-  return flag & TransactionRollbackType;
+  return flag & TRANSACTION_ROLLBACK_TYPE;
 }
 
 int MessageSysFlag::resetTransactionValue(int flag, int type) {
-  return (flag & (~TransactionRollbackType)) | type;
+  return (flag & (~TRANSACTION_ROLLBACK_TYPE)) | type;
 }
 
 int MessageSysFlag::clearCompressedFlag(int flag) {
-  return flag & (~CompressedFlag);
+  return flag & (~COMPRESSED_FLAG);
 }
 
 }  // namespace rocketmq
diff --git a/src/common/MessageSysFlag.h b/src/common/MessageSysFlag.h
index 8c61579..6948e37 100644
--- a/src/common/MessageSysFlag.h
+++ b/src/common/MessageSysFlag.h
@@ -21,22 +21,22 @@ namespace rocketmq {
 
 class MessageSysFlag {
  public:
-  static int getTransactionValue(int flag);
-  static int resetTransactionValue(int flag, int type);
+  static const int COMPRESSED_FLAG;
+  static const int MULTI_TAGS_FLAG;
 
-  static int clearCompressedFlag(int flag);
+  static const int TRANSACTION_NOT_TYPE;
+  static const int TRANSACTION_PREPARED_TYPE;
+  static const int TRANSACTION_COMMIT_TYPE;
+  static const int TRANSACTION_ROLLBACK_TYPE;
 
- public:
-  static const int CompressedFlag;
-  static const int MultiTagsFlag;
+  static const int BORNHOST_V6_FLAG;
+  static const int STOREHOST_V6_FLAG;
 
-  static const int TransactionNotType;
-  static const int TransactionPreparedType;
-  static const int TransactionCommitType;
-  static const int TransactionRollbackType;
+ public:
+  static int getTransactionValue(int flag);
+  static int resetTransactionValue(int flag, int type);
 
-  static const int BronhostV6Flag;
-  static const int StorehostV6Flag;
+  static int clearCompressedFlag(int flag);
 };
 
 }  // namespace rocketmq
diff --git a/src/common/OutputStream.cpp b/src/common/OutputStream.cpp
deleted file mode 100644
index 4a95013..0000000
--- a/src/common/OutputStream.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "OutputStream.h"
-
-#include <algorithm>
-#include <limits>
-
-#include "big_endian.h"
-
-namespace rocketmq {
-//==============================================================================
-OutputStream::OutputStream() {}
-
-OutputStream::~OutputStream() {}
-
-//==============================================================================
-bool OutputStream::writeBool(const bool b) {
-  return writeByte(b ? (char)1 : (char)0);
-}
-
-bool OutputStream::writeByte(char byte) {
-  return write(&byte, 1);
-}
-
-bool OutputStream::writeRepeatedByte(uint8_t byte, size_t numTimesToRepeat) {
-  for (size_t i = 0; i < numTimesToRepeat; ++i)
-    if (!writeByte((char)byte))
-      return false;
-
-  return true;
-}
-
-bool OutputStream::writeShortBigEndian(short value) {
-  unsigned short v;
-  char pShort[sizeof(v)];
-  WriteBigEndian(pShort, (unsigned short)value);
-  return write(pShort, 2);
-}
-
-bool OutputStream::writeIntBigEndian(int value) {
-  unsigned int v;
-  char pInt[sizeof(v)];
-  WriteBigEndian(pInt, (unsigned int)value);
-  return write(pInt, 4);
-}
-
-bool OutputStream::writeInt64BigEndian(int64_t value) {
-  uint64_t v;
-  char pUint64[sizeof(v)];
-  WriteBigEndian(pUint64, (uint64_t)value);
-  return write(pUint64, 8);
-}
-
-bool OutputStream::writeFloatBigEndian(float value) {
-  union {
-    int asInt;
-    float asFloat;
-  } n;
-  n.asFloat = value;
-  return writeIntBigEndian(n.asInt);
-}
-
-bool OutputStream::writeDoubleBigEndian(double value) {
-  union {
-    int64_t asInt;
-    double asDouble;
-  } n;
-  n.asDouble = value;
-  return writeInt64BigEndian(n.asInt);
-}
-
-int64_t OutputStream::writeFromInputStream(InputStream& source, int64_t numBytesToWrite) {
-  if (numBytesToWrite < 0)
-    numBytesToWrite = std::numeric_limits<int64_t>::max();
-
-  int64_t numWritten = 0;
-
-  while (numBytesToWrite > 0) {
-    char buffer[8192];
-    const int num = source.read(buffer, (int)std::min(numBytesToWrite, (int64_t)sizeof(buffer)));
-
-    if (num <= 0)
-      break;
-
-    write(buffer, (size_t)num);
-
-    numBytesToWrite -= num;
-    numWritten += num;
-  }
-
-  return numWritten;
-}
-}  // namespace rocketmq
diff --git a/src/common/OutputStream.h b/src/common/OutputStream.h
deleted file mode 100644
index 46378a2..0000000
--- a/src/common/OutputStream.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef __OUTPUT_STREAM_H__
-#define __OUTPUT_STREAM_H__
-
-#include "InputStream.h"
-
-namespace rocketmq {
-
-//==============================================================================
-/**
-    The base class for streams that write data to some kind of destination.
-
-    Input and output streams are used throughout the library - subclasses can
-   override
-    some or all of the virtual functions to implement their behaviour.
-
-    @see InputStream, MemoryOutputStream, FileOutputStream
-*/
-class ROCKETMQCLIENT_API OutputStream {
- protected:
-  //==============================================================================
-  OutputStream();
-
- public:
-  /** Destructor.
-
-      Some subclasses might want to do things like call flush() during their
-      destructors.
-  */
-  virtual ~OutputStream();
-
-  //==============================================================================
-  /** If the stream is using a buffer, this will ensure it gets written
-      out to the destination. */
-  virtual void flush() = 0;
-
-  /** Tries to move the stream's output position.
-
-      Not all streams will be able to seek to a new position - this will return
-      false if it fails to work.
-
-      @see getPosition
-  */
-  virtual bool setPosition(int64_t newPosition) = 0;
-
-  /** Returns the stream's current position.
-
-      @see setPosition
-  */
-  virtual int64_t getPosition() = 0;
-
-  //==============================================================================
-  /** Writes a block of data to the stream.
-
-      When creating a subclass of OutputStream, this is the only write method
-      that needs to be overloaded - the base class has methods for writing other
-      types of data which use this to do the work.
-
-      @param dataToWrite      the target buffer to receive the data. This must
-     not be null.
-      @param numberOfBytes    the number of bytes to write.
-      @returns false if the write operation fails for some reason
-  */
-  virtual bool write(const void* dataToWrite, size_t numberOfBytes) = 0;
-
-  //==============================================================================
-  /** Writes a single byte to the stream.
-      @returns false if the write operation fails for some reason
-      @see InputStream::readByte
-  */
-  virtual bool writeByte(char byte);
-
-  /** Writes a boolean to the stream as a single byte.
-      This is encoded as a binary byte (not as text) with a value of 1 or 0.
-      @returns false if the write operation fails for some reason
-      @see InputStream::readBool
-  */
-  virtual bool writeBool(bool boolValue);
-
-  /** Writes a 16-bit integer to the stream in a big-endian byte order.
-      This will write two bytes to the stream: (value >> 8), then (value &
-     0xff).
-      @returns false if the write operation fails for some reason
-      @see InputStream::readShortBigEndian
-  */
-  virtual bool writeShortBigEndian(short value);
-
-  /** Writes a 32-bit integer to the stream in a big-endian byte order.
-      @returns false if the write operation fails for some reason
-      @see InputStream::readIntBigEndian
-  */
-  virtual bool writeIntBigEndian(int value);
-
-  /** Writes a 64-bit integer to the stream in a big-endian byte order.
-      @returns false if the write operation fails for some reason
-      @see InputStream::readInt64BigEndian
-  */
-  virtual bool writeInt64BigEndian(int64_t value);
-
-  /** Writes a 32-bit floating point value to the stream in a binary format.
-      The binary 32-bit encoding of the float is written as a big-endian int.
-      @returns false if the write operation fails for some reason
-      @see InputStream::readFloatBigEndian
-  */
-  virtual bool writeFloatBigEndian(float value);
-
-  /** Writes a 64-bit floating point value to the stream in a binary format.
-      The eight raw bytes of the double value are written out as a big-endian
-     64-bit int.
-      @see InputStream::readDoubleBigEndian
-      @returns false if the write operation fails for some reason
-  */
-  virtual bool writeDoubleBigEndian(double value);
-
-  /** Writes a byte to the output stream a given number of times.
-      @returns false if the write operation fails for some reason
-  */
-  virtual bool writeRepeatedByte(uint8_t byte, size_t numTimesToRepeat);
-
-  /** Reads data from an input stream and writes it to this stream.
-
-      @param source               the stream to read from
-      @param maxNumBytesToWrite   the number of bytes to read from the stream
-     (if this is
-                                  less than zero, it will keep reading until the
-     input
-                                  is exhausted)
-      @returns the number of bytes written
-  */
-  virtual int64_t writeFromInputStream(InputStream& source, int64_t maxNumBytesToWrite);
-};
-
-}  // namespace rocketmq
-
-#endif  // __OUTPUT_STREAM_H__
diff --git a/src/common/SendCallbackWrap.cpp b/src/common/SendCallbackWrap.cpp
index 698fe56..e8951b3 100755
--- a/src/common/SendCallbackWrap.cpp
+++ b/src/common/SendCallbackWrap.cpp
@@ -167,7 +167,7 @@ void SendCallbackWrap::onExceptionImpl(ResponseFuture* responseFuture,
                  addr, retryBrokerName);
     try {
       // new request
-      m_request.setOpaque(RemotingCommand::createNewRequestId());
+      m_request.set_opaque(RemotingCommand::createNewRequestId());
 
       // resend
       m_addr = std::move(addr);
diff --git a/src/common/UtilAll.cpp b/src/common/UtilAll.cpp
index 7f2dbb2..162a45e 100644
--- a/src/common/UtilAll.cpp
+++ b/src/common/UtilAll.cpp
@@ -39,8 +39,8 @@
 
 namespace rocketmq {
 
-std::string UtilAll::s_localHostName;
-std::string UtilAll::s_localIpAddress;
+std::string UtilAll::sLocalHostName;
+std::string UtilAll::sLocalIpAddress;
 
 bool UtilAll::try_lock_for(std::timed_mutex& mutex, long timeout) {
   auto now = std::chrono::steady_clock::now();
@@ -57,12 +57,12 @@ bool UtilAll::try_lock_for(std::timed_mutex& mutex, long timeout) {
   }
 }
 
-int32_t UtilAll::HashCode(const std::string& str) {
-  // FIXME: don't equal to String#hashCode in Java
+int32_t UtilAll::hash_code(const std::string& str) {
+  // FIXME: don't equal to String#hashCode in Java for non-ascii
   int32_t h = 0;
   if (!str.empty()) {
     for (const auto& c : str) {
-      h = 31 * h + c;
+      h = 31 * h + (uint8_t)c;
     }
   }
   return h;
@@ -220,29 +220,29 @@ int UtilAll::Split(std::vector<std::string>& ret_, const std::string& strIn, con
 }
 
 std::string UtilAll::getLocalHostName() {
-  if (s_localHostName.empty()) {
+  if (sLocalHostName.empty()) {
     char name[1024];
     if (::gethostname(name, sizeof(name)) != 0) {
       return null;
     }
-    s_localHostName.append(name, strlen(name));
+    sLocalHostName.append(name, strlen(name));
   }
-  return s_localHostName;
+  return sLocalHostName;
 }
 
 std::string UtilAll::getLocalAddress() {
-  if (s_localIpAddress.empty()) {
+  if (sLocalIpAddress.empty()) {
     auto hostname = getLocalHostName();
     if (!hostname.empty()) {
       try {
-        s_localIpAddress = socketAddress2String(lookupNameServers(hostname));
+        sLocalIpAddress = socketAddress2String(lookupNameServers(hostname));
       } catch (std::exception& e) {
         LOG_WARN(e.what());
-        s_localIpAddress = "127.0.0.1";
+        sLocalIpAddress = "127.0.0.1";
       }
     }
   }
-  return s_localIpAddress;
+  return sLocalIpAddress;
 }
 
 uint32_t UtilAll::getIP() {
@@ -372,10 +372,10 @@ int64_t UtilAll::currentTimeSeconds() {
 }
 
 bool UtilAll::deflate(const std::string& input, std::string& out, int level) {
-  return deflate(input.data(), input.length(), out, level);
+  return deflate(ByteArray((char*)input.data(), input.size()), out, level);
 }
 
-bool UtilAll::deflate(const char* input, size_t len, std::string& out, int level) {
+bool UtilAll::deflate(const ByteArray& in, std::string& out, int level) {
   int ret;
   unsigned have;
   z_stream strm;
@@ -390,8 +390,8 @@ bool UtilAll::deflate(const char* input, size_t len, std::string& out, int level
     return false;
   }
 
-  strm.avail_in = len;
-  strm.next_in = (z_const Bytef*)input;
+  strm.avail_in = in.size();
+  strm.next_in = (z_const Bytef*)in.array();
 
   /* run deflate() on input until output buffer not full, finish
      compression if all of source has been read in */
@@ -413,10 +413,10 @@ bool UtilAll::deflate(const char* input, size_t len, std::string& out, int level
 }
 
 bool UtilAll::inflate(const std::string& input, std::string& out) {
-  return inflate(input.data(), input.length(), out);
+  return inflate(ByteArray((char*)input.data(), input.size()), out);
 }
 
-bool UtilAll::inflate(const char* input, size_t len, std::string& out) {
+bool UtilAll::inflate(const ByteArray& in, std::string& out) {
   int ret;
   unsigned have;
   z_stream strm;
@@ -433,8 +433,8 @@ bool UtilAll::inflate(const char* input, size_t len, std::string& out) {
     return false;
   }
 
-  strm.avail_in = len;
-  strm.next_in = (z_const Bytef*)input;
+  strm.avail_in = in.size();
+  strm.next_in = (z_const Bytef*)in.array();
 
   /* run inflate() on input until output buffer not full */
   do {
diff --git a/src/common/UtilAll.h b/src/common/UtilAll.h
index a919db7..5193714 100644
--- a/src/common/UtilAll.h
+++ b/src/common/UtilAll.h
@@ -14,15 +14,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __UTIL_ALL_H__
-#define __UTIL_ALL_H__
+#ifndef ROCKETMQ_COMMON_UTILALL_H_
+#define ROCKETMQ_COMMON_UTILALL_H_
 
-#include <exception>
-#include <mutex>
-#include <string>
-#include <vector>
+#include <algorithm>  // std::move
+#include <exception>  // std::exception
+#include <mutex>      // std::timed_mutex
+#include <string>     // std::string
+#include <vector>     // std::vector
 
-#include "RocketMQClient.h"
+#include "ByteArray.h"
 
 namespace rocketmq {
 
@@ -91,7 +92,7 @@ class UtilAll {
   template <typename T>
   static std::string to_string(T value);
 
-  static int32_t HashCode(const std::string& str);
+  static int32_t hash_code(const std::string& str);
 
   static std::string bytes2string(const char* bytes, size_t len);
   static void string2bytes(char* dest, const std::string& src);
@@ -122,9 +123,9 @@ class UtilAll {
   static int64_t currentTimeSeconds();
 
   static bool deflate(const std::string& input, std::string& out, int level);
-  static bool deflate(const char* input, size_t len, std::string& out, int level);
+  static bool deflate(const ByteArray& in, std::string& out, int level);
   static bool inflate(const std::string& input, std::string& out);
-  static bool inflate(const char* input, size_t len, std::string& out);
+  static bool inflate(const ByteArray& in, std::string& out);
 
   // Renames file |from_path| to |to_path|. Both paths must be on the same
   // volume, or the function will fail. Destination file will be created
@@ -135,8 +136,8 @@ class UtilAll {
   static bool ReplaceFile(const std::string& from_path, const std::string& to_path);
 
  private:
-  static std::string s_localHostName;
-  static std::string s_localIpAddress;
+  static std::string sLocalHostName;
+  static std::string sLocalIpAddress;
 };
 
 template <typename T>
@@ -155,6 +156,11 @@ inline std::string UtilAll::to_string<char*>(char* value) {
 }
 
 template <>
+inline std::string UtilAll::to_string<ByteArrayRef>(ByteArrayRef value) {
+  return batos(std::move(value));
+}
+
+template <>
 inline std::string UtilAll::to_string<std::exception_ptr>(std::exception_ptr eptr) {
   try {
     if (eptr) {
@@ -168,4 +174,4 @@ inline std::string UtilAll::to_string<std::exception_ptr>(std::exception_ptr ept
 
 }  // namespace rocketmq
 
-#endif  // __UTIL_ALL_H__
+#endif  // ROCKETMQ_COMMON_UTILALL_H_
diff --git a/src/common/Validators.cpp b/src/common/Validators.cpp
index 4cd843e..9525a41 100644
--- a/src/common/Validators.cpp
+++ b/src/common/Validators.cpp
@@ -103,7 +103,7 @@ void Validators::checkMessage(const Message& msg, int maxMessageSize) {
     THROW_MQEXCEPTION(MQClientException, "the message body is empty", MESSAGE_ILLEGAL);
   }
 
-  if (body.length() > (size_t)maxMessageSize) {
+  if (body.size() > (size_t)maxMessageSize) {
     std::string info = "the message body size over max value, MAX: " + UtilAll::to_string(maxMessageSize);
     THROW_MQEXCEPTION(MQClientException, info, MESSAGE_ILLEGAL);
   }
diff --git a/src/common/big_endian.cpp b/src/common/big_endian.cpp
deleted file mode 100644
index f2e1927..0000000
--- a/src/common/big_endian.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "big_endian.h"
-
-#include <cstdlib>
-#include <cstring>
-
-namespace rocketmq {
-
-BigEndianReader::BigEndianReader(const char* buf, size_t len) : ptr_(buf), end_(ptr_ + len) {}
-
-bool BigEndianReader::Skip(size_t len) {
-  if (ptr_ + len > end_)
-    return false;
-  ptr_ += len;
-  return true;
-}
-
-bool BigEndianReader::ReadBytes(void* out, size_t len) {
-  if (ptr_ + len > end_)
-    return false;
-  memcpy(out, ptr_, len);
-  ptr_ += len;
-  return true;
-}
-
-template <typename T>
-bool BigEndianReader::Read(T* value) {
-  if (ptr_ + sizeof(T) > end_)
-    return false;
-  ReadBigEndian<T>(ptr_, value);
-  ptr_ += sizeof(T);
-  return true;
-}
-
-bool BigEndianReader::ReadU8(uint8_t* value) {
-  return Read(value);
-}
-
-bool BigEndianReader::ReadU16(uint16_t* value) {
-  return Read(value);
-}
-
-bool BigEndianReader::ReadU32(uint32_t* value) {
-  return Read(value);
-}
-
-bool BigEndianReader::ReadU64(uint64_t* value) {
-  return Read(value);
-}
-
-BigEndianWriter::BigEndianWriter(char* buf, size_t len) : ptr_(buf), end_(ptr_ + len) {}
-
-bool BigEndianWriter::Skip(size_t len) {
-  if (ptr_ + len > end_)
-    return false;
-  ptr_ += len;
-  return true;
-}
-
-bool BigEndianWriter::WriteBytes(const void* buf, size_t len) {
-  if (ptr_ + len > end_)
-    return false;
-  memcpy(ptr_, buf, len);
-  ptr_ += len;
-  return true;
-}
-
-template <typename T>
-bool BigEndianWriter::Write(T value) {
-  if (ptr_ + sizeof(T) > end_)
-    return false;
-  WriteBigEndian<T>(ptr_, value);
-  ptr_ += sizeof(T);
-  return true;
-}
-
-bool BigEndianWriter::WriteU8(uint8_t value) {
-  return Write(value);
-}
-
-bool BigEndianWriter::WriteU16(uint16_t value) {
-  return Write(value);
-}
-
-bool BigEndianWriter::WriteU32(uint32_t value) {
-  return Write(value);
-}
-
-bool BigEndianWriter::WriteU64(uint64_t value) {
-  return Write(value);
-}
-
-}  // namespace rocketmq
diff --git a/src/common/big_endian.h b/src/common/big_endian.h
deleted file mode 100644
index ad59196..0000000
--- a/src/common/big_endian.h
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_BIG_ENDIAN_H_
-#define BASE_BIG_ENDIAN_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-namespace rocketmq {
-
-// Read an integer (signed or unsigned) from |buf| in Big Endian order.
-// Note: this loop is unrolled with -O1 and above.
-// NOTE(szym): glibc dns-canon.c use ntohs(*(uint16_t*)ptr) which is
-// potentially unaligned.
-// This would cause SIGBUS on ARMv5 or earlier and ARMv6-M.
-template <typename T>
-inline void ReadBigEndian(const char buf[], T* out) {
-  *out = buf[0];
-  for (size_t i = 1; i < sizeof(T); ++i) {
-    *out <<= 8;
-    // Must cast to uint8_t to avoid clobbering by sign extension.
-    *out |= static_cast<uint8_t>(buf[i]);
-  }
-}
-
-// Write an integer (signed or unsigned) |val| to |buf| in Big Endian order.
-// Note: this loop is unrolled with -O1 and above.
-template <typename T>
-inline void WriteBigEndian(char buf[], T val) {
-  for (size_t i = 0; i < sizeof(T); ++i) {
-    buf[sizeof(T) - i - 1] = static_cast<char>(val & 0xFF);
-    val >>= 8;
-  }
-}
-
-// Specializations to make clang happy about the (dead code) shifts above.
-template <>
-inline void ReadBigEndian<uint8_t>(const char buf[], uint8_t* out) {
-  *out = buf[0];
-}
-
-template <>
-inline void WriteBigEndian<uint8_t>(char buf[], uint8_t val) {
-  buf[0] = static_cast<char>(val);
-}
-
-// Allows reading integers in network order (big endian) while iterating over
-// an underlying buffer. All the reading functions advance the internal pointer.
-class BigEndianReader {
- public:
-  BigEndianReader(const char* buf, size_t len);
-
-  const char* ptr() const { return ptr_; }
-  int remaining() const { return end_ - ptr_; }
-
-  bool Skip(size_t len);
-  bool ReadBytes(void* out, size_t len);
-  bool ReadU8(uint8_t* value);
-  bool ReadU16(uint16_t* value);
-  bool ReadU32(uint32_t* value);
-  bool ReadU64(uint64_t* value);
-
- private:
-  // Hidden to promote type safety.
-  template <typename T>
-  bool Read(T* v);
-
-  const char* ptr_;
-  const char* end_;
-};
-
-// Allows writing integers in network order (big endian) while iterating over
-// an underlying buffer. All the writing functions advance the internal pointer.
-class BigEndianWriter {
- public:
-  BigEndianWriter(char* buf, size_t len);
-
-  char* ptr() const { return ptr_; }
-  int remaining() const { return end_ - ptr_; }
-
-  bool Skip(size_t len);
-  bool WriteBytes(const void* buf, size_t len);
-  bool WriteU8(uint8_t value);
-  bool WriteU16(uint16_t value);
-  bool WriteU32(uint32_t value);
-  bool WriteU64(uint64_t value);
-
- private:
-  // Hidden to promote type safety.
-  template <typename T>
-  bool Write(T v);
-
-  char* ptr_;
-  char* end_;
-};
-
-}  // namespace rocketmq
-
-#endif  // BASE_BIG_ENDIAN_H_
diff --git a/src/consumer/DefaultMQPushConsumer.cpp b/src/consumer/DefaultMQPushConsumer.cpp
index 4ef9b36..d729948 100644
--- a/src/consumer/DefaultMQPushConsumer.cpp
+++ b/src/consumer/DefaultMQPushConsumer.cpp
@@ -27,7 +27,7 @@ DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& groupname)
 
 DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& groupname, RPCHookPtr rpcHook)
     : DefaultMQPushConsumerConfigProxy(std::make_shared<DefaultMQPushConsumerConfigImpl>()),
-      m_pushConsumerDelegate(nullptr) {
+      push_consumer_impl_(nullptr) {
   // set default group name
   if (groupname.empty()) {
     setGroupName(DEFAULT_CONSUMER_GROUP);
@@ -35,61 +35,61 @@ DefaultMQPushConsumer::DefaultMQPushConsumer(const std::string& groupname, RPCHo
     setGroupName(groupname);
   }
 
-  m_pushConsumerDelegate = DefaultMQPushConsumerImpl::create(getRealConfig(), rpcHook);
+  push_consumer_impl_ = DefaultMQPushConsumerImpl::create(getRealConfig(), rpcHook);
 }
 
 DefaultMQPushConsumer::~DefaultMQPushConsumer() = default;
 
 void DefaultMQPushConsumer::start() {
-  m_pushConsumerDelegate->start();
+  push_consumer_impl_->start();
 }
 
 void DefaultMQPushConsumer::shutdown() {
-  m_pushConsumerDelegate->shutdown();
+  push_consumer_impl_->shutdown();
 }
 
 bool DefaultMQPushConsumer::sendMessageBack(MessageExtPtr msg, int delayLevel) {
-  return m_pushConsumerDelegate->sendMessageBack(msg, delayLevel);
+  return push_consumer_impl_->sendMessageBack(msg, delayLevel);
 }
 
 bool DefaultMQPushConsumer::sendMessageBack(MessageExtPtr msg, int delayLevel, const std::string& brokerName) {
-  return m_pushConsumerDelegate->sendMessageBack(msg, delayLevel, brokerName);
+  return push_consumer_impl_->sendMessageBack(msg, delayLevel, brokerName);
 }
 
 void DefaultMQPushConsumer::fetchSubscribeMessageQueues(const std::string& topic, std::vector<MQMessageQueue>& mqs) {
-  m_pushConsumerDelegate->fetchSubscribeMessageQueues(topic, mqs);
+  push_consumer_impl_->fetchSubscribeMessageQueues(topic, mqs);
 }
 
 void DefaultMQPushConsumer::registerMessageListener(MQMessageListener* messageListener) {
-  m_pushConsumerDelegate->registerMessageListener(messageListener);
+  push_consumer_impl_->registerMessageListener(messageListener);
 }
 
 void DefaultMQPushConsumer::registerMessageListener(MessageListenerConcurrently* messageListener) {
-  m_pushConsumerDelegate->registerMessageListener(messageListener);
+  push_consumer_impl_->registerMessageListener(messageListener);
 }
 
 void DefaultMQPushConsumer::registerMessageListener(MessageListenerOrderly* messageListener) {
-  m_pushConsumerDelegate->registerMessageListener(messageListener);
+  push_consumer_impl_->registerMessageListener(messageListener);
 }
 
 MQMessageListener* DefaultMQPushConsumer::getMessageListener() const {
-  return m_pushConsumerDelegate->getMessageListener();
+  return push_consumer_impl_->getMessageListener();
 }
 
 void DefaultMQPushConsumer::subscribe(const std::string& topic, const std::string& subExpression) {
-  m_pushConsumerDelegate->subscribe(topic, subExpression);
+  push_consumer_impl_->subscribe(topic, subExpression);
 }
 
 void DefaultMQPushConsumer::suspend() {
-  m_pushConsumerDelegate->suspend();
+  push_consumer_impl_->suspend();
 }
 
 void DefaultMQPushConsumer::resume() {
-  m_pushConsumerDelegate->resume();
+  push_consumer_impl_->resume();
 }
 
 void DefaultMQPushConsumer::setRPCHook(RPCHookPtr rpcHook) {
-  std::dynamic_pointer_cast<DefaultMQPushConsumerImpl>(m_pushConsumerDelegate)->setRPCHook(rpcHook);
+  std::dynamic_pointer_cast<DefaultMQPushConsumerImpl>(push_consumer_impl_)->setRPCHook(rpcHook);
 }
 
 }  // namespace rocketmq
diff --git a/src/consumer/PullAPIWrapper.cpp b/src/consumer/PullAPIWrapper.cpp
index 4b7e936..221f285 100644
--- a/src/consumer/PullAPIWrapper.cpp
+++ b/src/consumer/PullAPIWrapper.cpp
@@ -16,6 +16,7 @@
  */
 #include "PullAPIWrapper.h"
 
+#include "ByteBuffer.hpp"
 #include "MQClientAPIImpl.h"
 #include "MQClientInstance.h"
 #include "MessageDecoder.h"
@@ -56,12 +57,13 @@ PullResult PullAPIWrapper::processPullResult(const MQMessageQueue& mq,
   auto& pullResultExt = dynamic_cast<PullResultExt&>(pullResult);
 
   // update node
-  updatePullFromWhichNode(mq, pullResultExt.suggestWhichBrokerId);
+  updatePullFromWhichNode(mq, pullResultExt.suggert_which_boker_id());
 
   std::vector<MessageExtPtr> msgListFilterAgain;
   if (FOUND == pullResultExt.pull_status()) {
     // decode all msg list
-    auto msgList = MessageDecoder::decodes(*pullResultExt.msgMemBlock);
+    std::unique_ptr<ByteBuffer> byteBuffer(ByteBuffer::wrap(pullResultExt.message_binary()));
+    auto msgList = MessageDecoder::decodes(*byteBuffer);
 
     // filter msg list again
     if (subscriptionData != nullptr && !subscriptionData->getTagsSet().empty()) {
diff --git a/src/consumer/PullRequest.cpp b/src/consumer/PullRequest.cpp
index 2df5760..2ff69d0 100644
--- a/src/consumer/PullRequest.cpp
+++ b/src/consumer/PullRequest.cpp
@@ -16,6 +16,8 @@
  */
 #include "PullRequest.h"
 
+#include <sstream>  // std::stringstream
+
 #include "Logging.h"
 
 namespace rocketmq {
@@ -64,4 +66,11 @@ void PullRequest::setProcessQueue(ProcessQueuePtr processQueue) {
   m_processQueue = processQueue;
 }
 
+std::string PullRequest::toString() const {
+  std::stringstream ss;
+  ss << "PullRequest [consumerGroup=" << m_consumerGroup << ", messageQueue=" << m_messageQueue.toString()
+     << ", nextOffset=" << m_nextOffset << "]";
+  return ss.str();
+}
+
 }  // namespace rocketmq
diff --git a/src/consumer/PullRequest.h b/src/consumer/PullRequest.h
index 7de7369..e86c07d 100644
--- a/src/consumer/PullRequest.h
+++ b/src/consumer/PullRequest.h
@@ -49,12 +49,7 @@ class ROCKETMQCLIENT_API PullRequest {
   ProcessQueuePtr getProcessQueue();
   void setProcessQueue(ProcessQueuePtr processQueue);
 
-  std::string toString() const {
-    std::stringstream ss;
-    ss << "PullRequest [consumerGroup=" << m_consumerGroup << ", messageQueue=" << m_messageQueue.toString()
-       << ", nextOffset=" << m_nextOffset << "]";
-    return ss.str();
-  }
+  std::string toString() const;
 
  private:
   std::string m_consumerGroup;
diff --git a/src/consumer/PullResultExt.h b/src/consumer/PullResultExt.h
index 420419c..4bbdc1d 100644
--- a/src/consumer/PullResultExt.h
+++ b/src/consumer/PullResultExt.h
@@ -16,8 +16,7 @@
  */
 #include "PullResult.h"
 
-#include "DataBlock.h"
-#include "UtilAll.h"
+#include "ByteArray.h"
 
 namespace rocketmq {
 
@@ -38,16 +37,20 @@ class PullResultExt : public PullResult {
                 int64_t minOffset,
                 int64_t maxOffset,
                 int suggestWhichBrokerId,
-                MemoryBlockPtr2 messageBinary)
+                ByteArrayRef messageBinary)
       : PullResult(pullStatus, nextBeginOffset, minOffset, maxOffset),
-        suggestWhichBrokerId(suggestWhichBrokerId),
-        msgMemBlock(messageBinary) {}
+        suggert_which_boker_id_(suggestWhichBrokerId),
+        message_binary_(messageBinary) {}
 
   ~PullResultExt() override = default;
 
  public:
-  int suggestWhichBrokerId;
-  MemoryBlockPtr2 msgMemBlock;
+  inline int suggert_which_boker_id() const { return suggert_which_boker_id_; }
+  inline ByteArrayRef message_binary() const { return message_binary_; }
+
+ private:
+  int suggert_which_boker_id_;
+  ByteArrayRef message_binary_;
 };
 
 }  // namespace rocketmq
diff --git a/src/extern/CMessage.cpp b/src/extern/CMessage.cpp
index 588668d..b7db245 100644
--- a/src/extern/CMessage.cpp
+++ b/src/extern/CMessage.cpp
@@ -64,7 +64,7 @@ int SetMessageBody(CMessage* msg, const char* body) {
   if (msg == NULL) {
     return NULL_POINTER;
   }
-  reinterpret_cast<MQMessage*>(msg)->setBody(body);
+  reinterpret_cast<MQMessage*>(msg)->setBody(std::string(body));
   return OK;
 }
 
@@ -72,7 +72,8 @@ int SetByteMessageBody(CMessage* msg, const char* body, int len) {
   if (msg == NULL) {
     return NULL_POINTER;
   }
-  reinterpret_cast<MQMessage*>(msg)->setBody(body, len);
+
+  reinterpret_cast<MQMessage*>(msg)->setBody(std::string(body, len));
   return OK;
 }
 
diff --git a/src/io/Buffer.hpp b/src/io/Buffer.hpp
new file mode 100644
index 0000000..a066e2c
--- /dev/null
+++ b/src/io/Buffer.hpp
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef ROCKETMQ_IO_BUFFER_HPP_
+#define ROCKETMQ_IO_BUFFER_HPP_
+
+#include <stdexcept>  // std::invalid_argument, std::runtime_error
+
+#include "RocketMQClient.h"
+
+#include "UtilAll.h"
+
+namespace rocketmq {
+
+template <typename A>
+class Buffer {
+ protected:
+  Buffer(int32_t mark, int32_t pos, int32_t lim, int32_t cap) throw(std::invalid_argument) {
+    if (cap < 0) {
+      throw std::invalid_argument("Negative capacity: " + UtilAll::to_string(cap));
+    }
+    capacity_ = cap;
+    limit(lim);
+    position(pos);
+    if (mark >= 0) {
+      if (mark > pos) {
+        throw std::invalid_argument("mark > position: (" + UtilAll::to_string(mark) + " > " + UtilAll::to_string(pos) +
+                                    ")");
+      }
+      mark_ = mark;
+    }
+  }
+
+ public:
+  Buffer& position(int new_position) throw(std::invalid_argument) {
+    if ((new_position > limit_) || (new_position < 0)) {
+      throw std::invalid_argument("");
+    }
+    position_ = new_position;
+    if (mark_ > position_) {
+      mark_ = -1;
+    }
+    return *this;
+  }
+
+  Buffer& limit(int new_limit) throw(std::invalid_argument) {
+    if ((new_limit > capacity_) || (new_limit < 0)) {
+      throw std::invalid_argument("");
+    }
+    limit_ = new_limit;
+    if (position_ > limit_) {
+      position_ = limit_;
+    }
+    if (mark_ > limit_) {
+      mark_ = -1;
+    }
+    return *this;
+  }
+
+  Buffer& mark() {
+    mark_ = position_;
+    return *this;
+  }
+
+  Buffer& reset() {
+    int m = mark_;
+    if (m < 0) {
+      throw std::runtime_error("InvalidMarkException");
+    }
+    position_ = m;
+    return *this;
+  }
+
+  Buffer& clear() {
+    position_ = 0;
+    limit_ = capacity_;
+    mark_ = -1;
+    return *this;
+  }
+
+  Buffer& flip() {
+    limit_ = position_;
+    position_ = 0;
+    mark_ = -1;
+    return *this;
+  }
+
+  Buffer& rewind() {
+    position_ = 0;
+    mark_ = -1;
+    return *this;
+  }
+
+  inline int32_t remaining() const { return limit_ - position_; }
+  inline bool hasRemaining() const { return position_ < limit_; }
+
+  virtual bool isReadOnly() = 0;
+  virtual bool hasArray() = 0;
+  virtual A* array() = 0;
+  virtual int32_t arrayOffset() = 0;
+
+ protected:
+  int32_t nextGetIndex() {
+    if (position_ >= limit_) {
+      throw std::runtime_error("BufferUnderflowException");
+    }
+    return position_++;
+  }
+
+  int32_t nextGetIndex(int32_t nb) {
+    if (limit_ - position_ < nb) {
+      throw std::runtime_error("BufferUnderflowException");
+    }
+    int32_t p = position_;
+    position_ += nb;
+    return p;
+  }
+
+  int32_t nextPutIndex() {
+    if (position_ >= limit_) {
+      throw std::runtime_error("BufferOverflowException");
+    }
+    return position_++;
+  }
+
+  int32_t nextPutIndex(int32_t nb) {
+    if (limit_ - position_ < nb) {
+      throw std::runtime_error("BufferOverflowException");
+    }
+    int32_t p = position_;
+    position_ += nb;
+    return p;
+  }
+
+  int32_t checkIndex(int32_t i) const {
+    if ((i < 0) || (i >= limit_)) {
+      throw std::runtime_error("IndexOutOfBoundsException");
+    }
+    return i;
+  }
+
+  int32_t checkIndex(int32_t i, int32_t nb) const {
+    if ((i < 0) || (nb > limit_ - i)) {
+      throw std::runtime_error("IndexOutOfBoundsException");
+    }
+    return i;
+  }
+
+  void truncate() {
+    mark_ = -1;
+    position_ = 0;
+    limit_ = 0;
+    capacity_ = 0;
+  }
+
+  void discardMark() { mark_ = -1; }
+
+  static void checkBounds(int32_t off, int32_t len, int32_t size) {
+    if ((off | len | (off + len) | (size - (off + len))) < 0) {
+      throw std::runtime_error("IndexOutOfBoundsException");
+    }
+  }
+
+ public:
+  inline int32_t mark_value() const { return mark_; }
+  inline int32_t position() const { return position_; }
+  inline int32_t limit() const { return limit_; }
+  inline int32_t capacity() const { return capacity_; }
+
+ private:
+  // Invariants: mark <= position <= limit <= capacity
+  int32_t mark_ = -1;
+  int32_t position_ = 0;
+  int32_t limit_;
+  int32_t capacity_;
+};
+
+}  // namespace rocketmq
+
+#endif  // ROCKETMQ_IO_BUFFER_HPP_
diff --git a/src/io/ByteArray.cpp b/src/io/ByteArray.cpp
new file mode 100644
index 0000000..16568e0
--- /dev/null
+++ b/src/io/ByteArray.cpp
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "ByteArray.h"
+
+#include <cstring>  // std::memcpy
+
+#include <algorithm>  // std::move
+#include <stdexcept>  //
+#include <string>     // std::string
+
+namespace rocketmq {
+
+class ByteArrayView : public ByteArray {
+ public:
+  ByteArrayView(ByteArrayRef ba, size_t offset, size_t size) : ByteArray(ba->array() + offset, size), origin_(ba) {}
+  ByteArrayView(ByteArrayRef ba, size_t offset) : ByteArrayView(ba, offset, ba->size() - offset) {}
+
+  ByteArrayRef origin() { return origin_; }
+
+ private:
+  ByteArrayRef origin_;
+};
+
+ByteArrayRef slice(ByteArrayRef ba, size_t offset) {
+  return slice(ba, offset, ba->size() - offset);
+}
+
+ByteArrayRef slice(ByteArrayRef ba, size_t offset, size_t size) {
+  if (offset < 0 || size < 0 || ba->size() < offset + size) {
+    std::invalid_argument("");
+  }
+  return std::make_shared<ByteArrayView>(ba, offset, size);
+}
+
+class StringBaseByteArray : public ByteArray {
+ public:
+  StringBaseByteArray(const std::string& str) : ByteArray(nullptr, str.size()), string_(str) {
+    // Since C++11, The returned array is null-terminated, that is, data() and c_str() perform the same function.
+    // If empty() returns true, the pointer points to a single null character.
+    array_ = (char*)string_.data();
+  }
+  StringBaseByteArray(std::string&& str) : ByteArray(nullptr, str.size()), string_(std::move(str)) {
+    array_ = (char*)string_.data();
+  }
+
+  std::string sting() { return string_; }
+
+ private:
+  std::string string_;
+};
+
+ByteArrayRef stoba(const std::string& str) {
+  return std::make_shared<StringBaseByteArray>(str);
+}
+
+ByteArrayRef stoba(std::string&& str) {
+  return std::make_shared<StringBaseByteArray>(std::move(str));
+}
+
+ByteArrayRef catoba(const char* str, size_t len) {
+  return stoba(std::string(str, len));
+}
+
+std::string batos(ByteArrayRef ba) {
+  return std::string(ba->array(), ba->size());
+}
+
+}  // namespace rocketmq
diff --git a/include/CommandCustomHeader.h b/src/io/ByteBuffer.cpp
similarity index 62%
copy from include/CommandCustomHeader.h
copy to src/io/ByteBuffer.cpp
index 66c1b56..f12bd72 100644
--- a/include/CommandCustomHeader.h
+++ b/src/io/ByteBuffer.cpp
@@ -14,30 +14,27 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#ifndef __COMMAND_CUSTOM_HEADER_H__
-#define __COMMAND_CUSTOM_HEADER_H__
+#include "ByteBuffer.hpp"
 
-#include <map>
-#include <string>
+#include <algorithm>  // std::move
 
-#include "RocketMQClient.h"
-
-namespace Json {
-class Value;
-}
+#include "DefaultByteBuffer.hpp"
 
 namespace rocketmq {
 
-class ROCKETMQCLIENT_API CommandCustomHeader {
- public:
-  virtual ~CommandCustomHeader() = default;
-
-  // write CustomHeader to extFields (map<string,string>)
-  virtual void Encode(Json::Value& extFields) {}
+ByteBuffer* ByteBuffer::allocate(int32_t capacity) {
+  if (capacity < 0) {
+    throw std::invalid_argument("");
+  }
+  return new DefaultByteBuffer(capacity, capacity);
+}
 
-  virtual void SetDeclaredFieldOfCommandHeader(std::map<std::string, std::string>& requestMap) {}
-};
+ByteBuffer* ByteBuffer::wrap(ByteArrayRef array, int32_t offset, int32_t length) {
+  try {
+    return new DefaultByteBuffer(std::move(array), offset, length);
+  } catch (const std::exception& x) {
+    throw std::runtime_error("IndexOutOfBoundsException");
+  }
+}
 
 }  // namespace rocketmq
-
-#endif  // __COMMAND_CUSTOM_HEADER_H__
diff --git a/src/io/ByteBuffer.hpp b/src/io/ByteBuffer.hpp
new file mode 100644
index 0000000..5a30250
--- /dev/null
+++ b/src/io/ByteBuffer.hpp
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef ROCKETMQ_IO_BYTEBUFFER_HPP_
+#define ROCKETMQ_IO_BYTEBUFFER_HPP_
+
+#include <sstream>  // std::stringstream
+
+#include "ByteArray.h"
+#include "Buffer.hpp"
+#include "ByteOrder.h"
+
+namespace rocketmq {
+
+class ByteBuffer : public Buffer<char> {
+ public:
+  static ByteBuffer* allocate(int32_t capacity);
+
+  static ByteBuffer* wrap(ByteArrayRef array, int32_t offset, int32_t length);
+  static ByteBuffer* wrap(ByteArrayRef array) { return wrap(array, 0, array->size()); }
+
+ protected:
+  ByteBuffer(int32_t mark, int32_t pos, int32_t lim, int32_t cap, ByteArrayRef byte_array, int32_t offset)
+      : Buffer(mark, pos, lim, cap),
+        byte_array_(std::move(byte_array)),
+        offset_(offset),
+        is_read_only_(false),
+        big_endian_(true) {}
+
+  ByteBuffer(int32_t mark, int32_t pos, int32_t lim, int32_t cap) : ByteBuffer(mark, pos, lim, cap, nullptr, 0) {}
+
+ public:
+  virtual ~ByteBuffer() = default;
+
+ public:
+  virtual ByteBuffer* slice() = 0;
+  virtual ByteBuffer* duplicate() = 0;
+  virtual ByteBuffer* asReadOnlyBuffer() = 0;
+
+  // get/put routine
+  // ======================
+
+  virtual char get() = 0;
+  virtual ByteBuffer& put(char b) = 0;
+
+  virtual char get(int32_t index) const = 0;
+  virtual ByteBuffer& put(int32_t index, char b) = 0;
+
+  virtual ByteBuffer& get(ByteArray& dst, int32_t offset, int32_t length) {
+    checkBounds(offset, length, dst.size());
+    if (length > remaining()) {
+      throw std::runtime_error("BufferUnderflowException");
+    }
+    int32_t end = offset + length;
+    for (int32_t i = offset; i < end; i++) {
+      dst[i] = get();
+    }
+    return *this;
+  }
+
+  ByteBuffer& get(ByteArray& dst) { return get(dst, 0, dst.size()); }
+
+  virtual ByteBuffer& put(ByteBuffer& src) {
+    if (&src == this) {
+      throw std::invalid_argument("");
+    }
+    if (isReadOnly()) {
+      throw std::runtime_error("ReadOnlyBufferException");
+    }
+    int32_t n = src.remaining();
+    if (n > remaining()) {
+      throw std::runtime_error("BufferOverflowException");
+    }
+    for (int32_t i = 0; i < n; i++) {
+      put(src.get());
+    }
+    return *this;
+  }
+
+  virtual ByteBuffer& put(const ByteArray& src, int32_t offset, int32_t length) {
+    checkBounds(offset, length, src.size());
+    if (length > remaining()) {
+      throw std::runtime_error("BufferOverflowException");
+    }
+    int32_t end = offset + length;
+    for (int32_t i = offset; i < end; i++) {
+      put(src[i]);
+    }
+    return *this;
+  }
+
+  ByteBuffer& put(const ByteArray& src) { return put(src, 0, src.size()); }
+
+ public:
+  bool hasArray() override final { return (byte_array_ != nullptr) && !is_read_only_; }
+
+  char* array() override final {
+    if (byte_array_ == nullptr) {
+      throw std::runtime_error("UnsupportedOperationException");
+    }
+    if (is_read_only_) {
+      throw std::runtime_error("ReadOnlyBufferException");
+    }
+    return byte_array_->array();
+  }
+
+  int32_t arrayOffset() override final {
+    if (byte_array_ == nullptr) {
+      throw std::runtime_error("UnsupportedOperationException");
+    }
+    if (is_read_only_) {
+      throw std::runtime_error("ReadOnlyBufferException");
+    }
+    return offset_;
+  }
+
+  virtual ByteBuffer& compact() = 0;
+
+  virtual std::string toString() {
+    std::stringstream ss;
+    ss << "ByteBuffer"
+       << "[pos=" << position() << " lim=" << limit() << " cap=" << capacity() << "]";
+    return ss.str();
+  }
+
+  inline ByteOrder order() const { return big_endian_ ? ByteOrder::BO_BIG_ENDIAN : ByteOrder::BO_LITTLE_ENDIAN; }
+
+  inline ByteBuffer& order(ByteOrder bo) {
+    big_endian_ = (bo == ByteOrder::BO_BIG_ENDIAN);
+    return *this;
+  }
+
+  inline ByteArrayRef byte_array() { return byte_array_; }
+
+ public:
+  virtual int16_t getShort() = 0;
+  virtual ByteBuffer& putShort(int16_t value) = 0;
+  virtual int16_t getShort(int32_t index) = 0;
+  virtual ByteBuffer& putShort(int32_t index, int16_t value) = 0;
+
+  virtual int32_t getInt() = 0;
+  virtual ByteBuffer& putInt(int32_t value) = 0;
+  virtual int32_t getInt(int32_t index) = 0;
+  virtual ByteBuffer& putInt(int32_t index, int32_t value) = 0;
+
+  virtual int64_t getLong() = 0;
+  virtual ByteBuffer& putLong(int64_t value) = 0;
+  virtual int64_t getLong(int32_t index) = 0;
+  virtual ByteBuffer& putLong(int32_t index, int64_t value) = 0;
+
+  virtual float getFloat() = 0;
+  virtual ByteBuffer& putFloat(float value) = 0;
+  virtual float getFloat(int32_t index) = 0;
+  virtual ByteBuffer& putFloat(int32_t index, float value) = 0;
+
+  virtual double getDouble() = 0;
+  virtual ByteBuffer& putDouble(double value) = 0;
+  virtual double getDouble(int32_t index) = 0;
+  virtual ByteBuffer& putDouble(int32_t index, double value) = 0;
+
+ protected:
+  ByteArrayRef byte_array_;
+  int32_t offset_;
+  bool is_read_only_;
+
+  bool big_endian_;
+};
+
+}  // namespace rocketmq
+
+#endif  // ROCKETMQ_IO_BYTEBUFFER_HPP_
\ No newline at end of file
diff --git a/src/io/DefaultByteBuffer.hpp b/src/io/DefaultByteBuffer.hpp
new file mode 100644
index 0000000..73a4039
--- /dev/null
+++ b/src/io/DefaultByteBuffer.hpp
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef ROCKETMQ_IO_DEFAULTBYTEBUFFER_HPP_
+#define ROCKETMQ_IO_DEFAULTBYTEBUFFER_HPP_
+
+#include <cstdlib>  // std::memcpy
+
+#include <algorithm>  // std::move
+#include <typeindex>  // std::type_index
+
+#include "ByteBuffer.hpp"
+
+namespace rocketmq {
+
+class DefaultByteBuffer : public ByteBuffer {
+ protected:
+  friend class ByteBuffer;
+
+  DefaultByteBuffer(int32_t cap, int32_t lim) : ByteBuffer(-1, 0, lim, cap, std::make_shared<ByteArray>(cap), 0) {}
+
+  DefaultByteBuffer(ByteArrayRef buf, int32_t off, int32_t len)
+      : ByteBuffer(-1, off, off + len, buf->size(), std::move(buf), 0) {}
+
+  DefaultByteBuffer(ByteArrayRef buf, int32_t mark, int32_t pos, int32_t lim, int32_t cap, int32_t off)
+      : ByteBuffer(mark, pos, lim, cap, std::move(buf), off) {}
+
+ public:
+  ByteBuffer* slice() override {
+    return new DefaultByteBuffer(byte_array_, -1, 0, remaining(), remaining(), position() + offset_);
+  }
+
+  ByteBuffer* duplicate() override {
+    return new DefaultByteBuffer(byte_array_, mark_value(), position(), limit(), capacity(), offset_);
+  }
+
+  ByteBuffer* asReadOnlyBuffer() override {
+    // return new HeapByteBufferR(byte_array_, mark_value(), position(), limit(), capacity(), offset_);
+    return nullptr;
+  }
+
+  char get() override { return (*byte_array_)[ix(nextGetIndex())]; }
+  char get(int i) const override { return (*byte_array_)[ix(checkIndex(i))]; }
+
+  ByteBuffer& get(ByteArray& dst, int32_t offset, int length) override {
+    checkBounds(offset, length, dst.size());
+    if (length > remaining()) {
+      throw std::runtime_error("BufferUnderflowException");
+    }
+    std::memcpy(dst.array() + offset, byte_array_->array() + ix(position()), length);
+    position(position() + length);
+    return *this;
+  }
+
+  ByteBuffer& put(char x) override {
+    (*byte_array_)[ix(nextPutIndex())] = x;
+    return *this;
+  }
+
+  ByteBuffer& put(int32_t i, char x) override {
+    (*byte_array_)[ix(checkIndex(i))] = x;
+    return *this;
+  }
+
+  ByteBuffer& put(const ByteArray& src, int offset, int length) override {
+    checkBounds(offset, length, src.size());
+    if (length > remaining()) {
+      throw std::runtime_error("BufferOverflowException");
+    }
+    std::memcpy(byte_array_->array() + ix(position()), src.array() + offset, length);
+    position(position() + length);
+    return *this;
+  }
+
+  ByteBuffer& put(ByteBuffer& src) override {
+    if (std::type_index(typeid(src)) == std::type_index(typeid(DefaultByteBuffer))) {
+      if (&src == this) {
+        throw std::invalid_argument("");
+      }
+      DefaultByteBuffer& sb = dynamic_cast<DefaultByteBuffer&>(src);
+      int32_t n = sb.remaining();
+      if (n > remaining()) {
+        throw std::runtime_error("BufferOverflowException");
+      }
+      std::memcpy(byte_array_->array() + ix(position()), sb.byte_array_->array() + sb.ix(sb.position()), n);
+      sb.position(sb.position() + n);
+      position(position() + n);
+    } else {
+      ByteBuffer::put(src);
+    }
+    return *this;
+  }
+
+ public:
+  bool isReadOnly() override { return false; }
+
+  ByteBuffer& compact() override {
+    std::memcpy(byte_array_->array() + ix(0), byte_array_->array() + ix(position()), remaining());
+    position(remaining());
+    limit(capacity());
+    discardMark();
+    return *this;
+  }
+
+ public:
+  int16_t getShort() override {
+    return ByteOrderUtil::Read<uint16_t>(byte_array_->array() + ix(nextGetIndex(2)), big_endian_);
+  }
+
+  int16_t getShort(int32_t i) override {
+    return ByteOrderUtil::Read<uint16_t>(byte_array_->array() + ix(checkIndex(i, 2)), big_endian_);
+  }
+
+  ByteBuffer& putShort(int16_t x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(nextPutIndex(2)), x, big_endian_);
+    return *this;
+  }
+
+  ByteBuffer& putShort(int32_t i, int16_t x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(checkIndex(i, 2)), x, big_endian_);
+    return *this;
+  }
+
+  int32_t getInt() override {
+    return ByteOrderUtil::Read<uint32_t>(byte_array_->array() + ix(nextGetIndex(4)), big_endian_);
+  }
+  int32_t getInt(int32_t i) override {
+    return ByteOrderUtil::Read<uint32_t>(byte_array_->array() + ix(checkIndex(i, 4)), big_endian_);
+  }
+
+  ByteBuffer& putInt(int32_t x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(nextPutIndex(4)), x, big_endian_);
+    return *this;
+  }
+
+  ByteBuffer& putInt(int32_t i, int32_t x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(checkIndex(i, 4)), x, big_endian_);
+    return *this;
+  }
+
+  int64_t getLong() override {
+    return ByteOrderUtil::Read<uint64_t>(byte_array_->array() + ix(nextGetIndex(8)), big_endian_);
+  }
+
+  int64_t getLong(int32_t i) override {
+    return ByteOrderUtil::Read<uint64_t>(byte_array_->array() + ix(checkIndex(i, 8)), big_endian_);
+  }
+
+  ByteBuffer& putLong(int64_t x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(nextPutIndex(8)), x, big_endian_);
+    return *this;
+  }
+
+  ByteBuffer& putLong(int32_t i, int64_t x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(checkIndex(i, 8)), x, big_endian_);
+    return *this;
+  }
+
+  float getFloat() override {
+    return ByteOrderUtil::ReinterpretRawBits<float, uint32_t>(
+        ByteOrderUtil::Read<uint32_t>(byte_array_->array() + ix(nextGetIndex(4)), big_endian_));
+  }
+
+  float getFloat(int32_t i) override {
+    return ByteOrderUtil::ReinterpretRawBits<float, uint32_t>(
+        ByteOrderUtil::Read<uint32_t>(byte_array_->array() + ix(checkIndex(i, 4)), big_endian_));
+  }
+
+  ByteBuffer& putFloat(float x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(nextPutIndex(4)),
+                         ByteOrderUtil::ReinterpretRawBits<uint32_t, float>(x), big_endian_);
+    return *this;
+  }
+
+  ByteBuffer& putFloat(int32_t i, float x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(checkIndex(i, 4)),
+                         ByteOrderUtil::ReinterpretRawBits<uint32_t, float>(x), big_endian_);
+    return *this;
+  }
+
+  double getDouble() override {
+    return ByteOrderUtil::ReinterpretRawBits<double, uint64_t>(
+        ByteOrderUtil::Read<uint64_t>(byte_array_->array() + ix(nextGetIndex(8)), big_endian_));
+  }
+
+  double getDouble(int32_t i) override {
+    return ByteOrderUtil::ReinterpretRawBits<double, uint64_t>(
+        ByteOrderUtil::Read<uint64_t>(byte_array_->array() + ix(checkIndex(i, 8)), big_endian_));
+  }
+
+  ByteBuffer& putDouble(double x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(nextPutIndex(8)),
+                         ByteOrderUtil::ReinterpretRawBits<uint64_t, double>(x), big_endian_);
+    return *this;
+  }
+
+  ByteBuffer& putDouble(int32_t i, double x) override {
+    ByteOrderUtil::Write(byte_array_->array() + ix(checkIndex(i, 8)),
+                         ByteOrderUtil::ReinterpretRawBits<uint64_t, double>(x), big_endian_);
+    return *this;
+  }
+
+ protected:
+  inline int32_t ix(int32_t i) const { return i + offset_; }
+};
+
+}  // namespace rocketmq
+
+#endif  // ROCKETMQ_IO_DEFAULTBYTEBUFFER_HPP_
diff --git a/src/message/MQMessage.cpp b/src/message/MQMessage.cpp
index 71f8a30..0e46e9d 100644
--- a/src/message/MQMessage.cpp
+++ b/src/message/MQMessage.cpp
@@ -23,6 +23,10 @@
 
 namespace rocketmq {
 
+bool operator==(std::nullptr_t, const MQMessage& message) noexcept {
+  return nullptr == message.message_impl_;
+}
+
 MQMessage::MQMessage() : MQMessage(null, null) {}
 
 MQMessage::MQMessage(const std::string& topic, const std::string& body) : MQMessage(topic, null, body) {}
@@ -118,10 +122,6 @@ const std::string& MQMessage::getBody() const {
   return message_impl_->getBody();
 }
 
-void MQMessage::setBody(const char* body, int len) {
-  message_impl_->setBody(body, len);
-}
-
 void MQMessage::setBody(const std::string& body) {
   message_impl_->setBody(body);
 }
diff --git a/src/message/MQMessageQueue.cpp b/src/message/MQMessageQueue.cpp
index 50ab3f0..c9d913c 100644
--- a/src/message/MQMessageQueue.cpp
+++ b/src/message/MQMessageQueue.cpp
@@ -16,90 +16,56 @@
  */
 #include "MQMessageQueue.h"
 
+#include <sstream>  // std::stringstream
+
 namespace rocketmq {
 
-MQMessageQueue::MQMessageQueue() {
-  m_queueId = -1;  // invalide mq
-  m_topic.clear();
-  m_brokerName.clear();
-}
+MQMessageQueue::MQMessageQueue()
+    : queue_id_(-1)  // invalide mq
+{}
 
 MQMessageQueue::MQMessageQueue(const std::string& topic, const std::string& brokerName, int queueId)
-    : m_topic(topic), m_brokerName(brokerName), m_queueId(queueId) {}
+    : topic_(topic), broker_name_(brokerName), queue_id_(queueId) {}
 
 MQMessageQueue::MQMessageQueue(const MQMessageQueue& other)
-    : m_topic(other.m_topic), m_brokerName(other.m_brokerName), m_queueId(other.m_queueId) {}
+    : MQMessageQueue(other.topic_, other.broker_name_, other.queue_id_) {}
 
 MQMessageQueue& MQMessageQueue::operator=(const MQMessageQueue& other) {
   if (this != &other) {
-    m_brokerName = other.m_brokerName;
-    m_topic = other.m_topic;
-    m_queueId = other.m_queueId;
+    broker_name_ = other.broker_name_;
+    topic_ = other.topic_;
+    queue_id_ = other.queue_id_;
   }
   return *this;
 }
 
-const std::string& MQMessageQueue::getTopic() const {
-  return m_topic;
-}
-
-void MQMessageQueue::setTopic(const std::string& topic) {
-  m_topic = topic;
-}
-
-const std::string& MQMessageQueue::getBrokerName() const {
-  return m_brokerName;
-}
-
-// NOTE: only use to initial the mq
-void MQMessageQueue::setBrokerName(const std::string& brokerName) {
-  m_brokerName = brokerName;
-}
-
-int MQMessageQueue::getQueueId() const {
-  return m_queueId;
-}
-
-void MQMessageQueue::setQueueId(int queueId) {
-  m_queueId = queueId;
+bool MQMessageQueue::operator==(const MQMessageQueue& other) const {
+  return this == &other ||
+         (queue_id_ == other.queue_id_ && broker_name_ == other.broker_name_ && topic_ == other.topic_);
 }
 
-bool MQMessageQueue::operator==(const MQMessageQueue& mq) const {
-  if (this == &mq) {
-    return true;
-  }
-
-  if (m_brokerName != mq.m_brokerName) {
-    return false;
-  }
-
-  if (m_queueId != mq.m_queueId) {
-    return false;
-  }
-
-  if (m_topic != mq.m_topic) {
-    return false;
-  }
-
-  return true;
+bool MQMessageQueue::operator<(const MQMessageQueue& mq) const {
+  return compareTo(mq) < 0;
 }
 
 int MQMessageQueue::compareTo(const MQMessageQueue& mq) const {
-  int result = m_topic.compare(mq.m_topic);
+  int result = topic_.compare(mq.topic_);
   if (result != 0) {
     return result;
   }
 
-  result = m_brokerName.compare(mq.m_brokerName);
+  result = broker_name_.compare(mq.broker_name_);
   if (result != 0) {
     return result;
   }
 
-  return m_queueId - mq.m_queueId;
+  return queue_id_ - mq.queue_id_;
 }
 
-bool MQMessageQueue::operator<(const MQMessageQueue& mq) const {
-  return compareTo(mq) < 0;
+std::string MQMessageQueue::toString() const {
+  std::stringstream ss;
+  ss << "MessageQueue [topic=" << topic_ << ", brokerName=" << broker_name_ << ", queueId=" << queue_id_ << "]";
+  return ss.str();
 }
 
 }  // namespace rocketmq
diff --git a/src/message/MessageClientIDSetter.cpp b/src/message/MessageClientIDSetter.cpp
index c007638..450273e 100644
--- a/src/message/MessageClientIDSetter.cpp
+++ b/src/message/MessageClientIDSetter.cpp
@@ -33,9 +33,9 @@ namespace rocketmq {
 MessageClientIDSetter::MessageClientIDSetter() {
   std::srand((uint32_t)std::time(NULL));
 
-  uint32_t pid = ByteOrder::swapIfLittleEndian(static_cast<uint32_t>(UtilAll::getProcessId()));
-  uint32_t ip = ByteOrder::swapIfLittleEndian(UtilAll::getIP());
-  uint32_t random_num = ByteOrder::swapIfLittleEndian(static_cast<uint32_t>(std::rand()));
+  uint32_t pid = ByteOrderUtil::NorminalBigEndian(static_cast<uint32_t>(UtilAll::getProcessId()));
+  uint32_t ip = ByteOrderUtil::NorminalBigEndian(UtilAll::getIP());
+  uint32_t random_num = ByteOrderUtil::NorminalBigEndian(static_cast<uint32_t>(std::rand()));
 
   char bin_buf[10];
   std::memcpy(bin_buf + 2, &pid, 4);
@@ -90,8 +90,8 @@ std::string MessageClientIDSetter::createUniqueID() {
     current = UtilAll::currentTimeMillis();
   }
 
-  uint32_t period = ByteOrder::swapIfLittleEndian(static_cast<uint32_t>(current - mStartTime));
-  uint16_t seqid = ByteOrder::swapIfLittleEndian(mCounter++);
+  uint32_t period = ByteOrderUtil::NorminalBigEndian(static_cast<uint32_t>(current - mStartTime));
+  uint16_t seqid = ByteOrderUtil::NorminalBigEndian(mCounter++);
 
   char bin_buf[6];
   std::memcpy(bin_buf, &period, 4);
diff --git a/src/message/MessageDecoder.cpp b/src/message/MessageDecoder.cpp
index e7e4e59..d0ac623 100644
--- a/src/message/MessageDecoder.cpp
+++ b/src/message/MessageDecoder.cpp
@@ -16,19 +16,15 @@
  */
 #include "MessageDecoder.h"
 
-#include <cstring>  // std::memcpy
-
 #include <algorithm>  // std::move
 #include <sstream>    // std::stringstream
 
 #ifndef WIN32
-#include <arpa/inet.h>   // htons, htonl
 #include <netinet/in.h>  // struct sockaddr, sockaddr_in, sockaddr_in6
 #endif
 
 #include "ByteOrder.h"
 #include "Logging.h"
-#include "MemoryOutputStream.h"
 #include "MessageExtImpl.h"
 #include "MessageAccessor.h"
 #include "MessageSysFlag.h"
@@ -47,160 +43,155 @@ int MessageDecoder::MessagePhysicOffsetPostion = 28;
 int MessageDecoder::MessageStoreTimestampPostion = 56;
 
 std::string MessageDecoder::createMessageId(const struct sockaddr* sa, int64_t offset) {
-  MemoryOutputStream mos(sa->sa_family == AF_INET ? 16 : 28);
+  int msgIDLength = sa->sa_family == AF_INET ? 16 : 28;
+  std::unique_ptr<ByteBuffer> byteBuffer(ByteBuffer::allocate(msgIDLength));
   if (sa->sa_family == AF_INET) {
-    const struct sockaddr_in* sin = (struct sockaddr_in*)sa;
-    mos.write(&sin->sin_addr.s_addr, 4);
-    mos.writeRepeatedByte(0, 2);
-    mos.write(&sin->sin_port, 2);
-    mos.writeInt64BigEndian(offset);
+    struct sockaddr_in* sin = (struct sockaddr_in*)sa;
+    byteBuffer->put(ByteArray((char*)&sin->sin_addr, 4));
+    byteBuffer->putInt(ByteOrderUtil::NorminalBigEndian(sin->sin_port));
   } else {
-    const struct sockaddr_in6* sin6 = (struct sockaddr_in6*)sa;
-    mos.write(&sin6->sin6_addr, 16);
-    mos.writeRepeatedByte(0, 2);
-    mos.write(&sin6->sin6_port, 2);
-    mos.writeInt64BigEndian(offset);
+    struct sockaddr_in6* sin6 = (struct sockaddr_in6*)sa;
+    byteBuffer->put(ByteArray((char*)&sin6->sin6_addr, 16));
+    byteBuffer->putInt(ByteOrderUtil::NorminalBigEndian(sin6->sin6_port));
   }
-
-  const char* bytes = static_cast<const char*>(mos.getData());
-  int len = mos.getDataSize();
-
-  return UtilAll::bytes2string(bytes, len);
+  byteBuffer->putLong(offset);
+  byteBuffer->flip();
+  return UtilAll::bytes2string(byteBuffer->array(), msgIDLength);
 }
 
 MessageId MessageDecoder::decodeMessageId(const std::string& msgId) {
   size_t ip_length = msgId.length() == 32 ? 4 * 2 : 16 * 2;
 
+  ByteArray byteArray(ip_length / 2);
   std::string ip = msgId.substr(0, ip_length);
+  UtilAll::string2bytes(byteArray.array(), ip);
+
   std::string port = msgId.substr(ip_length, 8);
-  std::string offset = msgId.substr(ip_length + 8);
+  // uint32_t portInt = ByteOrderUtil::NorminalBigEndian<uint32_t>(std::stoul(port, nullptr, 16));
+  uint32_t portInt = std::stoul(port, nullptr, 16);
+
+  auto* sin = ipPort2SocketAddress(byteArray, portInt);
 
-  uint16_t portInt = (uint16_t)std::stoul(port, nullptr, 16);
+  std::string offset = msgId.substr(ip_length + 8);
+  // uint64_t offsetInt = ByteOrderUtil::NorminalBigEndian<uint64_t>(std::stoull(offset, nullptr, 16));
   uint64_t offsetInt = std::stoull(offset, nullptr, 16);
 
-  if (ip_length == 32) {
-    int32_t ipInt = std::stoul(ip, nullptr, 16);
-    struct sockaddr_in sin;
-    sin.sin_family = AF_INET;
-    sin.sin_port = htons(portInt);
-    sin.sin_addr.s_addr = htonl(ipInt);
-    return MessageId((struct sockaddr*)&sin, offsetInt);
-  } else {
-    struct sockaddr_in6 sin6;
-    sin6.sin6_family = AF_INET6;
-    sin6.sin6_port = htons(portInt);
-    UtilAll::string2bytes((char*)&sin6.sin6_addr, ip);
-    return MessageId((struct sockaddr*)&sin6, offsetInt);
-  }
+  return MessageId(sin, offsetInt);
 }
 
-MessageExtPtr MessageDecoder::clientDecode(MemoryInputStream& byteBuffer, bool readBody) {
+MessageExtPtr MessageDecoder::clientDecode(ByteBuffer& byteBuffer, bool readBody) {
   return decode(byteBuffer, readBody, true, true);
 }
 
-MessageExtPtr MessageDecoder::decode(MemoryInputStream& byteBuffer, bool readBody) {
+MessageExtPtr MessageDecoder::decode(ByteBuffer& byteBuffer) {
+  return decode(byteBuffer, true);
+}
+
+MessageExtPtr MessageDecoder::decode(ByteBuffer& byteBuffer, bool readBody) {
   return decode(byteBuffer, readBody, true, false);
 }
 
-MessageExtPtr MessageDecoder::decode(MemoryInputStream& byteBuffer, bool readBody, bool deCompressBody, bool isClient) {
+MessageExtPtr MessageDecoder::decode(ByteBuffer& byteBuffer, bool readBody, bool deCompressBody, bool isClient) {
   auto msgExt = isClient ? std::make_shared<MessageClientExtImpl>() : std::make_shared<MessageExtImpl>();
 
   // 1 TOTALSIZE
-  int32_t storeSize = byteBuffer.readIntBigEndian();
+  int32_t storeSize = byteBuffer.getInt();
   msgExt->setStoreSize(storeSize);
 
   // 2 MAGICCODE sizeof(int)
-  byteBuffer.skipNextBytes(sizeof(int));
+  byteBuffer.getInt();
 
   // 3 BODYCRC
-  int32_t bodyCRC = byteBuffer.readIntBigEndian();
+  int32_t bodyCRC = byteBuffer.getInt();
   msgExt->setBodyCRC(bodyCRC);
 
   // 4 QUEUEID
-  int32_t queueId = byteBuffer.readIntBigEndian();
+  int32_t queueId = byteBuffer.getInt();
   msgExt->setQueueId(queueId);
 
   // 5 FLAG
-  int32_t flag = byteBuffer.readIntBigEndian();
+  int32_t flag = byteBuffer.getInt();
   msgExt->setFlag(flag);
 
   // 6 QUEUEOFFSET
-  int64_t queueOffset = byteBuffer.readInt64BigEndian();
+  int64_t queueOffset = byteBuffer.getLong();
   msgExt->setQueueOffset(queueOffset);
 
   // 7 PHYSICALOFFSET
-  int64_t physicOffset = byteBuffer.readInt64BigEndian();
+  int64_t physicOffset = byteBuffer.getLong();
   msgExt->setCommitLogOffset(physicOffset);
 
   // 8 SYSFLAG
-  int32_t sysFlag = byteBuffer.readIntBigEndian();
+  int32_t sysFlag = byteBuffer.getInt();
   msgExt->setSysFlag(sysFlag);
 
   // 9 BORNTIMESTAMP
-  int64_t bornTimeStamp = byteBuffer.readInt64BigEndian();
+  int64_t bornTimeStamp = byteBuffer.getLong();
   msgExt->setBornTimestamp(bornTimeStamp);
 
   // 10 BORNHOST
-  int32_t bornHost = byteBuffer.readIntBigEndian();
-  int32_t bornPort = byteBuffer.readIntBigEndian();
+  int bornhostIPLength = (sysFlag & MessageSysFlag::BORNHOST_V6_FLAG) == 0 ? 4 : 16;
+  ByteArray bornHost(bornhostIPLength);
+  byteBuffer.get(bornHost, 0, bornhostIPLength);
+  int32_t bornPort = byteBuffer.getInt();
   msgExt->setBornHost(ipPort2SocketAddress(bornHost, bornPort));
 
   // 11 STORETIMESTAMP
-  int64_t storeTimestamp = byteBuffer.readInt64BigEndian();
+  int64_t storeTimestamp = byteBuffer.getLong();
   msgExt->setStoreTimestamp(storeTimestamp);
 
   // 12 STOREHOST
-  int32_t storeHost = byteBuffer.readIntBigEndian();
-  int32_t storePort = byteBuffer.readIntBigEndian();
+  int storehostIPLength = (sysFlag & MessageSysFlag::STOREHOST_V6_FLAG) == 0 ? 4 : 16;
+  ByteArray storeHost(bornhostIPLength);
+  byteBuffer.get(storeHost, 0, storehostIPLength);
+  int32_t storePort = byteBuffer.getInt();
   msgExt->setStoreHost(ipPort2SocketAddress(storeHost, storePort));
 
   // 13 RECONSUMETIMES
-  int32_t reconsumeTimes = byteBuffer.readIntBigEndian();
+  int32_t reconsumeTimes = byteBuffer.getInt();
   msgExt->setReconsumeTimes(reconsumeTimes);
 
   // 14 Prepared Transaction Offset
-  int64_t preparedTransactionOffset = byteBuffer.readInt64BigEndian();
+  int64_t preparedTransactionOffset = byteBuffer.getLong();
   msgExt->setPreparedTransactionOffset(preparedTransactionOffset);
 
   // 15 BODY
   int uncompress_failed = false;
-  int32_t bodyLen = byteBuffer.readIntBigEndian();
+  int32_t bodyLen = byteBuffer.getInt();
   if (bodyLen > 0) {
     if (readBody) {
-      MemoryPool block;
-      byteBuffer.readIntoMemoryBlock(block, bodyLen);
+      ByteArray body(byteBuffer.array() + byteBuffer.arrayOffset() + byteBuffer.position(), bodyLen);
+      byteBuffer.position(byteBuffer.position() + bodyLen);
 
       // decompress body
-      if (deCompressBody && (sysFlag & MessageSysFlag::CompressedFlag) == MessageSysFlag::CompressedFlag) {
-        std::string outbody;
-        if (UtilAll::inflate(block.getData(), block.getSize(), outbody)) {
-          msgExt->setBody(std::move(outbody));
+      if (deCompressBody && (sysFlag & MessageSysFlag::COMPRESSED_FLAG) == MessageSysFlag::COMPRESSED_FLAG) {
+        std::string origin_body;
+        if (UtilAll::inflate(body, origin_body)) {
+          msgExt->setBody(std::move(origin_body));
         } else {
           uncompress_failed = true;
         }
       } else {
-        msgExt->setBody(block.getData(), block.getSize());
+        // c_str safety
+        msgExt->setBody(std::string(body.array(), body.size()));
       }
     } else {
-      byteBuffer.skipNextBytes(bodyLen);
+      byteBuffer.position(byteBuffer.position() + bodyLen);
     }
   }
 
   // 16 TOPIC
-  int8_t topicLen = byteBuffer.readByte();
-  MemoryPool block;
-  byteBuffer.readIntoMemoryBlock(block, topicLen);
-  const char* const pTopic = static_cast<const char*>(block.getData());
-  topicLen = block.getSize();
-  msgExt->setTopic(pTopic, topicLen);
+  int8_t topicLen = byteBuffer.get();
+  ByteArray topic(topicLen);
+  byteBuffer.get(topic);
+  msgExt->setTopic(topic.array(), topic.size());
 
   // 17 properties
-  int16_t propertiesLen = byteBuffer.readShortBigEndian();
+  int16_t propertiesLen = byteBuffer.getShort();
   if (propertiesLen > 0) {
-    MemoryPool block;
-    byteBuffer.readIntoMemoryBlock(block, propertiesLen);
-    std::string propertiesString(block.getData(), block.getSize());
-
+    ByteArray properties(propertiesLen);
+    byteBuffer.get(properties);
+    std::string propertiesString(properties.array(), properties.size());
     std::map<std::string, std::string> propertiesMap = string2messageProperties(propertiesString);
     MessageAccessor::setProperties(*msgExt, std::move(propertiesMap));
   }
@@ -216,28 +207,18 @@ MessageExtPtr MessageDecoder::decode(MemoryInputStream& byteBuffer, bool readBod
   return msgExt;
 }
 
-MessageExtPtr MessageDecoder::decode(MemoryBlock& mem) {
-  return decode(mem, true);
-}
-
-MessageExtPtr MessageDecoder::decode(MemoryBlock& mem, bool readBody) {
-  MemoryInputStream rawInput(mem, true);
-  return decode(rawInput, readBody);
-}
-
-std::vector<MessageExtPtr> MessageDecoder::decodes(MemoryBlock& mem) {
-  return decodes(mem, true);
+std::vector<MessageExtPtr> MessageDecoder::decodes(ByteBuffer& byteBuffer) {
+  return decodes(byteBuffer, true);
 }
 
-std::vector<MessageExtPtr> MessageDecoder::decodes(MemoryBlock& mem, bool readBody) {
+std::vector<MessageExtPtr> MessageDecoder::decodes(ByteBuffer& byteBuffer, bool readBody) {
   std::vector<MessageExtPtr> msgExts;
-  MemoryInputStream rawInput(mem, true);
-  while (rawInput.getNumBytesRemaining() > 0) {
-    auto msgExt = clientDecode(rawInput, readBody);
+  while (byteBuffer.hasRemaining()) {
+    auto msgExt = clientDecode(byteBuffer, readBody);
     if (nullptr == msgExt) {
       break;
     }
-    msgExts.emplace_back(msgExt);
+    msgExts.emplace_back(std::move(msgExt));
   }
   return msgExts;
 }
@@ -280,10 +261,10 @@ std::map<std::string, std::string> MessageDecoder::string2messageProperties(cons
 }
 
 std::string MessageDecoder::encodeMessage(Message& message) {
-  const std::string& body = message.getBody();
-  uint32_t bodyLen = body.length();
+  const auto& body = message.getBody();
+  uint32_t bodyLen = body.size();
   std::string properties = MessageDecoder::messageProperties2String(message.getProperties());
-  uint16_t propertiesLength = (int16_t)properties.length();
+  uint16_t propertiesLength = (int16_t)properties.size();
   uint32_t storeSize = 4                        // 1 TOTALSIZE
                        + 4                      // 2 MAGICCODE
                        + 4                      // 3 BODYCRC
@@ -295,31 +276,31 @@ std::string MessageDecoder::encodeMessage(Message& message) {
   std::string encodeMsg;
 
   // 1 TOTALSIZE
-  uint32_t storeSize_net = ByteOrder::swapIfLittleEndian(storeSize);
+  uint32_t storeSize_net = ByteOrderUtil::NorminalBigEndian(storeSize);
   encodeMsg.append((char*)&storeSize_net, sizeof(uint32_t));
 
   // 2 MAGICCODE
   uint32_t magicCode = 0;
-  uint32_t magicCode_net = ByteOrder::swapIfLittleEndian(magicCode);
+  uint32_t magicCode_net = ByteOrderUtil::NorminalBigEndian(magicCode);
   encodeMsg.append((char*)&magicCode_net, sizeof(uint32_t));
 
   // 3 BODYCRC
   uint32_t bodyCrc = 0;
-  uint32_t bodyCrc_net = ByteOrder::swapIfLittleEndian(bodyCrc);
+  uint32_t bodyCrc_net = ByteOrderUtil::NorminalBigEndian(bodyCrc);
   encodeMsg.append((char*)&bodyCrc_net, sizeof(uint32_t));
 
   // 4 FLAG
   uint32_t flag = message.getFlag();
-  uint32_t flag_net = ByteOrder::swapIfLittleEndian(flag);
+  uint32_t flag_net = ByteOrderUtil::NorminalBigEndian(flag);
   encodeMsg.append((char*)&flag_net, sizeof(uint32_t));
 
   // 5 BODY
-  uint32_t bodyLen_net = ByteOrder::swapIfLittleEndian(bodyLen);
+  uint32_t bodyLen_net = ByteOrderUtil::NorminalBigEndian(bodyLen);
   encodeMsg.append((char*)&bodyLen_net, sizeof(uint32_t));
-  encodeMsg.append(body);
+  encodeMsg.append(body.data(), body.size());
 
   // 6 properties
-  uint16_t propertiesLength_net = ByteOrder::swapIfLittleEndian(propertiesLength);
+  uint16_t propertiesLength_net = ByteOrderUtil::NorminalBigEndian(propertiesLength);
   encodeMsg.append((char*)&propertiesLength_net, sizeof(uint16_t));
   encodeMsg.append(std::move(properties));
 
diff --git a/src/message/MessageDecoder.h b/src/message/MessageDecoder.h
index 2bc935a..1dd259c 100644
--- a/src/message/MessageDecoder.h
+++ b/src/message/MessageDecoder.h
@@ -17,10 +17,10 @@
 #ifndef ROCKETMQ_MESSAGE_MESSAGEDECODER_H_
 #define ROCKETMQ_MESSAGE_MESSAGEDECODER_H_
 
+#include "ByteBuffer.hpp"
 #include "MQClientException.h"
 #include "MQMessageExt.h"
 #include "MessageId.h"
-#include "MemoryInputStream.h"
 
 namespace rocketmq {
 
@@ -29,11 +29,13 @@ class MessageDecoder {
   static std::string createMessageId(const struct sockaddr* sa, int64_t offset);
   static MessageId decodeMessageId(const std::string& msgId);
 
-  static MessageExtPtr decode(MemoryBlock& mem);
-  static MessageExtPtr decode(MemoryBlock& mem, bool readBody);
+  static MessageExtPtr clientDecode(ByteBuffer& byteBuffer, bool readBody);
+  static MessageExtPtr decode(ByteBuffer& byteBuffer);
+  static MessageExtPtr decode(ByteBuffer& byteBuffer, bool readBody);
+  static MessageExtPtr decode(ByteBuffer& byteBuffer, bool readBody, bool deCompressBody, bool isClient);
 
-  static std::vector<MessageExtPtr> decodes(MemoryBlock& mem);
-  static std::vector<MessageExtPtr> decodes(MemoryBlock& mem, bool readBody);
+  static std::vector<MessageExtPtr> decodes(ByteBuffer& byteBuffer);
+  static std::vector<MessageExtPtr> decodes(ByteBuffer& byteBuffer, bool readBody);
 
   static std::string messageProperties2String(const std::map<std::string, std::string>& properties);
   static std::map<std::string, std::string> string2messageProperties(const std::string& properties);
@@ -41,12 +43,6 @@ class MessageDecoder {
   static std::string encodeMessage(Message& message);
   static std::string encodeMessages(std::vector<MQMessage>& msgs);
 
- private:
-  static MessageExtPtr clientDecode(MemoryInputStream& byteBuffer, bool readBody);
-
-  static MessageExtPtr decode(MemoryInputStream& byteBuffer, bool readBody);
-  static MessageExtPtr decode(MemoryInputStream& byteBuffer, bool readBody, bool deCompressBody, bool isClient);
-
  public:
   static const char NAME_VALUE_SEPARATOR;
   static const char PROPERTY_SEPARATOR;
diff --git a/src/message/MessageExtImpl.cpp b/src/message/MessageExtImpl.cpp
index ea36b35..94b38c4 100644
--- a/src/message/MessageExtImpl.cpp
+++ b/src/message/MessageExtImpl.cpp
@@ -60,7 +60,7 @@ MessageExtImpl::~MessageExtImpl() {
 }
 
 TopicFilterType MessageExtImpl::parseTopicFilterType(int32_t sysFlag) {
-  if ((sysFlag & MessageSysFlag::MultiTagsFlag) == MessageSysFlag::MultiTagsFlag) {
+  if ((sysFlag & MessageSysFlag::MULTI_TAGS_FLAG) == MessageSysFlag::MULTI_TAGS_FLAG) {
     return MULTI_TAG;
   }
   return SINGLE_TAG;
diff --git a/src/message/MessageImpl.cpp b/src/message/MessageImpl.cpp
index f3f9def..1738952 100644
--- a/src/message/MessageImpl.cpp
+++ b/src/message/MessageImpl.cpp
@@ -144,11 +144,6 @@ const std::string& MessageImpl::getBody() const {
   return body_;
 }
 
-void MessageImpl::setBody(const char* body, int len) {
-  body_.clear();
-  body_.append(body, len);
-}
-
 void MessageImpl::setBody(const std::string& body) {
   body_ = body;
 }
diff --git a/src/message/MessageImpl.h b/src/message/MessageImpl.h
index bc4424f..de83e5e 100644
--- a/src/message/MessageImpl.h
+++ b/src/message/MessageImpl.h
@@ -65,7 +65,6 @@ class MessageImpl : public noncopyable,     // base
   void setFlag(int32_t flag) override;
 
   const std::string& getBody() const override;
-  void setBody(const char* body, int len) override;
   void setBody(const std::string& body) override;
   void setBody(std::string&& body) override;
 
diff --git a/src/message/MessageUtil.cpp b/src/message/MessageUtil.cpp
index dc7e0a0..21d2510 100644
--- a/src/message/MessageUtil.cpp
+++ b/src/message/MessageUtil.cpp
@@ -16,6 +16,7 @@
  */
 #include "MessageUtil.h"
 
+#include "ByteArray.h"
 #include "ClientErrorCode.h"
 #include "MessageImpl.h"
 #include "MessageAccessor.h"
diff --git a/src/producer/DefaultMQProducer.cpp b/src/producer/DefaultMQProducer.cpp
index bf1c7ab..8996470 100644
--- a/src/producer/DefaultMQProducer.cpp
+++ b/src/producer/DefaultMQProducer.cpp
@@ -30,7 +30,7 @@ DefaultMQProducer::DefaultMQProducer(const std::string& groupname, RPCHookPtr rp
 DefaultMQProducer::DefaultMQProducer(const std::string& groupname,
                                      RPCHookPtr rpcHook,
                                      DefaultMQProducerConfigPtr producerConfig)
-    : DefaultMQProducerConfigProxy(producerConfig), m_producerDelegate(nullptr) {
+    : DefaultMQProducerConfigProxy(producerConfig), producer_impl_(nullptr) {
   // set default group name
   if (groupname.empty()) {
     setGroupName(DEFAULT_PRODUCER_GROUP);
@@ -38,75 +38,75 @@ DefaultMQProducer::DefaultMQProducer(const std::string& groupname,
     setGroupName(groupname);
   }
 
-  m_producerDelegate = DefaultMQProducerImpl::create(getRealConfig(), rpcHook);
+  producer_impl_ = DefaultMQProducerImpl::create(getRealConfig(), rpcHook);
 }
 
 DefaultMQProducer::~DefaultMQProducer() = default;
 
 void DefaultMQProducer::start() {
-  m_producerDelegate->start();
+  producer_impl_->start();
 }
 
 void DefaultMQProducer::shutdown() {
-  m_producerDelegate->shutdown();
+  producer_impl_->shutdown();
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg) {
-  return m_producerDelegate->send(msg);
+  return producer_impl_->send(msg);
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg, long timeout) {
-  return m_producerDelegate->send(msg, timeout);
+  return producer_impl_->send(msg, timeout);
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq) {
-  return m_producerDelegate->send(msg, mq);
+  return producer_impl_->send(msg, mq);
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq, long timeout) {
-  return m_producerDelegate->send(msg, mq, timeout);
+  return producer_impl_->send(msg, mq, timeout);
 }
 
 void DefaultMQProducer::send(MQMessage& msg, SendCallback* sendCallback) noexcept {
-  m_producerDelegate->send(msg, sendCallback, getSendMsgTimeout());
+  producer_impl_->send(msg, sendCallback, getSendMsgTimeout());
 }
 
 void DefaultMQProducer::send(MQMessage& msg, SendCallback* sendCallback, long timeout) noexcept {
-  m_producerDelegate->send(msg, sendCallback, timeout);
+  producer_impl_->send(msg, sendCallback, timeout);
 }
 
 void DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq, SendCallback* sendCallback) noexcept {
-  return m_producerDelegate->send(msg, mq, sendCallback);
+  return producer_impl_->send(msg, mq, sendCallback);
 }
 
 void DefaultMQProducer::send(MQMessage& msg,
                              const MQMessageQueue& mq,
                              SendCallback* sendCallback,
                              long timeout) noexcept {
-  m_producerDelegate->send(msg, mq, sendCallback, timeout);
+  producer_impl_->send(msg, mq, sendCallback, timeout);
 }
 
 void DefaultMQProducer::sendOneway(MQMessage& msg) {
-  m_producerDelegate->sendOneway(msg);
+  producer_impl_->sendOneway(msg);
 }
 
 void DefaultMQProducer::sendOneway(MQMessage& msg, const MQMessageQueue& mq) {
-  m_producerDelegate->sendOneway(msg, mq);
+  producer_impl_->sendOneway(msg, mq);
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* selector, void* arg) {
-  return m_producerDelegate->send(msg, selector, arg);
+  return producer_impl_->send(msg, selector, arg);
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* selector, void* arg, long timeout) {
-  return m_producerDelegate->send(msg, selector, arg, timeout);
+  return producer_impl_->send(msg, selector, arg, timeout);
 }
 
 void DefaultMQProducer::send(MQMessage& msg,
                              MessageQueueSelector* selector,
                              void* arg,
                              SendCallback* sendCallback) noexcept {
-  return m_producerDelegate->send(msg, selector, arg, sendCallback);
+  return producer_impl_->send(msg, selector, arg, sendCallback);
 }
 
 void DefaultMQProducer::send(MQMessage& msg,
@@ -114,11 +114,11 @@ void DefaultMQProducer::send(MQMessage& msg,
                              void* arg,
                              SendCallback* sendCallback,
                              long timeout) noexcept {
-  m_producerDelegate->send(msg, selector, arg, sendCallback, timeout);
+  producer_impl_->send(msg, selector, arg, sendCallback, timeout);
 }
 
 void DefaultMQProducer::sendOneway(MQMessage& msg, MessageQueueSelector* selector, void* arg) {
-  m_producerDelegate->sendOneway(msg, selector, arg);
+  producer_impl_->sendOneway(msg, selector, arg);
 }
 
 TransactionSendResult DefaultMQProducer::sendMessageInTransaction(MQMessage& msg, void* arg) {
@@ -127,36 +127,35 @@ TransactionSendResult DefaultMQProducer::sendMessageInTransaction(MQMessage& msg
 }
 
 SendResult DefaultMQProducer::send(std::vector<MQMessage>& msgs) {
-  return m_producerDelegate->send(msgs);
+  return producer_impl_->send(msgs);
 }
 
 SendResult DefaultMQProducer::send(std::vector<MQMessage>& msgs, long timeout) {
-  return m_producerDelegate->send(msgs, timeout);
+  return producer_impl_->send(msgs, timeout);
 }
 
 SendResult DefaultMQProducer::send(std::vector<MQMessage>& msgs, const MQMessageQueue& mq) {
-  return m_producerDelegate->send(msgs, mq);
+  return producer_impl_->send(msgs, mq);
 }
 
 SendResult DefaultMQProducer::send(std::vector<MQMessage>& msgs, const MQMessageQueue& mq, long timeout) {
-  return m_producerDelegate->send(msgs, mq, timeout);
+  return producer_impl_->send(msgs, mq, timeout);
 }
 
 MQMessage DefaultMQProducer::request(MQMessage& msg, long timeout) {
-  return m_producerDelegate->request(msg, timeout);
+  return producer_impl_->request(msg, timeout);
 }
 
 bool DefaultMQProducer::isSendLatencyFaultEnable() const {
-  return std::dynamic_pointer_cast<DefaultMQProducerImpl>(m_producerDelegate)->isSendLatencyFaultEnable();
+  return std::dynamic_pointer_cast<DefaultMQProducerImpl>(producer_impl_)->isSendLatencyFaultEnable();
 }
 
 void DefaultMQProducer::setSendLatencyFaultEnable(bool sendLatencyFaultEnable) {
-  std::dynamic_pointer_cast<DefaultMQProducerImpl>(m_producerDelegate)
-      ->setSendLatencyFaultEnable(sendLatencyFaultEnable);
+  std::dynamic_pointer_cast<DefaultMQProducerImpl>(producer_impl_)->setSendLatencyFaultEnable(sendLatencyFaultEnable);
 }
 
 void DefaultMQProducer::setRPCHook(RPCHookPtr rpcHook) {
-  std::dynamic_pointer_cast<DefaultMQProducerImpl>(m_producerDelegate)->setRPCHook(rpcHook);
+  std::dynamic_pointer_cast<DefaultMQProducerImpl>(producer_impl_)->setRPCHook(rpcHook);
 }
 
 }  // namespace rocketmq
diff --git a/src/producer/DefaultMQProducerImpl.cpp b/src/producer/DefaultMQProducerImpl.cpp
index 4fea984..54d16fc 100644
--- a/src/producer/DefaultMQProducerImpl.cpp
+++ b/src/producer/DefaultMQProducerImpl.cpp
@@ -528,13 +528,13 @@ SendResult* DefaultMQProducerImpl::sendKernelImpl(MessagePtr msg,
       int sysFlag = 0;
       bool msgBodyCompressed = false;
       if (tryToCompressMessage(*msg)) {
-        sysFlag |= MessageSysFlag::CompressedFlag;
+        sysFlag |= MessageSysFlag::COMPRESSED_FLAG;
         msgBodyCompressed = true;
       }
 
       const auto& tranMsg = msg->getProperty(MQMessageConst::PROPERTY_TRANSACTION_PREPARED);
       if (UtilAll::stob(tranMsg)) {
-        sysFlag |= MessageSysFlag::TransactionPreparedType;
+        sysFlag |= MessageSysFlag::TRANSACTION_PREPARED_TYPE;
       }
 
       // TOOD: send message hook
@@ -747,14 +747,14 @@ void DefaultMQProducerImpl::checkTransactionStateImpl(const std::string& addr,
   endHeader->transactionId = transactionId;
   switch (localTransactionState) {
     case COMMIT_MESSAGE:
-      endHeader->commitOrRollback = MessageSysFlag::TransactionCommitType;
+      endHeader->commitOrRollback = MessageSysFlag::TRANSACTION_COMMIT_TYPE;
       break;
     case ROLLBACK_MESSAGE:
-      endHeader->commitOrRollback = MessageSysFlag::TransactionRollbackType;
+      endHeader->commitOrRollback = MessageSysFlag::TRANSACTION_ROLLBACK_TYPE;
       LOG_WARN_NEW("when broker check, client rollback this transaction, {}", endHeader->toString());
       break;
     case UNKNOWN:
-      endHeader->commitOrRollback = MessageSysFlag::TransactionNotType;
+      endHeader->commitOrRollback = MessageSysFlag::TRANSACTION_NOT_TYPE;
       LOG_WARN_NEW("when broker check, client does not know this transaction state, {}", endHeader->toString());
       break;
     default:
@@ -785,13 +785,13 @@ void DefaultMQProducerImpl::endTransaction(SendResult& sendResult,
   requestHeader->commitLogOffset = id.getOffset();
   switch (localTransactionState) {
     case COMMIT_MESSAGE:
-      requestHeader->commitOrRollback = MessageSysFlag::TransactionCommitType;
+      requestHeader->commitOrRollback = MessageSysFlag::TRANSACTION_COMMIT_TYPE;
       break;
     case ROLLBACK_MESSAGE:
-      requestHeader->commitOrRollback = MessageSysFlag::TransactionRollbackType;
+      requestHeader->commitOrRollback = MessageSysFlag::TRANSACTION_ROLLBACK_TYPE;
       break;
     case UNKNOWN:
-      requestHeader->commitOrRollback = MessageSysFlag::TransactionNotType;
+      requestHeader->commitOrRollback = MessageSysFlag::TRANSACTION_NOT_TYPE;
       break;
     default:
       break;
@@ -819,10 +819,10 @@ bool DefaultMQProducerImpl::tryToCompressMessage(Message& msg) {
   }
 
   const auto& body = msg.getBody();
-  if (body.length() >= m_producerConfig->getCompressMsgBodyOverHowmuch()) {
-    std::string outBody;
-    if (UtilAll::deflate(body, outBody, m_producerConfig->getCompressLevel())) {
-      msg.setBody(std::move(outBody));
+  if (body.size() >= m_producerConfig->getCompressMsgBodyOverHowmuch()) {
+    std::string out_body;
+    if (UtilAll::deflate(body, out_body, m_producerConfig->getCompressLevel())) {
+      msg.setBody(std::move(out_body));
       msg.putProperty(MQMessageConst::PROPERTY_ALREADY_COMPRESSED_FLAG, "true");
       return true;
     }
diff --git a/src/producer/TransactionMQProducer.cpp b/src/producer/TransactionMQProducer.cpp
index cd2e6a7..cae9240 100644
--- a/src/producer/TransactionMQProducer.cpp
+++ b/src/producer/TransactionMQProducer.cpp
@@ -45,17 +45,17 @@ void TransactionMQProducer::setTransactionListener(TransactionListener* transact
 }
 
 void TransactionMQProducer::start() {
-  std::dynamic_pointer_cast<DefaultMQProducerImpl>(m_producerDelegate)->initTransactionEnv();
+  std::dynamic_pointer_cast<DefaultMQProducerImpl>(producer_impl_)->initTransactionEnv();
   DefaultMQProducer::start();
 }
 
 void TransactionMQProducer::shutdown() {
   DefaultMQProducer::shutdown();
-  std::dynamic_pointer_cast<DefaultMQProducerImpl>(m_producerDelegate)->destroyTransactionEnv();
+  std::dynamic_pointer_cast<DefaultMQProducerImpl>(producer_impl_)->destroyTransactionEnv();
 }
 
 TransactionSendResult TransactionMQProducer::sendMessageInTransaction(MQMessage& msg, void* arg) {
-  return m_producerDelegate->sendMessageInTransaction(msg, arg);
+  return producer_impl_->sendMessageInTransaction(msg, arg);
 }
 
 }  // namespace rocketmq
diff --git a/src/protocol/RemotingCommand.cpp b/src/protocol/RemotingCommand.cpp
index 413edbc..2541523 100644
--- a/src/protocol/RemotingCommand.cpp
+++ b/src/protocol/RemotingCommand.cpp
@@ -16,10 +16,14 @@
  */
 #include "RemotingCommand.h"
 
-#include <atomic>
-#include <limits>
+#include <cstring>  // std::memcpy
+
+#include <algorithm>  // std::move
+#include <atomic>     // std::atomic
+#include <limits>     // std::numeric_limits
 
 #include "ByteOrder.h"
+#include "ByteBuffer.hpp"
 #include "Logging.h"
 #include "MQVersion.h"
 #include "RemotingSerializable.h"
@@ -54,92 +58,104 @@ RemotingCommand::RemotingCommand(int32_t code,
                                  int32_t flag,
                                  const std::string& remark,
                                  CommandCustomHeader* customHeader)
-    : m_code(code),
-      m_language(language),
-      m_version(version),
-      m_opaque(opaque),
-      m_flag(flag),
-      m_remark(remark),
-      m_customHeader(customHeader) {}
+    : code_(code),
+      language_(language),
+      version_(version),
+      opaque_(opaque),
+      flag_(flag),
+      remark_(remark),
+      custom_header_(customHeader) {}
 
 RemotingCommand::RemotingCommand(RemotingCommand&& command) {
-  m_code = command.m_code;
-  m_language = std::move(command.m_language);
-  m_version = command.m_version;
-  m_opaque = command.m_opaque;
-  m_flag = command.m_flag;
-  m_remark = std::move(command.m_remark);
-  m_extFields = std::move(command.m_extFields);
-  m_customHeader = std::move(command.m_customHeader);
-  m_body = std::move(command.m_body);
+  code_ = command.code_;
+  language_ = std::move(command.language_);
+  version_ = command.version_;
+  opaque_ = command.opaque_;
+  flag_ = command.flag_;
+  remark_ = std::move(command.remark_);
+  ext_fields_ = std::move(command.ext_fields_);
+  custom_header_ = std::move(command.custom_header_);
+  body_ = std::move(command.body_);
 }
 
 RemotingCommand::~RemotingCommand() = default;
 
-MemoryBlockPtr RemotingCommand::encode() const {
+ByteArrayRef RemotingCommand::encode() const {
   Json::Value root;
-  root["code"] = m_code;
-  root["language"] = m_language;
-  root["version"] = m_version;
-  root["opaque"] = m_opaque;
-  root["flag"] = m_flag;
-  root["remark"] = m_remark;
-
-  Json::Value extJson;
-  for (const auto& it : m_extFields) {
-    extJson[it.first] = it.second;
+  root["code"] = code_;
+  root["language"] = language_;
+  root["version"] = version_;
+  root["opaque"] = opaque_;
+  root["flag"] = flag_;
+  root["remark"] = remark_;
+
+  Json::Value ext_fields;
+  for (const auto& it : ext_fields_) {
+    ext_fields[it.first] = it.second;
   }
-  if (m_customHeader != nullptr) {
+  if (custom_header_ != nullptr) {
     // write customHeader to extFields
-    m_customHeader->Encode(extJson);
+    custom_header_->Encode(ext_fields);
   }
-  root["extFields"] = extJson;
+  root["extFields"] = ext_fields;
 
+  // serialize header
   std::string header = RemotingSerializable::toJson(root);
 
-  uint32_t headerLen = header.size();
-  uint32_t packageLen = 4 + headerLen;
-  if (m_body != nullptr) {
-    packageLen += m_body->getSize();
+  // 1> header length size
+  uint32_t length = 4;
+  // 2> header data length
+  length += header.size();
+  // 3> body data length
+  if (body_ != nullptr) {
+    length += body_->size();
   }
 
-  uint32_t messageHeader[2];
-  messageHeader[0] = ByteOrder::swapIfLittleEndian(packageLen);
-  messageHeader[1] = ByteOrder::swapIfLittleEndian(headerLen);
-
-  std::unique_ptr<MemoryPool> package(new MemoryPool(4 + packageLen));
-  package->copyFrom(messageHeader, 0, sizeof(messageHeader));
-  package->copyFrom(header.data(), sizeof(messageHeader), headerLen);
-  if (m_body != nullptr && m_body->getSize() > 0) {
-    package->copyFrom(m_body->getData(), sizeof(messageHeader) + headerLen, m_body->getSize());
+  std::unique_ptr<ByteBuffer> result(ByteBuffer::allocate(4 + length));
+
+  // length
+  result->putInt(length);
+  // header length
+  result->putInt((uint32_t)header.size());
+  // header data
+  result->put(ByteArray((char*)header.data(), header.size()));
+  // body data;
+  if (body_ != nullptr) {
+    result->put(*body_);
   }
 
-  return std::move(package);
+  // result->flip();
+
+  return result->byte_array();
+}
+
+static inline int32_t getHeaderLength(int32_t length) {
+  return length & 0x00FFFFFF;
 }
 
-RemotingCommand* RemotingCommand::Decode(MemoryBlockPtr2 package, bool havePackageLen) {
+static RemotingCommand* Decode(ByteBuffer& byteBuffer, bool hasPackageLength) {
   // decode package: [4 bytes(packageLength) +] 4 bytes(headerLength) + header + body
-  int packageLength = package->getSize();
-  uint32_t netHeaderLen;
-  const char* data = package->getData();
-
-  if (havePackageLen) {
-    data += 4;
-    packageLength -= 4;
-    package->copyTo(&netHeaderLen, 4, sizeof(netHeaderLen));
-  } else {
-    package->copyTo(&netHeaderLen, 0, sizeof(netHeaderLen));
+
+  int32_t length = byteBuffer.limit();
+  if (hasPackageLength) {
+    // skip package length
+    (void)byteBuffer.getInt();
+    length -= 4;
   }
-  int oriHeaderLen = ByteOrder::swapIfLittleEndian(netHeaderLen);
-  int headerLength = oriHeaderLen & 0xFFFFFF;
 
   // decode header
-  const char* begin = data + 4;
-  const char* end = data + 4 + headerLength;
+
+  int32_t oriHeaderLen = byteBuffer.getInt();
+  int32_t headerLength = getHeaderLength(oriHeaderLen);
+
+  // ByteArray headData(headerLength);
+  // byteBuffer.get(headerData);
+  ByteArray headerData(byteBuffer.array() + byteBuffer.arrayOffset() + byteBuffer.position(), headerLength);
+  byteBuffer.position(byteBuffer.position() + headerLength);
 
   Json::Value object;
   try {
-    object = RemotingSerializable::fromJson(begin, end);
+    object = RemotingSerializable::fromJson(headerData);
   } catch (std::exception& e) {
     LOG_WARN_NEW("parse json failed. {}", e.what());
     THROW_MQEXCEPTION(MQClientException, "conn't parse json", -1);
@@ -162,16 +178,21 @@ RemotingCommand* RemotingCommand::Decode(MemoryBlockPtr2 package, bool havePacka
     for (auto& name : extFields.getMemberNames()) {
       auto& value = extFields[name];
       if (value.isString()) {
-        cmd->m_extFields[name] = value.asString();
+        cmd->set_ext_field(name, value.asString());
       }
     }
   }
 
   // decode body
-  int bodyLength = packageLength - 4 - headerLength;
+
+  int32_t bodyLength = length - 4 - headerLength;
   if (bodyLength > 0) {
-    auto* body = new MemoryView(package, (havePackageLen ? 8 : 4) + headerLength);
-    cmd->setBody(body);
+    // ByteArrayRef bodyData = std::make_shared<ByteArray>(bodyLength);
+    // byteBuffer.get(*bodyData);
+    ByteArrayRef bodyData =
+        slice(byteBuffer.byte_array(), byteBuffer.arrayOffset() + byteBuffer.position(), bodyLength);
+    byteBuffer.position(byteBuffer.position() + bodyLength);
+    cmd->set_body(std::move(bodyData));
   }
 
   LOG_DEBUG_NEW("code:{}, language:{}, version:{}, opaque:{}, flag:{}, remark:{}, headLen:{}, bodyLen:{}", code,
@@ -180,85 +201,38 @@ RemotingCommand* RemotingCommand::Decode(MemoryBlockPtr2 package, bool havePacka
   return cmd.release();
 }
 
-int32_t RemotingCommand::getCode() const {
-  return m_code;
-}
-
-void RemotingCommand::setCode(int32_t code) {
-  m_code = code;
-}
-
-int32_t RemotingCommand::getVersion() const {
-  return m_version;
-}
-
-int32_t RemotingCommand::getOpaque() const {
-  return m_opaque;
-}
-
-void RemotingCommand::setOpaque(int32_t opaque) {
-  m_opaque = opaque;
-}
-
-int32_t RemotingCommand::getFlag() const {
-  return m_flag;
-}
-
-const std::string& RemotingCommand::getRemark() const {
-  return m_remark;
-}
-
-void RemotingCommand::setRemark(const std::string& mark) {
-  m_remark = mark;
+RemotingCommand* RemotingCommand::Decode(ByteArrayRef array, bool hasPackageLength) {
+  std::unique_ptr<ByteBuffer> byteBuffer(ByteBuffer::wrap(std::move(array)));
+  return rocketmq::Decode(*byteBuffer, hasPackageLength);
 }
 
 bool RemotingCommand::isResponseType() {
   int bits = 1 << RPC_TYPE;
-  return (m_flag & bits) == bits;
+  return (flag_ & bits) == bits;
 }
 
 void RemotingCommand::markResponseType() {
   int bits = 1 << RPC_TYPE;
-  m_flag |= bits;
+  flag_ |= bits;
 }
 
 bool RemotingCommand::isOnewayRPC() {
   int bits = 1 << RPC_ONEWAY;
-  return (m_flag & bits) == bits;
+  return (flag_ & bits) == bits;
 }
 
 void RemotingCommand::markOnewayRPC() {
   int bits = 1 << RPC_ONEWAY;
-  m_flag |= bits;
-}
-
-void RemotingCommand::addExtField(const std::string& key, const std::string& value) {
-  m_extFields[key] = value;
+  flag_ |= bits;
 }
 
 CommandCustomHeader* RemotingCommand::readCustomHeader() const {
-  return m_customHeader.get();
-}
-
-MemoryBlockPtr2 RemotingCommand::getBody() const {
-  return m_body;
-}
-
-void RemotingCommand::setBody(MemoryBlock* body) {
-  m_body.reset(body);
-}
-
-void RemotingCommand::setBody(MemoryBlockPtr2 body) {
-  m_body = body;
-}
-
-void RemotingCommand::setBody(const std::string& body) {
-  m_body.reset(new MemoryPool(body.data(), body.size()));
+  return custom_header_.get();
 }
 
 std::string RemotingCommand::toString() const {
   std::stringstream ss;
-  ss << "code:" << m_code << ", opaque:" << m_opaque << ", flag:" << m_flag << ", body.size:" << m_body->getSize();
+  ss << "code:" << code_ << ", opaque:" << opaque_ << ", flag:" << flag_ << ", body.size:" << body_->size();
   return ss.str();
 }
 
diff --git a/src/protocol/RemotingSerializable.cpp b/src/protocol/RemotingSerializable.cpp
index 96d04b5..e864926 100644
--- a/src/protocol/RemotingSerializable.cpp
+++ b/src/protocol/RemotingSerializable.cpp
@@ -71,9 +71,9 @@ Json::Value RemotingSerializable::fromJson(const std::string& json) {
   return fromJson(begin, end);
 }
 
-Json::Value RemotingSerializable::fromJson(const MemoryBlock& data) {
-  const char* begin = data.getData();
-  const char* end = begin + data.getSize();
+Json::Value RemotingSerializable::fromJson(const ByteArray& bytes) {
+  const char* begin = bytes.array();
+  const char* end = begin + bytes.size();
   return fromJson(begin, end);
 }
 
diff --git a/src/protocol/RemotingSerializable.h b/src/protocol/RemotingSerializable.h
index 08ed73b..e5a37d8 100644
--- a/src/protocol/RemotingSerializable.h
+++ b/src/protocol/RemotingSerializable.h
@@ -19,7 +19,7 @@
 
 #include <json/json.h>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 
 namespace rocketmq {
 
@@ -35,7 +35,7 @@ class RemotingSerializable {
 
   static Json::Value fromJson(std::istream& sin);
   static Json::Value fromJson(const std::string& json);
-  static Json::Value fromJson(const MemoryBlock& data);
+  static Json::Value fromJson(const ByteArray& bytes);
   static Json::Value fromJson(const char* begin, const char* end);
 
  private:
diff --git a/src/protocol/TopicList.h b/src/protocol/TopicList.h
index faa9bbb..450e6b2 100644
--- a/src/protocol/TopicList.h
+++ b/src/protocol/TopicList.h
@@ -17,19 +17,19 @@
 #ifndef __TOPIC_LIST_H__
 #define __TOPIC_LIST_H__
 
-#include <string>
-#include <vector>
+#include <string>  // std::string
+#include <vector>  // std::vector
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 
 namespace rocketmq {
 
 class TopicList {
  public:
-  static TopicList* Decode(MemoryBlock& mem) { return new TopicList(); }
+  static TopicList* Decode(const ByteArray& mem) { return new TopicList(); }
 
  private:
-  std::vector<std::string> m_topicList;
+  std::vector<std::string> topic_list_;
 };
 
 }  // namespace rocketmq
diff --git a/src/protocol/TopicRouteData.h b/src/protocol/TopicRouteData.h
index 6193588..446dd7b 100644
--- a/src/protocol/TopicRouteData.h
+++ b/src/protocol/TopicRouteData.h
@@ -23,7 +23,7 @@
 #include <cstdlib>
 #include <memory>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "Logging.h"
 #include "RemotingSerializable.h"
 #include "UtilAll.h"
@@ -62,8 +62,8 @@ typedef std::shared_ptr<TopicRouteData> TopicRouteDataPtr;
 
 class TopicRouteData {
  public:
-  static TopicRouteData* Decode(MemoryBlock& mem) {
-    Json::Value root = RemotingSerializable::fromJson(mem);
+  static TopicRouteData* Decode(const ByteArray& bodyData) {
+    Json::Value root = RemotingSerializable::fromJson(bodyData);
 
     std::unique_ptr<TopicRouteData> trd(new TopicRouteData());
     trd->setOrderTopicConf(root["orderTopicConf"].asString());
diff --git a/src/protocol/body/LockBatchBody.cpp b/src/protocol/body/LockBatchBody.cpp
index 9c3b6f0..fde8dcb 100644
--- a/src/protocol/body/LockBatchBody.cpp
+++ b/src/protocol/body/LockBatchBody.cpp
@@ -65,8 +65,8 @@ void LockBatchResponseBody::setLockOKMQSet(std::vector<MQMessageQueue> lockOKMQS
   m_lockOKMQSet.swap(lockOKMQSet);
 }
 
-LockBatchResponseBody* LockBatchResponseBody::Decode(MemoryBlock& mem) {
-  Json::Value root = RemotingSerializable::fromJson(mem);
+LockBatchResponseBody* LockBatchResponseBody::Decode(const ByteArray& bodyData) {
+  Json::Value root = RemotingSerializable::fromJson(bodyData);
   auto& mqs = root["lockOKMQSet"];
   std::unique_ptr<LockBatchResponseBody> body(new LockBatchResponseBody());
   for (const auto& qd : mqs) {
diff --git a/src/protocol/body/LockBatchBody.h b/src/protocol/body/LockBatchBody.h
index 22bd8e6..ce38974 100644
--- a/src/protocol/body/LockBatchBody.h
+++ b/src/protocol/body/LockBatchBody.h
@@ -20,7 +20,6 @@
 #include <set>
 #include <string>
 
-#include "DataBlock.h"
 #include "MQMessageQueue.h"
 #include "RemotingSerializable.h"
 #include "UtilAll.h"
@@ -48,7 +47,7 @@ class LockBatchRequestBody : public RemotingSerializable {
 
 class LockBatchResponseBody {
  public:
-  static LockBatchResponseBody* Decode(MemoryBlock& mem);
+  static LockBatchResponseBody* Decode(const ByteArray& bodyData);
 
   const std::vector<MQMessageQueue>& getLockOKMQSet();
   void setLockOKMQSet(std::vector<MQMessageQueue> lockOKMQSet);
diff --git a/src/protocol/body/ResetOffsetBody.cpp b/src/protocol/body/ResetOffsetBody.cpp
index 9caaf08..497f591 100644
--- a/src/protocol/body/ResetOffsetBody.cpp
+++ b/src/protocol/body/ResetOffsetBody.cpp
@@ -20,9 +20,9 @@
 
 namespace rocketmq {
 
-ResetOffsetBody* ResetOffsetBody::Decode(MemoryBlock& mem) {
+ResetOffsetBody* ResetOffsetBody::Decode(const ByteArray& bodyData) {
   // FIXME: object as key
-  Json::Value root = RemotingSerializable::fromJson(mem);
+  Json::Value root = RemotingSerializable::fromJson(bodyData);
   Json::Value qds = root["offsetTable"];
   std::unique_ptr<ResetOffsetBody> body(new ResetOffsetBody());
   for (unsigned int i = 0; i < qds.size(); i++) {
@@ -35,11 +35,11 @@ ResetOffsetBody* ResetOffsetBody::Decode(MemoryBlock& mem) {
 }
 
 std::map<MQMessageQueue, int64_t> ResetOffsetBody::getOffsetTable() {
-  return m_offsetTable;
+  return offset_table_;
 }
 
 void ResetOffsetBody::setOffsetTable(const MQMessageQueue& mq, int64_t offset) {
-  m_offsetTable[mq] = offset;
+  offset_table_[mq] = offset;
 }
 
 }  // namespace rocketmq
diff --git a/src/protocol/body/ResetOffsetBody.h b/src/protocol/body/ResetOffsetBody.h
index bc2c5f0..f1024b9 100644
--- a/src/protocol/body/ResetOffsetBody.h
+++ b/src/protocol/body/ResetOffsetBody.h
@@ -17,22 +17,22 @@
 #ifndef __RESET_OFFSET_BODY__
 #define __RESET_OFFSET_BODY__
 
-#include <map>
+#include <map>  // std::map
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "MQMessageQueue.h"
 
 namespace rocketmq {
 
 class ResetOffsetBody {
  public:
-  static ResetOffsetBody* Decode(MemoryBlock& mem);
+  static ResetOffsetBody* Decode(const ByteArray& bodyData);
 
   std::map<MQMessageQueue, int64_t> getOffsetTable();
   void setOffsetTable(const MQMessageQueue& mq, int64_t offset);
 
  private:
-  std::map<MQMessageQueue, int64_t> m_offsetTable;
+  std::map<MQMessageQueue, int64_t> offset_table_;
 };
 
 }  // namespace rocketmq
diff --git a/src/protocol/header/CommandHeader.cpp b/src/protocol/header/CommandHeader.cpp
index 2bb5cee..6a6ce80 100644
--- a/src/protocol/header/CommandHeader.cpp
+++ b/src/protocol/header/CommandHeader.cpp
@@ -642,8 +642,8 @@ void ConsumerSendMsgBackRequestHeader::SetDeclaredFieldOfCommandHeader(std::map<
 // GetConsumerListByGroupResponseBody
 //######################################
 
-GetConsumerListByGroupResponseBody* GetConsumerListByGroupResponseBody::Decode(MemoryBlock& mem) {
-  Json::Value root = RemotingSerializable::fromJson(mem);
+GetConsumerListByGroupResponseBody* GetConsumerListByGroupResponseBody::Decode(const ByteArray& bodyData) {
+  Json::Value root = RemotingSerializable::fromJson(bodyData);
   auto& ids = root["consumerIdList"];
   std::unique_ptr<GetConsumerListByGroupResponseBody> body(new GetConsumerListByGroupResponseBody());
   for (unsigned int i = 0; i < ids.size(); i++) {
diff --git a/src/protocol/header/CommandHeader.h b/src/protocol/header/CommandHeader.h
index 53b2114..39998d6 100644
--- a/src/protocol/header/CommandHeader.h
+++ b/src/protocol/header/CommandHeader.h
@@ -19,8 +19,8 @@
 
 #include <vector>
 
+#include "ByteArray.h"
 #include "CommandCustomHeader.h"
-#include "DataBlock.h"
 
 namespace rocketmq {
 
@@ -395,7 +395,7 @@ class ConsumerSendMsgBackRequestHeader : public CommandCustomHeader {
 
 class GetConsumerListByGroupResponseBody : public CommandCustomHeader {
  public:
-  static GetConsumerListByGroupResponseBody* Decode(MemoryBlock& mem);
+  static GetConsumerListByGroupResponseBody* Decode(const ByteArray& bodyData);
   void SetDeclaredFieldOfCommandHeader(std::map<std::string, std::string>& requestMap) override;
 
  public:
diff --git a/src/transport/SocketUtil.cpp b/src/transport/SocketUtil.cpp
index e4810d8..59dff7b 100644
--- a/src/transport/SocketUtil.cpp
+++ b/src/transport/SocketUtil.cpp
@@ -42,12 +42,21 @@ union sockaddr_union {
 
 thread_local static sockaddr_union sin_buf;
 
-struct sockaddr* ipPort2SocketAddress(uint32_t host, uint16_t port) {
-  struct sockaddr_in* sin = &sin_buf.sin;
-  sin->sin_family = AF_INET;
-  sin->sin_port = htons(port);
-  sin->sin_addr.s_addr = htonl(host);
-  return (struct sockaddr*)sin;
+struct sockaddr* ipPort2SocketAddress(const ByteArray& ip, uint16_t port) {
+  if (ip.size() == 4) {
+    struct sockaddr_in* sin = &sin_buf.sin;
+    sin->sin_family = AF_INET;
+    sin->sin_port = ByteOrderUtil::NorminalBigEndian<uint16_t>(port);
+    ByteOrderUtil::Read<decltype(sin->sin_addr)>(&sin->sin_addr, ip.array());
+    return (struct sockaddr*)sin;
+  } else if (ip.size() == 16) {
+    struct sockaddr_in6* sin6 = &sin_buf.sin6;
+    sin6->sin6_family = AF_INET6;
+    sin6->sin6_port = ByteOrderUtil::NorminalBigEndian<uint16_t>(port);
+    ByteOrderUtil::Read<decltype(sin6->sin6_addr)>(&sin6->sin6_addr, ip.array());
+    return (struct sockaddr*)sin6;
+  }
+  return nullptr;
 }
 
 struct sockaddr* string2SocketAddress(const std::string& addr) {
@@ -159,11 +168,11 @@ struct sockaddr* copySocketAddress(struct sockaddr* dst, const struct sockaddr*
 }
 
 uint64_t h2nll(uint64_t v) {
-  return ByteOrder::swapIfLittleEndian(v);
+  return ByteOrderUtil::NorminalBigEndian(v);
 }
 
 uint64_t n2hll(uint64_t v) {
-  return ByteOrder::swapIfLittleEndian(v);
+  return ByteOrderUtil::NorminalBigEndian(v);
 }
 
 }  // namespace rocketmq
diff --git a/src/transport/SocketUtil.h b/src/transport/SocketUtil.h
index e6a421b..bd2f31c 100644
--- a/src/transport/SocketUtil.h
+++ b/src/transport/SocketUtil.h
@@ -18,6 +18,7 @@
 #define __SOCKET_UTIL_H__
 
 #include <cstdint>
+
 #include <string>
 
 #ifndef WIN32
@@ -28,13 +29,15 @@
 #pragma comment(lib, "ws2_32.lib")
 #endif
 
+#include "ByteArray.h"
+
 namespace rocketmq {
 
 static inline size_t sockaddr_size(const struct sockaddr* sa) {
   return sa->sa_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
 }
 
-struct sockaddr* ipPort2SocketAddress(uint32_t host, uint16_t port);
+struct sockaddr* ipPort2SocketAddress(const ByteArray& ip, uint16_t port);
 
 struct sockaddr* string2SocketAddress(const std::string& addr);
 std::string socketAddress2String(const struct sockaddr* addr);
diff --git a/src/transport/TcpRemotingClient.cpp b/src/transport/TcpRemotingClient.cpp
index 948eb0e..5691f58 100644
--- a/src/transport/TcpRemotingClient.cpp
+++ b/src/transport/TcpRemotingClient.cpp
@@ -16,10 +16,11 @@
  */
 #include "TcpRemotingClient.h"
 
-#include <stddef.h>
+#include <cstddef>
+
+#include <algorithm>  // std::move
 
 #include "Logging.h"
-#include "MemoryOutputStream.h"
 #include "UtilAll.h"
 
 namespace rocketmq {
@@ -232,7 +233,7 @@ std::unique_ptr<RemotingCommand> TcpRemotingClient::invokeSync(const std::string
       CloseTransport(addr, channel);
       throw e;
     } catch (const RemotingTimeoutException& e) {
-      int code = request.getCode();
+      int code = request.code();
       if (code != GET_CONSUMER_LIST_BY_GROUP) {
         CloseTransport(addr, channel);
         LOG_WARN_NEW("invokeSync: close socket because of timeout, {}ms, {}", timeoutMillis,
@@ -250,8 +251,8 @@ std::unique_ptr<RemotingCommand> TcpRemotingClient::invokeSyncImpl(
     TcpTransportPtr channel,
     RemotingCommand& request,
     int64_t timeoutMillis) throw(RemotingTimeoutException, RemotingSendRequestException) {
-  int code = request.getCode();
-  int opaque = request.getOpaque();
+  int code = request.code();
+  int opaque = request.opaque();
 
   auto responseFuture = std::make_shared<ResponseFuture>(code, opaque, timeoutMillis);
   putResponseFuture(channel, opaque, responseFuture);
@@ -305,8 +306,8 @@ void TcpRemotingClient::invokeAsyncImpl(TcpTransportPtr channel,
                                         RemotingCommand& request,
                                         int64_t timeoutMillis,
                                         InvokeCallback* invokeCallback) throw(RemotingSendRequestException) {
-  int code = request.getCode();
-  int opaque = request.getOpaque();
+  int code = request.code();
+  int opaque = request.opaque();
 
   // delete in callback
   auto responseFuture = std::make_shared<ResponseFuture>(code, opaque, timeoutMillis, invokeCallback);
@@ -555,8 +556,8 @@ bool TcpRemotingClient::CloseNameServerTransport(TcpTransportPtr channel) {
 }
 
 bool TcpRemotingClient::SendCommand(TcpTransportPtr channel, RemotingCommand& msg) {
-  MemoryBlockPtr package(msg.encode());
-  return channel->sendMessage(package->getData(), package->getSize());
+  auto package = msg.encode();
+  return channel->sendMessage(package->array(), package->size());
 }
 
 void TcpRemotingClient::channelClosed(TcpTransportPtr channel) {
@@ -564,15 +565,14 @@ void TcpRemotingClient::channelClosed(TcpTransportPtr channel) {
   m_handleExecutor.submit([channel] { static_cast<ResponseFutureInfo*>(channel->getInfo())->activeAllResponses(); });
 }
 
-void TcpRemotingClient::messageReceived(MemoryBlockPtr mem, TcpTransportPtr channel) {
-  m_dispatchExecutor.submit(
-      std::bind(&TcpRemotingClient::processMessageReceived, this, MemoryBlockPtr2(std::move(mem)), channel));
+void TcpRemotingClient::messageReceived(ByteArrayRef msg, TcpTransportPtr channel) {
+  m_dispatchExecutor.submit(std::bind(&TcpRemotingClient::processMessageReceived, this, std::move(msg), channel));
 }
 
-void TcpRemotingClient::processMessageReceived(MemoryBlockPtr2 mem, TcpTransportPtr channel) {
+void TcpRemotingClient::processMessageReceived(ByteArrayRef msg, TcpTransportPtr channel) {
   std::unique_ptr<RemotingCommand> cmd;
   try {
-    cmd.reset(RemotingCommand::Decode(mem));
+    cmd.reset(RemotingCommand::Decode(std::move(msg)));
   } catch (...) {
     LOG_ERROR_NEW("processMessageReceived error");
     return;
@@ -612,7 +612,7 @@ void TcpRemotingClient::processMessageReceived(MemoryBlockPtr2 mem, TcpTransport
 
 void TcpRemotingClient::processResponseCommand(std::unique_ptr<RemotingCommand> responseCommand,
                                                TcpTransportPtr channel) {
-  int opaque = responseCommand->getOpaque();
+  int opaque = responseCommand->opaque();
   auto responseFuture = popResponseFuture(channel, opaque);
   if (responseFuture != nullptr) {
     int code = responseFuture->getRequestCode();
@@ -636,7 +636,7 @@ void TcpRemotingClient::processRequestCommand(std::unique_ptr<RemotingCommand> r
                                               TcpTransportPtr channel) {
   std::unique_ptr<RemotingCommand> response;
 
-  int requestCode = requestCommand->getCode();
+  int requestCode = requestCommand->code();
   const auto& it = m_processorTable.find(requestCode);
   if (it != m_processorTable.end()) {
     try {
@@ -653,14 +653,14 @@ void TcpRemotingClient::processRequestCommand(std::unique_ptr<RemotingCommand> r
     }
   } else {
     // send REQUEST_CODE_NOT_SUPPORTED response
-    std::string error = "request type " + UtilAll::to_string(requestCommand->getCode()) + " not supported";
+    std::string error = "request type " + UtilAll::to_string(requestCommand->code()) + " not supported";
     response.reset(new RemotingCommand(REQUEST_CODE_NOT_SUPPORTED, error));
 
     LOG_ERROR_NEW("{}: {}", channel->getPeerAddrAndPort(), error);
   }
 
   if (!requestCommand->isOnewayRPC() && response != nullptr) {
-    response->setOpaque(requestCommand->getOpaque());
+    response->set_opaque(requestCommand->opaque());
     response->markResponseType();
     try {
       if (!SendCommand(channel, *response)) {
diff --git a/src/transport/TcpRemotingClient.h b/src/transport/TcpRemotingClient.h
index e06f7ab..f193714 100755
--- a/src/transport/TcpRemotingClient.h
+++ b/src/transport/TcpRemotingClient.h
@@ -66,8 +66,8 @@ class TcpRemotingClient {
 
   void channelClosed(TcpTransportPtr channel);
 
-  void messageReceived(MemoryBlockPtr mem, TcpTransportPtr channel);
-  void processMessageReceived(MemoryBlockPtr2 mem, TcpTransportPtr channel);
+  void messageReceived(ByteArrayRef msg, TcpTransportPtr channel);
+  void processMessageReceived(ByteArrayRef msg, TcpTransportPtr channel);
   void processRequestCommand(std::unique_ptr<RemotingCommand> cmd, TcpTransportPtr channel);
   void processResponseCommand(std::unique_ptr<RemotingCommand> cmd, TcpTransportPtr channel);
 
diff --git a/src/transport/TcpTransport.cpp b/src/transport/TcpTransport.cpp
index 770bb43..15cfa9d 100644
--- a/src/transport/TcpTransport.cpp
+++ b/src/transport/TcpTransport.cpp
@@ -229,7 +229,7 @@ void TcpTransport::dataArrived(BufferEvent& event) {
       return;
     }
 
-    uint32_t msgLen = ByteOrder::swapIfLittleEndian(packageLength);  // same as ntohl()
+    uint32_t msgLen = ByteOrderUtil::NorminalBigEndian(packageLength);  // same as ntohl()
     size_t recvLen = evbuffer_get_length(input);
     if (recvLen >= msgLen + 4) {
       LOG_DEBUG_NEW("had received all data. msgLen:{}, from:{}, recvLen:{}", msgLen, event.getfd(), recvLen);
@@ -239,19 +239,19 @@ void TcpTransport::dataArrived(BufferEvent& event) {
     }
 
     if (msgLen > 0) {
-      MemoryBlockPtr msg(new MemoryPool(msgLen, true));
+      auto msg = std::make_shared<ByteArray>(msgLen);
 
       event.read(&packageLength, 4);  // skip length field
-      event.read(msg->getData(), msgLen);
+      event.read(msg->array(), msgLen);
 
       messageReceived(std::move(msg));
     }
   }
 }
 
-void TcpTransport::messageReceived(MemoryBlockPtr mem) {
+void TcpTransport::messageReceived(ByteArrayRef msg) {
   if (m_readCallback != nullptr) {
-    m_readCallback(std::move(mem), shared_from_this());
+    m_readCallback(std::move(msg), shared_from_this());
   }
 }
 
diff --git a/src/transport/TcpTransport.h b/src/transport/TcpTransport.h
index 5a1ccb7..cffe2e9 100755
--- a/src/transport/TcpTransport.h
+++ b/src/transport/TcpTransport.h
@@ -21,7 +21,7 @@
 #include <condition_variable>
 #include <mutex>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "EventLoop.h"
 
 namespace rocketmq {
@@ -44,7 +44,7 @@ class TcpTransportInfo {
 
 class TcpTransport : public noncopyable, public std::enable_shared_from_this<TcpTransport> {
  public:
-  typedef std::function<void(MemoryBlockPtr, TcpTransportPtr) noexcept> ReadCallback;
+  typedef std::function<void(ByteArrayRef, TcpTransportPtr) noexcept> ReadCallback;
   typedef std::function<void(TcpTransportPtr) noexcept> CloseCallback;
 
  public:
@@ -76,7 +76,7 @@ class TcpTransport : public noncopyable, public std::enable_shared_from_this<Tcp
   void dataArrived(BufferEvent& event);
   void eventOccurred(BufferEvent& event, short what);
 
-  void messageReceived(MemoryBlockPtr mem);
+  void messageReceived(ByteArrayRef msg);
 
   TcpConnectStatus closeBufferEvent(bool isDeleted = false);
 
diff --git a/test/src/common/BigEndianTest.cpp b/test/src/common/BigEndianTest.cpp
deleted file mode 100644
index b329988..0000000
--- a/test/src/common/BigEndianTest.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include <string>
-
-#include "big_endian.h"
-
-using testing::InitGoogleMock;
-using testing::InitGoogleTest;
-using testing::Return;
-
-using rocketmq::BigEndianReader;
-using rocketmq::BigEndianWriter;
-
-TEST(BigEndianTest, BigEndianObject) {
-  char buf[32];
-
-  BigEndianWriter writer(buf, 32);
-  BigEndianReader reader(buf, 32);
-
-  uint64_t uint64[1];
-  EXPECT_TRUE(writer.WriteU64((uint64_t)0x1234567890ABCDEF));
-  EXPECT_EQ(*(uint64_t*)reader.ptr(), 0xEFCDAB9078563412);
-  EXPECT_TRUE(reader.ReadU64(uint64));
-  EXPECT_EQ(*uint64, 0x1234567890ABCDEF);
-
-  uint32_t uint32[1];
-  EXPECT_TRUE(writer.WriteU32((uint32_t)0x12345678));
-  EXPECT_EQ(*(uint32_t*)reader.ptr(), 0x78563412);
-  EXPECT_TRUE(reader.ReadU32(uint32));
-  EXPECT_EQ(*uint32, 0x12345678);
-
-  uint16_t uint16[1];
-  EXPECT_TRUE(writer.WriteU16((uint16_t)0x1234));
-  EXPECT_EQ(*(uint16_t*)reader.ptr(), 0x3412);
-  EXPECT_TRUE(reader.ReadU16(uint16));
-  EXPECT_EQ(*uint16, 0x1234);
-
-  uint8_t uint8[1];
-  EXPECT_TRUE(writer.WriteU8((uint8_t)0x12));
-  EXPECT_EQ(*(uint8_t*)reader.ptr(), 0x12);
-  EXPECT_TRUE(reader.ReadU8(uint8));
-  EXPECT_EQ(*uint8, 0x12);
-
-  char str[] = "RocketMQ";
-  char str2[sizeof(str)];
-  EXPECT_TRUE(writer.WriteBytes(str, sizeof(str) - 1));
-  EXPECT_TRUE(strncmp(reader.ptr(), str, sizeof(str) - 1) == 0);
-  EXPECT_TRUE(reader.ReadBytes(str2, sizeof(str) - 1));
-  EXPECT_TRUE(strncmp(str2, str, sizeof(str) - 1) == 0);
-}
-
-TEST(BigEndianTest, BigEndian) {
-  char buf[8];
-
-  rocketmq::WriteBigEndian(buf, (uint8_t)0x12);
-  EXPECT_EQ(*(uint8_t*)buf, 0x12);
-
-  uint8_t out[1];
-  rocketmq::ReadBigEndian(buf, out);
-  EXPECT_EQ(*out, 0x12);
-}
-
-int main(int argc, char* argv[]) {
-  InitGoogleMock(&argc, argv);
-  testing::GTEST_FLAG(throw_on_failure) = true;
-  testing::GTEST_FLAG(filter) = "BigEndianTest.*";
-  return RUN_ALL_TESTS();
-}
diff --git a/test/src/common/ClientRPCHookTest.cpp b/test/src/common/ClientRPCHookTest.cpp
index 0d22c93..02ce843 100644
--- a/test/src/common/ClientRPCHookTest.cpp
+++ b/test/src/common/ClientRPCHookTest.cpp
@@ -50,7 +50,7 @@ TEST(ClientRPCHookTest, BeforeRequest) {
   RemotingCommand sendRequestCommand(MQRequestCode::UPDATE_AND_CREATE_TOPIC, sendMessageRequestHeader);
   clientRPCHook.doBeforeRequest("127.0.0.1:9876", sendRequestCommand, true);
 
-  sendRequestCommand.setBody("1231231");
+  sendRequestCommand.set_body("1231231");
   clientRPCHook.doBeforeRequest("127.0.0.1:9876", sendRequestCommand, true);
 }
 
diff --git a/test/src/common/MemoryBlockTest.cpp b/test/src/common/MemoryBlockTest.cpp
deleted file mode 100644
index fc8d0ec..0000000
--- a/test/src/common/MemoryBlockTest.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include <string>
-
-#include "DataBlock.h"
-
-using testing::InitGoogleMock;
-using testing::InitGoogleTest;
-using testing::Return;
-
-using rocketmq::MemoryBlock;
-using rocketmq::MemoryPool;
-
-TEST(MemoryBlockTest, Init) {
-  MemoryBlock memoryBlock;
-  EXPECT_EQ(memoryBlock.getSize(), 0);
-  EXPECT_TRUE(memoryBlock.getData() == nullptr);
-
-  MemoryPool twoMemoryBlock(0, true);
-  EXPECT_EQ(twoMemoryBlock.getSize(), 0);
-  EXPECT_TRUE(twoMemoryBlock.getData() == nullptr);
-
-  MemoryPool threeMemoryBlock(10, true);
-  EXPECT_EQ(threeMemoryBlock.getSize(), 10);
-  EXPECT_TRUE(threeMemoryBlock.getData() != nullptr);
-
-  MemoryPool frouMemoryBlock(12, false);
-  EXPECT_EQ(frouMemoryBlock.getSize(), 12);
-  EXPECT_TRUE(frouMemoryBlock.getData() != nullptr);
-
-  char buf[] = "RocketMQ";
-  MemoryPool fiveMemoryBlock(buf, 0);
-  EXPECT_EQ(fiveMemoryBlock.getSize(), 0);
-  EXPECT_TRUE(fiveMemoryBlock.getData() == nullptr);
-
-  MemoryPool sixMemoryBlock(nullptr, 16);
-  EXPECT_EQ(sixMemoryBlock.getSize(), 16);
-  EXPECT_TRUE(sixMemoryBlock.getData() != nullptr);
-
-  MemoryPool sevenMemoryBlock(buf, sizeof(buf) - 1);
-  EXPECT_EQ(sevenMemoryBlock.getSize(), sizeof(buf) - 1);
-  EXPECT_EQ((std::string)sevenMemoryBlock, buf);
-
-  MemoryPool nineMemoryBlock(sevenMemoryBlock);
-  EXPECT_EQ(nineMemoryBlock.getSize(), sevenMemoryBlock.getSize());
-  EXPECT_EQ(nineMemoryBlock, sevenMemoryBlock);
-
-  MemoryPool eightMemoryBlock(fiveMemoryBlock);
-  EXPECT_EQ(eightMemoryBlock.getSize(), fiveMemoryBlock.getSize());
-  EXPECT_TRUE(eightMemoryBlock.getData() == nullptr);
-}
-
-TEST(MemoryBlockTest, Operators) {
-  MemoryPool memoryBlock(8, false);
-
-  MemoryPool operaterMemoryBlock = memoryBlock;
-  EXPECT_TRUE(operaterMemoryBlock == memoryBlock);
-
-  char buf[] = "RocketMQ";
-  MemoryPool twoMemoryBlock(buf, sizeof(buf) - 1);
-  EXPECT_FALSE(memoryBlock == twoMemoryBlock);
-
-  MemoryPool threeMemoryBlock(buf, 7);
-  EXPECT_FALSE(memoryBlock == threeMemoryBlock);
-  EXPECT_TRUE(twoMemoryBlock != threeMemoryBlock);
-
-  threeMemoryBlock.fillWith(49);
-  EXPECT_EQ((std::string)threeMemoryBlock, "1111111");
-
-  threeMemoryBlock.reset();
-  EXPECT_EQ(threeMemoryBlock.getSize(), 0);
-  EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
-
-  threeMemoryBlock.setSize(16, false);
-  EXPECT_EQ(threeMemoryBlock.getSize(), 16);
-
-  threeMemoryBlock.setSize(0, false);
-  EXPECT_EQ(threeMemoryBlock.getSize(), 0);
-  EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
-
-  MemoryPool appendMemoryBlock;
-  EXPECT_EQ(appendMemoryBlock.getSize(), 0);
-  EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
-
-  appendMemoryBlock.append(buf, 0);
-  EXPECT_EQ(appendMemoryBlock.getSize(), 0);
-  EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
-
-  appendMemoryBlock.append(buf, sizeof(buf) - 1);
-  EXPECT_EQ(appendMemoryBlock.getSize(), 8);
-
-  MemoryPool replaceWithMemoryBlock;
-  replaceWithMemoryBlock.append(buf, sizeof(buf) - 1);
-
-  char aliyunBuf[] = "aliyun";
-  replaceWithMemoryBlock.replaceWith(aliyunBuf, 0);
-  EXPECT_EQ(replaceWithMemoryBlock.getSize(), 8);
-  EXPECT_EQ((std::string)replaceWithMemoryBlock, "RocketMQ");
-
-  replaceWithMemoryBlock.replaceWith(aliyunBuf, sizeof(aliyunBuf) - 1);
-  EXPECT_EQ(replaceWithMemoryBlock.getSize(), 6);
-  EXPECT_EQ((std::string)replaceWithMemoryBlock, "aliyun");
-
-  MemoryPool insertMemoryBlock;
-  insertMemoryBlock.append(buf, sizeof(buf) - 1);
-  insertMemoryBlock.insert(aliyunBuf, 0, 0);
-  EXPECT_EQ((std::string)insertMemoryBlock, "RocketMQ");
-
-  MemoryPool twoInsertMemoryBlock;
-  twoInsertMemoryBlock.append(buf, sizeof(buf) - 1);
-  twoInsertMemoryBlock.insert(aliyunBuf, sizeof(aliyunBuf) - 1, 0);
-  EXPECT_EQ((std::string)twoInsertMemoryBlock, "aliyunRocketMQ");
-
-  MemoryPool threeInsertMemoryBlock;
-  threeInsertMemoryBlock.append(buf, sizeof(buf) - 1);
-  threeInsertMemoryBlock.insert(aliyunBuf, sizeof(aliyunBuf) - 1, 100);
-  EXPECT_EQ((std::string)threeInsertMemoryBlock, "RocketMQaliyun");
-
-  MemoryPool removeSectionMemoryBlock(buf, sizeof(buf) - 1);
-  removeSectionMemoryBlock.removeSection(8, 0);
-  EXPECT_EQ((std::string)removeSectionMemoryBlock, "RocketMQ");
-
-  MemoryPool twoRemoveSectionMemoryBlock(buf, sizeof(buf) - 1);
-  twoRemoveSectionMemoryBlock.removeSection(1, 4);
-  EXPECT_EQ((std::string)twoRemoveSectionMemoryBlock, "RtMQ");
-}
-
-int main(int argc, char* argv[]) {
-  InitGoogleMock(&argc, argv);
-  testing::GTEST_FLAG(throw_on_failure) = true;
-  testing::GTEST_FLAG(filter) = "MemoryBlockTest.*";
-  return RUN_ALL_TESTS();
-}
diff --git a/test/src/common/MemoryOutputStreamTest.cpp b/test/src/common/MemoryOutputStreamTest.cpp
deleted file mode 100644
index 80218cf..0000000
--- a/test/src/common/MemoryOutputStreamTest.cpp
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include "DataBlock.h"
-#include "MemoryInputStream.h"
-#include "MemoryOutputStream.h"
-
-using testing::InitGoogleMock;
-using testing::InitGoogleTest;
-using testing::Return;
-
-using rocketmq::MemoryBlock;
-using rocketmq::MemoryInputStream;
-using rocketmq::MemoryOutputStream;
-using rocketmq::MemoryPool;
-
-TEST(MemoryOutputStreamTest, Init) {
-  MemoryOutputStream memoryOutput;
-  EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
-  EXPECT_TRUE(memoryOutput.getData() != nullptr);
-
-  EXPECT_EQ(memoryOutput.getPosition(), 0);
-  EXPECT_EQ(memoryOutput.getDataSize(), 0);
-
-  MemoryOutputStream twoMemoryOutput(512);
-  EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
-
-  MemoryPool memoryBlock(12, false);
-  MemoryOutputStream threeMemoryOutput(memoryBlock, false);
-  EXPECT_EQ(threeMemoryOutput.getPosition(), 0);
-  EXPECT_EQ(threeMemoryOutput.getDataSize(), 0);
-
-  MemoryOutputStream frouMemoryOutput(memoryBlock, true);
-  EXPECT_EQ(frouMemoryOutput.getPosition(), memoryBlock.getSize());
-  EXPECT_EQ(frouMemoryOutput.getDataSize(), memoryBlock.getSize());
-
-  char buf[] = "RocketMQ";
-  MemoryOutputStream fiveMemoryOutputStream(buf, sizeof(buf));
-  EXPECT_EQ(fiveMemoryOutputStream.getData(), buf);
-
-  fiveMemoryOutputStream.reset();
-  EXPECT_EQ(memoryOutput.getPosition(), 0);
-  EXPECT_EQ(memoryOutput.getDataSize(), 0);
-}
-
-TEST(MemoryOutputStreamTest, Flush) {
-  char buf[] = "RocketMQ";
-  MemoryOutputStream memoryOutput;
-  memoryOutput.write(buf, sizeof(buf) - 1);
-  memoryOutput.flush();
-  EXPECT_FALSE(memoryOutput.getData() == buf);
-}
-
-TEST(MemoryOutputStreamTest, Preallocate) {
-  MemoryOutputStream memoryOutput;
-
-  // TODO:
-  memoryOutput.preallocate(250);
-
-  memoryOutput.preallocate(256);
-}
-
-TEST(MemoryOutputStreamTest, GetMemoryBlock) {
-  char buf[] = "RocketMQ";
-  MemoryOutputStream memoryOutput;
-  memoryOutput.write(buf, sizeof(buf) - 1);
-  MemoryPool memoryBlock = memoryOutput.getMemoryBlock();
-  EXPECT_EQ(memoryBlock.getSize(), memoryOutput.getDataSize());
-}
-
-TEST(MemoryOutputStreamTest, PrepareToWriteAndGetData) {
-  char buf[] = "RocketMQ";
-  MemoryOutputStream memoryOutput(buf, sizeof(buf));
-  EXPECT_EQ(memoryOutput.getData(), buf);
-
-  // prepareToWrite
-  // EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
-  EXPECT_TRUE(memoryOutput.writeByte('r'));
-  EXPECT_STREQ(static_cast<const char*>(memoryOutput.getData()), "rocketMQ");
-
-  MemoryOutputStream blockMmoryOutput(8);
-  auto* memoryData = static_cast<const char*>(blockMmoryOutput.getData());
-  EXPECT_EQ(memoryData[blockMmoryOutput.getDataSize()], 0);
-
-  blockMmoryOutput.write(buf, 8);
-  blockMmoryOutput.write(buf, 8);
-  auto* data = static_cast<const char*>(blockMmoryOutput.getData());
-  EXPECT_STREQ(data, "rocketMQrocketMQ");
-}
-
-TEST(MemoryOutputStreamTest, Position) {
-  char buf[] = "RocketMQ";
-
-  MemoryOutputStream memoryOutput;
-  EXPECT_EQ(memoryOutput.getPosition(), 0);
-
-  memoryOutput.write(buf, sizeof(buf) - 1);
-  EXPECT_EQ(memoryOutput.getPosition(), 8);
-
-  EXPECT_FALSE(memoryOutput.setPosition(9));
-
-  EXPECT_TRUE(memoryOutput.setPosition(-1));
-  EXPECT_EQ(memoryOutput.getPosition(), 0);
-
-  EXPECT_TRUE(memoryOutput.setPosition(8));
-  EXPECT_EQ(memoryOutput.getPosition(), 8);
-
-  EXPECT_TRUE(memoryOutput.setPosition(7));
-  EXPECT_EQ(memoryOutput.getPosition(), 7);
-}
-
-TEST(MemoryOutputStreamTest, Write) {
-  MemoryOutputStream memoryOutput;
-  MemoryInputStream memoryInput(memoryOutput.getData(), 256, false);
-
-  EXPECT_TRUE(memoryOutput.writeBool(true));
-  EXPECT_TRUE(memoryInput.readBool());
-
-  EXPECT_TRUE(memoryOutput.writeBool(false));
-  EXPECT_FALSE(memoryInput.readBool());
-
-  EXPECT_TRUE(memoryOutput.writeByte('a'));
-  EXPECT_EQ(memoryInput.readByte(), 'a');
-
-  EXPECT_TRUE(memoryOutput.writeShortBigEndian(128));
-  EXPECT_EQ(memoryInput.readShortBigEndian(), 128);
-
-  EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
-  EXPECT_EQ(memoryInput.readIntBigEndian(), 123);
-
-  EXPECT_TRUE(memoryOutput.writeInt64BigEndian(123123));
-  EXPECT_EQ(memoryInput.readInt64BigEndian(), 123123);
-
-  EXPECT_TRUE(memoryOutput.writeDoubleBigEndian(12.71));
-  EXPECT_EQ(memoryInput.readDoubleBigEndian(), 12.71);
-
-  EXPECT_TRUE(memoryOutput.writeFloatBigEndian(12.1));
-  float f = 12.1;
-  EXPECT_EQ(memoryInput.readFloatBigEndian(), f);
-}
-
-TEST(MemoryInputStreamTest, Info) {
-  char buf[] = "RocketMQ";
-
-  MemoryInputStream memoryInput(buf, sizeof(buf) - 1, false);
-  EXPECT_EQ(memoryInput.getData(), buf);
-  EXPECT_EQ(memoryInput.getTotalLength(), 8);
-
-  MemoryInputStream twoMemoryInput(buf, sizeof(buf) - 1, true);
-  EXPECT_NE(twoMemoryInput.getData(), buf);
-
-  MemoryBlock memoryBlock(buf, sizeof(buf) - 1);
-  MemoryInputStream threeMemoryInput(memoryBlock, false);
-  EXPECT_EQ(threeMemoryInput.getData(), memoryBlock.getData());
-  EXPECT_EQ(threeMemoryInput.getTotalLength(), 8);
-
-  MemoryInputStream frouMemoryInput(memoryBlock, true);
-  EXPECT_NE(frouMemoryInput.getData(), memoryBlock.getData());
-}
-
-TEST(MemoryInputStreamTest, Position) {
-  char buf[] = "RocketMQ";
-
-  MemoryInputStream memoryInput(buf, sizeof(buf) - 1, false);
-  EXPECT_EQ(memoryInput.getPosition(), 0);
-  EXPECT_FALSE(memoryInput.isExhausted());
-
-  memoryInput.setPosition(9);
-  EXPECT_EQ(memoryInput.getPosition(), 8);
-  EXPECT_TRUE(memoryInput.isExhausted());
-
-  memoryInput.setPosition(-1);
-  EXPECT_EQ(memoryInput.getPosition(), 0);
-}
-
-int main(int argc, char* argv[]) {
-  InitGoogleMock(&argc, argv);
-  testing::GTEST_FLAG(throw_on_failure) = true;
-  testing::GTEST_FLAG(filter) = "*.*";
-  return RUN_ALL_TESTS();
-}
diff --git a/test/src/extern/CProducerTest.cpp b/test/src/extern/CProducerTest.cpp
index 5c97043..17ed7c6 100644
--- a/test/src/extern/CProducerTest.cpp
+++ b/test/src/extern/CProducerTest.cpp
@@ -49,10 +49,10 @@ class MockDefaultMQProducer : public DefaultMQProducer {
   MOCK_METHOD(void, start, (), (override));
   MOCK_METHOD(void, shutdown, (), (override));
 
-  MOCK_METHOD(SendResult, send, (MQMessage*), (override));
-  MOCK_METHOD(void, send, (MQMessage*, SendCallback*), (noexcept, override));
-  MOCK_METHOD(SendResult, send, (MQMessage*, MessageQueueSelector*, void*, long), (override));
-  MOCK_METHOD(void, sendOneway, (MQMessage*), (override));
+  MOCK_METHOD(SendResult, send, (MQMessage&), (override));
+  MOCK_METHOD(void, send, (MQMessage&, SendCallback*), (noexcept, override));
+  MOCK_METHOD(SendResult, send, (MQMessage&, MessageQueueSelector*, void*, long), (override));
+  MOCK_METHOD(void, sendOneway, (MQMessage&), (override));
 };
 
 void CSendSuccessCallbackFunc(CSendResult result) {}
diff --git a/test/src/extern/CPullConsumerTest.cpp b/test/src/extern/CPullConsumerTest.cpp
index a356a57..2297779 100644
--- a/test/src/extern/CPullConsumerTest.cpp
+++ b/test/src/extern/CPullConsumerTest.cpp
@@ -22,7 +22,7 @@
 
 #include "DefaultMQPullConsumer.h"
 #include "MQClientInstance.h"
-#include "MQMessageExt.h"
+#include "MessageExtImpl.h"
 #include "MQMessageQueue.h"
 #include "PullResult.h"
 #include "SessionCredentials.h"
@@ -39,7 +39,8 @@ using testing::SetArgReferee;
 
 using rocketmq::DefaultMQPullConsumer;
 using rocketmq::MessageModel;
-using rocketmq::MQMessageExt;
+using rocketmq::MessageExtPtr;
+using rocketmq::MessageClientExtImpl;
 using rocketmq::MQMessageQueue;
 using rocketmq::PullResult;
 using rocketmq::PullStatus;
@@ -70,9 +71,9 @@ TEST(CPullConsumerTest, Pull) {
   PullResult offsetIllegalPullResult(PullStatus::OFFSET_ILLEGAL, 1, 2, 3);
   PullResult defaultPullResult((PullStatus)-1, 1, 2, 3);
 
-  std::vector<std::shared_ptr<MQMessageExt>> src;
+  std::vector<MessageExtPtr> src;
   for (int i = 0; i < 5; i++) {
-    auto ext = std::make_shared<MQMessageExt>();
+    auto ext = std::make_shared<MessageClientExtImpl>();
     src.push_back(ext);
   }
   PullResult foundPullResult(PullStatus::FOUND, 1, 2, 3, src);
diff --git a/test/src/message/MQMessageExtTest.cpp b/test/src/message/MQMessageExtTest.cpp
index 86a28aa..400d900 100644
--- a/test/src/message/MQMessageExtTest.cpp
+++ b/test/src/message/MQMessageExtTest.cpp
@@ -18,6 +18,7 @@
 #include <gtest/gtest.h>
 
 #include "MQMessageExt.h"
+#include "MessageExtImpl.h"
 #include "MessageSysFlag.h"
 #include "SocketUtil.h"
 #include "TopicFilterType.h"
@@ -26,14 +27,15 @@ using testing::InitGoogleMock;
 using testing::InitGoogleTest;
 using testing::Return;
 
+using rocketmq::MessageClientExtImpl;
+using rocketmq::MessageExtImpl;
 using rocketmq::MessageSysFlag;
-using rocketmq::MQMessageClientExt;
 using rocketmq::MQMessageConst;
 using rocketmq::MQMessageExt;
 using rocketmq::TopicFilterType;
 
-TEST(MessageExtTest, MessageClientExt) {
-  MQMessageClientExt messageClientExt;
+TEST(MessageExtTest, MessageClientExtImpl) {
+  MessageClientExtImpl messageClientExt;
   EXPECT_EQ(messageClientExt.getQueueOffset(), 0);
   EXPECT_EQ(messageClientExt.getCommitLogOffset(), 0);
   EXPECT_EQ(messageClientExt.getBornTimestamp(), 0);
@@ -117,8 +119,8 @@ TEST(MessageExtTest, MessageExt) {
 }
 
 TEST(MessageExtTest, ParseTopicFilterType) {
-  EXPECT_EQ(MQMessageExt::parseTopicFilterType(MessageSysFlag::MultiTagsFlag), TopicFilterType::MULTI_TAG);
-  EXPECT_EQ(MQMessageExt::parseTopicFilterType(0), TopicFilterType::SINGLE_TAG);
+  EXPECT_EQ(MessageExtImpl::parseTopicFilterType(MessageSysFlag::MULTI_TAGS_FLAG), TopicFilterType::MULTI_TAG);
+  EXPECT_EQ(MessageExtImpl::parseTopicFilterType(0), TopicFilterType::SINGLE_TAG);
 }
 
 int main(int argc, char* argv[]) {
diff --git a/test/src/message/MQMessageTest.cpp b/test/src/message/MQMessageTest.cpp
index bea6ae2..515e384 100644
--- a/test/src/message/MQMessageTest.cpp
+++ b/test/src/message/MQMessageTest.cpp
@@ -85,10 +85,6 @@ TEST(MessageTest, GetterAndSetter) {
   message.setBody("testBody");
   EXPECT_EQ(message.getBody(), "testBody");
 
-  const char* body = "testBody";
-  message.setBody(body, 5);
-  EXPECT_EQ(message.getBody(), "testB");
-
   EXPECT_EQ(message.getTags(), "");  // default
   message.setTags("testTags");
   EXPECT_EQ(message.getTags(), "testTags");
diff --git a/test/src/message/MessageBatchTest.cpp b/test/src/message/MessageBatchTest.cpp
index 7d84592..8e61c4d 100644
--- a/test/src/message/MessageBatchTest.cpp
+++ b/test/src/message/MessageBatchTest.cpp
@@ -30,6 +30,7 @@ using testing::Return;
 using rocketmq::MessageBatch;
 using rocketmq::MessageDecoder;
 using rocketmq::MQMessage;
+using rocketmq::stoba;
 
 TEST(MessageBatchTest, Encode) {
   std::vector<MQMessage> msgs;
diff --git a/test/src/message/MessageDecoderTest.cpp b/test/src/message/MessageDecoderTest.cpp
index 5acfc81..8f15e02 100644
--- a/test/src/message/MessageDecoderTest.cpp
+++ b/test/src/message/MessageDecoderTest.cpp
@@ -17,18 +17,17 @@
 
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
-#include <stdio.h>
 
 #include <string>
 #include <vector>
 
+#include "ByteArray.h"
+#include "ByteBuffer.hpp"
 #include "MessageDecoder.h"
 #include "MQMessage.h"
 #include "MQMessageConst.h"
 #include "MQMessageExt.h"
 #include "MessageId.h"
-#include "MemoryInputStream.h"
-#include "MemoryOutputStream.h"
 #include "MessageSysFlag.h"
 #include "RemotingCommand.h"
 #include "UtilAll.h"
@@ -38,9 +37,8 @@ using testing::InitGoogleMock;
 using testing::InitGoogleTest;
 using testing::Return;
 
-using rocketmq::MemoryBlock;
-using rocketmq::MemoryInputStream;
-using rocketmq::MemoryOutputStream;
+using rocketmq::ByteArray;
+using rocketmq::ByteBuffer;
 using rocketmq::MessageSysFlag;
 using rocketmq::MessageDecoder;
 using rocketmq::MQMessage;
@@ -49,124 +47,134 @@ using rocketmq::MQMessageExt;
 using rocketmq::MessageId;
 using rocketmq::RemotingCommand;
 using rocketmq::SendMessageRequestHeader;
+using rocketmq::stoba;
 using rocketmq::UtilAll;
 
 // TODO
 TEST(MessageDecoderTest, MessageId) {
   std::string strMsgId = MessageDecoder::createMessageId(rocketmq::string2SocketAddress("127.0.0.1:10091"), 1024LL);
-  EXPECT_EQ(strMsgId, "0100007F0000276B0000000000000400");
+  EXPECT_EQ(strMsgId, "7F0000010000276B0000000000000400");
 
   MessageId msgId = MessageDecoder::decodeMessageId(strMsgId);
-  EXPECT_EQ(msgId.getOffset(), 1024);
+  EXPECT_EQ(msgId.getOffset(), 1024LL);
+
+  std::string strMsgId2 = MessageDecoder::createMessageId(rocketmq::string2SocketAddress("/172.16.2.114:0"), 123456LL);
+  EXPECT_EQ(strMsgId2, "AC10027200000000000000000001E240");
+
+  MessageId msgId2 = MessageDecoder::decodeMessageId(strMsgId2);
+  EXPECT_EQ(msgId2.getOffset(), 123456LL);
 }
 
 TEST(MessageDecoderTest, Decode) {
-  MemoryOutputStream* memoryOut = new MemoryOutputStream(1024);
+  std::unique_ptr<ByteBuffer> byteBuffer(ByteBuffer::allocate(1024));
   MQMessageExt msgExt;
 
   // 1 TOTALSIZE  4=0+4
-  memoryOut->writeIntBigEndian(111);
+  byteBuffer->putInt(111);
   msgExt.setStoreSize(111);
 
   // 2 MAGICCODE sizeof(int)  8=4+4
-  memoryOut->writeIntBigEndian(14);
+  byteBuffer->putInt(14);
 
   // 3 BODYCRC  12=8+4
-  memoryOut->writeIntBigEndian(24);
+  byteBuffer->putInt(24);
   msgExt.setBodyCRC(24);
 
   // 4 QUEUEID  16=12+4
-  memoryOut->writeIntBigEndian(4);
+  byteBuffer->putInt(4);
   msgExt.setQueueId(4);
 
   // 5 FLAG  20=16+4
-  memoryOut->writeIntBigEndian(4);
+  byteBuffer->putInt(4);
   msgExt.setFlag(4);
 
   // 6 QUEUEOFFSET  28=20+8
-  memoryOut->writeInt64BigEndian(1024LL);
+  byteBuffer->putLong(1024LL);
   msgExt.setQueueOffset(1024LL);
 
   // 7 PHYSICALOFFSET  36=28+8
-  memoryOut->writeInt64BigEndian(2048LL);
+  byteBuffer->putLong(2048LL);
   msgExt.setCommitLogOffset(2048LL);
 
   // 8 SYSFLAG  40=36+4
-  memoryOut->writeIntBigEndian(0);
+  byteBuffer->putInt(0);
   msgExt.setSysFlag(0);
 
   // 9 BORNTIMESTAMP  48=40+8
-  memoryOut->writeInt64BigEndian(4096LL);
+  byteBuffer->putLong(4096LL);
   msgExt.setBornTimestamp(4096LL);
 
   // 10 BORNHOST  56=48+4+4
-  memoryOut->writeIntBigEndian(ntohl(inet_addr("127.0.0.1")));
-  memoryOut->writeIntBigEndian(10091);
+  byteBuffer->putInt(ntohl(inet_addr("127.0.0.1")));
+  byteBuffer->putInt(10091);
   msgExt.setBornHost(rocketmq::string2SocketAddress("127.0.0.1:10091"));
 
   // 11 STORETIMESTAMP  64=56+8
-  memoryOut->writeInt64BigEndian(4096LL);
+  byteBuffer->putLong(4096LL);
   msgExt.setStoreTimestamp(4096LL);
 
   // 12 STOREHOST  72=64+4+4
-  memoryOut->writeIntBigEndian(ntohl(inet_addr("127.0.0.2")));
-  memoryOut->writeIntBigEndian(10092);
+  byteBuffer->putInt(ntohl(inet_addr("127.0.0.2")));
+  byteBuffer->putInt(10092);
   msgExt.setStoreHost(rocketmq::string2SocketAddress("127.0.0.2:10092"));
 
   // 13 RECONSUMETIMES 76=72+4
-  memoryOut->writeIntBigEndian(18);
+  byteBuffer->putInt(18);
   msgExt.setReconsumeTimes(18);
 
   // 14 Prepared Transaction Offset  84=76+8
-  memoryOut->writeInt64BigEndian(12LL);
+  byteBuffer->putLong(12LL);
   msgExt.setPreparedTransactionOffset(12LL);
 
   // 15 BODY  98=84+4+10
-  std::string body = "1234567890";
-  memoryOut->writeIntBigEndian(body.size());
-  memoryOut->write(body.data(), body.size());
+  std::string body("1234567890");
+  byteBuffer->putInt(body.size());
+  byteBuffer->put(*stoba(body));
   msgExt.setBody(body);
 
   // 16 TOPIC  109=98+1+10
   std::string topic = "topic_1234";
-  memoryOut->writeByte(topic.size());
-  memoryOut->write(topic.data(), topic.size());
+  byteBuffer->put((int8_t)topic.size());
+  byteBuffer->put(*stoba(topic));
   msgExt.setTopic(topic);
 
   // 17 PROPERTIES 111=109+2
-  memoryOut->writeShortBigEndian(0);
+  byteBuffer->putShort(0);
 
   msgExt.setMsgId(MessageDecoder::createMessageId(msgExt.getStoreHost(), (int64_t)msgExt.getCommitLogOffset()));
 
-  auto block = memoryOut->getMemoryBlock();
-  auto msgs = MessageDecoder::decodes(*static_cast<MemoryBlock*>(&block));
+  byteBuffer->flip();
+  auto msgs = MessageDecoder::decodes(*byteBuffer);
   EXPECT_EQ(msgs.size(), 1);
 
   std::cout << msgs[0]->toString() << std::endl;
   std::cout << msgExt.toString() << std::endl;
   EXPECT_EQ(msgs[0]->toString(), msgExt.toString());
 
-  msgs = MessageDecoder::decodes(*static_cast<MemoryBlock*>(&block), false);
-  EXPECT_EQ(msgs[0]->getBody().size(), 0);
+  byteBuffer->rewind();
+  msgs = MessageDecoder::decodes(*byteBuffer, false);
+  EXPECT_EQ(msgs[0]->getBody(), "");
 
   //===============================================================
 
+  byteBuffer->clear();
+
   // 8 SYSFLAG  40=36+4
-  memoryOut->setPosition(36);
-  memoryOut->writeIntBigEndian(0 | MessageSysFlag::CompressedFlag);
-  msgExt.setSysFlag(0 | MessageSysFlag::CompressedFlag);
+  byteBuffer->position(36);
+  byteBuffer->putInt(0 | MessageSysFlag::COMPRESSED_FLAG);
+  msgExt.setSysFlag(0 | MessageSysFlag::COMPRESSED_FLAG);
 
   // 15 Body 84
   std::string compressedBody;
   UtilAll::deflate(body, compressedBody, 5);
-  memoryOut->setPosition(84);
-  memoryOut->writeIntBigEndian(compressedBody.size());
-  memoryOut->write(compressedBody.data(), compressedBody.size());
+  byteBuffer->position(84);
+  byteBuffer->putInt(compressedBody.size());
+  byteBuffer->put(*stoba(compressedBody));
   msgExt.setBody(compressedBody);
 
   // 16 TOPIC
-  memoryOut->writeByte(topic.size());
-  memoryOut->write(topic.data(), topic.size());
+  byteBuffer->put((int8_t)topic.size());
+  byteBuffer->put(*stoba(topic));
   msgExt.setTopic(topic);
 
   // 17 PROPERTIES
@@ -174,17 +182,18 @@ TEST(MessageDecoderTest, Decode) {
   properties["RocketMQ"] = "cpp-client";
   properties[MQMessageConst::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX] = "123456";
   std::string props = MessageDecoder::messageProperties2String(properties);
-  memoryOut->writeShortBigEndian(props.size());
-  memoryOut->write(props.data(), props.size());
+  byteBuffer->putShort(props.size());
+  byteBuffer->put(*stoba(props));
   msgExt.setProperties(properties);
   msgExt.setMsgId("123456");
 
-  memoryOut->setPosition(0);
-  memoryOut->writeIntBigEndian(memoryOut->getDataSize());
-  msgExt.setStoreSize(memoryOut->getDataSize());
+  byteBuffer->flip();
+
+  byteBuffer->putInt(byteBuffer->limit());
+  msgExt.setStoreSize(byteBuffer->limit());
 
-  block = memoryOut->getMemoryBlock();
-  msgs = MessageDecoder::decodes(*static_cast<MemoryBlock*>(&block));
+  byteBuffer->rewind();
+  msgs = MessageDecoder::decodes(*byteBuffer);
   EXPECT_EQ(msgs[0]->toString(), msgExt.toString());
 }
 
diff --git a/test/src/protocol/CommandHeaderTest.cpp b/test/src/protocol/CommandHeaderTest.cpp
index 37ed241..502ab29 100644
--- a/test/src/protocol/CommandHeaderTest.cpp
+++ b/test/src/protocol/CommandHeaderTest.cpp
@@ -24,7 +24,7 @@
 #include <memory>
 #include <string>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "MQClientException.h"
 #include "MessageSysFlag.h"
 #include "UtilAll.h"
@@ -37,6 +37,7 @@ using testing::Return;
 using Json::FastWriter;
 using Json::Value;
 
+using rocketmq::ByteArray;
 using rocketmq::CommandCustomHeader;
 using rocketmq::ConsumerSendMsgBackRequestHeader;
 using rocketmq::CreateTopicRequestHeader;
@@ -51,8 +52,6 @@ using rocketmq::GetMaxOffsetResponseHeader;
 using rocketmq::GetMinOffsetRequestHeader;
 using rocketmq::GetMinOffsetResponseHeader;
 using rocketmq::GetRouteInfoRequestHeader;
-using rocketmq::MemoryBlock;
-using rocketmq::MemoryView;
 using rocketmq::NotifyConsumerIdsChangedRequestHeader;
 using rocketmq::PullMessageRequestHeader;
 using rocketmq::PullMessageResponseHeader;
@@ -80,8 +79,8 @@ TEST(CommandHeaderTest, GetConsumerListByGroupResponseBody) {
   FastWriter writer;
   std::string data = writer.write(root);
 
-  std::unique_ptr<MemoryBlock> mem(new MemoryBlock(const_cast<char*>(data.data()), data.size()));
-  std::unique_ptr<GetConsumerListByGroupResponseBody> body(GetConsumerListByGroupResponseBody::Decode(*mem));
+  const ByteArray bodyData((char*)data.data(), data.size());
+  std::unique_ptr<GetConsumerListByGroupResponseBody> body(GetConsumerListByGroupResponseBody::Decode(bodyData));
   EXPECT_EQ(body->consumerIdList.size(), 2);
 }
 
diff --git a/test/src/protocol/LockBatchBodyTest.cpp b/test/src/protocol/LockBatchBodyTest.cpp
index 567f27c..64da9fb 100644
--- a/test/src/protocol/LockBatchBodyTest.cpp
+++ b/test/src/protocol/LockBatchBodyTest.cpp
@@ -19,7 +19,7 @@
 
 #include <vector>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "MQMessageQueue.h"
 #include "protocol/body/LockBatchBody.h"
 
@@ -27,9 +27,9 @@ using testing::InitGoogleMock;
 using testing::InitGoogleTest;
 using testing::Return;
 
+using rocketmq::ByteArray;
 using rocketmq::LockBatchRequestBody;
 using rocketmq::LockBatchResponseBody;
-using rocketmq::MemoryBlock;
 using rocketmq::MQMessageQueue;
 using rocketmq::UnlockBatchRequestBody;
 
@@ -75,10 +75,10 @@ TEST(LockBatchBodyTest, LockBatchResponseBody) {
   root["lockOKMQSet"] = mqs;
 
   Json::FastWriter fastwrite;
-  std::string outData = fastwrite.write(root);
+  std::string data = fastwrite.write(root);
 
-  std::unique_ptr<MemoryBlock> mem(new MemoryBlock(const_cast<char*>(outData.data()), outData.size()));
-  std::unique_ptr<LockBatchResponseBody> lockBatchResponseBody(LockBatchResponseBody::Decode(*mem));
+  const ByteArray bodyData((char*)data.data(), data.size());
+  std::unique_ptr<LockBatchResponseBody> lockBatchResponseBody(LockBatchResponseBody::Decode(bodyData));
 
   MQMessageQueue messageQueue("testTopic", "testBroker", 1);
   EXPECT_EQ(messageQueue, lockBatchResponseBody->getLockOKMQSet()[0]);
diff --git a/test/src/protocol/RemotingCommandTest.cpp b/test/src/protocol/RemotingCommandTest.cpp
index e579e00..7729d93 100644
--- a/test/src/protocol/RemotingCommandTest.cpp
+++ b/test/src/protocol/RemotingCommandTest.cpp
@@ -20,10 +20,9 @@
 #include <memory>
 #include <string>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "MQProtos.h"
 #include "MQVersion.h"
-#include "MemoryOutputStream.h"
 #include "RemotingCommand.h"
 #include "protocol/header/CommandHeader.h"
 
@@ -31,13 +30,12 @@ using testing::InitGoogleMock;
 using testing::InitGoogleTest;
 using testing::Return;
 
+using rocketmq::ByteArray;
 using rocketmq::GetConsumerRunningInfoRequestHeader;
 using rocketmq::GetEarliestMsgStoretimeResponseHeader;
 using rocketmq::GetMaxOffsetResponseHeader;
 using rocketmq::GetMinOffsetResponseHeader;
 using rocketmq::GetRouteInfoRequestHeader;
-using rocketmq::MemoryBlock;
-using rocketmq::MemoryOutputStream;
 using rocketmq::MQRequestCode;
 using rocketmq::MQVersion;
 using rocketmq::NotifyConsumerIdsChangedRequestHeader;
@@ -50,15 +48,15 @@ using rocketmq::SendMessageResponseHeader;
 
 TEST(RemotingCommandTest, Init) {
   RemotingCommand remotingCommand;
-  EXPECT_EQ(remotingCommand.getCode(), 0);
+  EXPECT_EQ(remotingCommand.code(), 0);
 
   RemotingCommand twoRemotingCommand(13);
-  EXPECT_EQ(twoRemotingCommand.getCode(), 13);
-  EXPECT_EQ(twoRemotingCommand.getOpaque(), 0);
-  EXPECT_EQ(twoRemotingCommand.getRemark(), "");
-  EXPECT_EQ(twoRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
-  EXPECT_EQ(twoRemotingCommand.getFlag(), 0);
-  EXPECT_TRUE(twoRemotingCommand.getBody() == nullptr);
+  EXPECT_EQ(twoRemotingCommand.code(), 13);
+  EXPECT_EQ(twoRemotingCommand.opaque(), 0);
+  EXPECT_EQ(twoRemotingCommand.remark(), "");
+  EXPECT_EQ(twoRemotingCommand.version(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(twoRemotingCommand.flag(), 0);
+  EXPECT_TRUE(twoRemotingCommand.body() == nullptr);
   EXPECT_TRUE(twoRemotingCommand.readCustomHeader() == nullptr);
 
   RemotingCommand threeRemotingCommand(13, new GetRouteInfoRequestHeader("topic"));
@@ -66,86 +64,85 @@ TEST(RemotingCommandTest, Init) {
 
   RemotingCommand frouRemotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark",
                                       new GetRouteInfoRequestHeader("topic"));
-  EXPECT_EQ(frouRemotingCommand.getCode(), 13);
-  EXPECT_EQ(frouRemotingCommand.getOpaque(), 12);
-  EXPECT_EQ(frouRemotingCommand.getRemark(), "remark");
-  EXPECT_EQ(frouRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
-  EXPECT_EQ(frouRemotingCommand.getFlag(), 3);
-  EXPECT_TRUE(frouRemotingCommand.getBody() == nullptr);
+  EXPECT_EQ(frouRemotingCommand.code(), 13);
+  EXPECT_EQ(frouRemotingCommand.opaque(), 12);
+  EXPECT_EQ(frouRemotingCommand.remark(), "remark");
+  EXPECT_EQ(frouRemotingCommand.version(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(frouRemotingCommand.flag(), 3);
+  EXPECT_TRUE(frouRemotingCommand.body() == nullptr);
   EXPECT_FALSE(frouRemotingCommand.readCustomHeader() == nullptr);
 
   RemotingCommand sixRemotingCommand(std::move(frouRemotingCommand));
-  EXPECT_EQ(sixRemotingCommand.getCode(), 13);
-  EXPECT_EQ(sixRemotingCommand.getOpaque(), 12);
-  EXPECT_EQ(sixRemotingCommand.getRemark(), "remark");
-  EXPECT_EQ(sixRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
-  EXPECT_EQ(sixRemotingCommand.getFlag(), 3);
-  EXPECT_TRUE(sixRemotingCommand.getBody() == nullptr);
+  EXPECT_EQ(sixRemotingCommand.code(), 13);
+  EXPECT_EQ(sixRemotingCommand.opaque(), 12);
+  EXPECT_EQ(sixRemotingCommand.remark(), "remark");
+  EXPECT_EQ(sixRemotingCommand.version(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(sixRemotingCommand.flag(), 3);
+  EXPECT_TRUE(sixRemotingCommand.body() == nullptr);
   EXPECT_FALSE(sixRemotingCommand.readCustomHeader() == nullptr);
 
   RemotingCommand* sevenRemotingCommand = &sixRemotingCommand;
-  EXPECT_EQ(sevenRemotingCommand->getCode(), 13);
-  EXPECT_EQ(sevenRemotingCommand->getOpaque(), 12);
-  EXPECT_EQ(sevenRemotingCommand->getRemark(), "remark");
-  EXPECT_EQ(sevenRemotingCommand->getVersion(), MQVersion::s_CurrentVersion);
-  EXPECT_EQ(sevenRemotingCommand->getFlag(), 3);
-  EXPECT_TRUE(sevenRemotingCommand->getBody() == nullptr);
+  EXPECT_EQ(sevenRemotingCommand->code(), 13);
+  EXPECT_EQ(sevenRemotingCommand->opaque(), 12);
+  EXPECT_EQ(sevenRemotingCommand->remark(), "remark");
+  EXPECT_EQ(sevenRemotingCommand->version(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(sevenRemotingCommand->flag(), 3);
+  EXPECT_TRUE(sevenRemotingCommand->body() == nullptr);
   EXPECT_FALSE(sevenRemotingCommand->readCustomHeader() == nullptr);
 }
 
 TEST(RemotingCommandTest, Info) {
   RemotingCommand remotingCommand;
 
-  remotingCommand.setCode(13);
-  EXPECT_EQ(remotingCommand.getCode(), 13);
+  remotingCommand.set_code(13);
+  EXPECT_EQ(remotingCommand.code(), 13);
 
-  remotingCommand.setOpaque(12);
-  EXPECT_EQ(remotingCommand.getOpaque(), 12);
+  remotingCommand.set_opaque(12);
+  EXPECT_EQ(remotingCommand.opaque(), 12);
 
-  remotingCommand.setRemark("123");
-  EXPECT_EQ(remotingCommand.getRemark(), "123");
+  remotingCommand.set_remark("123");
+  EXPECT_EQ(remotingCommand.remark(), "123");
 
-  remotingCommand.setBody("msgBody");
-  EXPECT_EQ((std::string)*remotingCommand.getBody(), "msgBody");
+  remotingCommand.set_body("msgBody");
+  EXPECT_EQ((std::string)remotingCommand.body()->array(), "msgBody");
 
-  remotingCommand.addExtField("key", "value");
+  remotingCommand.set_ext_field("key", "value");
 }
 
 TEST(RemotingCommandTest, Flag) {
   RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 0, "remark",
                                   new GetRouteInfoRequestHeader("topic"));
   ;
-  EXPECT_EQ(remotingCommand.getFlag(), 0);
+  EXPECT_EQ(remotingCommand.flag(), 0);
 
   remotingCommand.markResponseType();
   int bits = 1 << 0;
   int flag = 0;
   flag |= bits;
-  EXPECT_EQ(remotingCommand.getFlag(), flag);
+  EXPECT_EQ(remotingCommand.flag(), flag);
   EXPECT_TRUE(remotingCommand.isResponseType());
 
   bits = 1 << 1;
   flag |= bits;
   remotingCommand.markOnewayRPC();
-  EXPECT_EQ(remotingCommand.getFlag(), flag);
+  EXPECT_EQ(remotingCommand.flag(), flag);
   EXPECT_TRUE(remotingCommand.isOnewayRPC());
 }
 
 TEST(RemotingCommandTest, EncodeAndDecode) {
   RemotingCommand remotingCommand(MQRequestCode::QUERY_BROKER_OFFSET, "CPP", MQVersion::s_CurrentVersion, 12, 3,
                                   "remark", nullptr);
-  remotingCommand.setBody("123123");
+  remotingCommand.set_body("123123");
 
   auto package = remotingCommand.encode();
 
-  std::unique_ptr<RemotingCommand> decodeRemtingCommand(
-      RemotingCommand::Decode(std::shared_ptr<MemoryBlock>(std::move(package)), true));
+  std::unique_ptr<RemotingCommand> decodeRemtingCommand(RemotingCommand::Decode(package, true));
 
-  EXPECT_EQ(remotingCommand.getCode(), decodeRemtingCommand->getCode());
-  EXPECT_EQ(remotingCommand.getOpaque(), decodeRemtingCommand->getOpaque());
-  EXPECT_EQ(remotingCommand.getRemark(), decodeRemtingCommand->getRemark());
-  EXPECT_EQ(remotingCommand.getVersion(), decodeRemtingCommand->getVersion());
-  EXPECT_EQ(remotingCommand.getFlag(), decodeRemtingCommand->getFlag());
+  EXPECT_EQ(remotingCommand.code(), decodeRemtingCommand->code());
+  EXPECT_EQ(remotingCommand.opaque(), decodeRemtingCommand->opaque());
+  EXPECT_EQ(remotingCommand.remark(), decodeRemtingCommand->remark());
+  EXPECT_EQ(remotingCommand.version(), decodeRemtingCommand->version());
+  EXPECT_EQ(remotingCommand.flag(), decodeRemtingCommand->flag());
   EXPECT_TRUE(decodeRemtingCommand->readCustomHeader() == nullptr);
 
   // ~RemotingCommand delete
@@ -156,10 +153,10 @@ TEST(RemotingCommandTest, EncodeAndDecode) {
 
   RemotingCommand remotingCommand2(MQRequestCode::GET_CONSUMER_RUNNING_INFO, "CPP", MQVersion::s_CurrentVersion, 12, 3,
                                    "remark", requestHeader);
-  remotingCommand2.setBody("123123");
+  remotingCommand2.set_body("123123");
   package = remotingCommand2.encode();
 
-  decodeRemtingCommand.reset(RemotingCommand::Decode(std::shared_ptr<MemoryBlock>(std::move(package)), true));
+  decodeRemtingCommand.reset(RemotingCommand::Decode(package, true));
 
   auto* header = decodeRemtingCommand->decodeCommandCustomHeader<GetConsumerRunningInfoRequestHeader>();
   EXPECT_EQ(requestHeader->getClientId(), header->getClientId());
@@ -171,9 +168,9 @@ TEST(RemotingCommandTest, SetExtHeader) {
 
   EXPECT_TRUE(remotingCommand->readCustomHeader() == nullptr);
 
-  remotingCommand->addExtField("msgId", "ABCD");
-  remotingCommand->addExtField("queueId", "1");
-  remotingCommand->addExtField("queueOffset", "1024");
+  remotingCommand->set_ext_field("msgId", "ABCD");
+  remotingCommand->set_ext_field("queueId", "1");
+  remotingCommand->set_ext_field("queueOffset", "1024");
   auto* sendMessageResponseHeader = remotingCommand->decodeCommandCustomHeader<SendMessageResponseHeader>();
   EXPECT_EQ(sendMessageResponseHeader->msgId, "ABCD");
   EXPECT_EQ(sendMessageResponseHeader->queueId, 1);
diff --git a/test/src/protocol/TopicRouteDataTest.cpp b/test/src/protocol/TopicRouteDataTest.cpp
index b9671ed..3b518b9 100644
--- a/test/src/protocol/TopicRouteDataTest.cpp
+++ b/test/src/protocol/TopicRouteDataTest.cpp
@@ -19,15 +19,15 @@
 
 #include <memory>
 
-#include "DataBlock.h"
+#include "ByteArray.h"
 #include "TopicRouteData.h"
 
 using testing::InitGoogleMock;
 using testing::InitGoogleTest;
 using testing::Return;
 
+using rocketmq::ByteArray;
 using rocketmq::BrokerData;
-using rocketmq::MemoryBlock;
 using rocketmq::QueueData;
 using rocketmq::TopicRouteData;
 
@@ -59,10 +59,10 @@ TEST(TopicRouteDataTest, TopicRouteData) {
 
   root["brokerDatas"] = brokerDatas;
 
-  std::string out = root.toStyledString();
+  std::string data = root.toStyledString();
 
-  std::unique_ptr<MemoryBlock> block(new MemoryBlock(const_cast<char*>(out.data()), out.size()));
-  std::unique_ptr<TopicRouteData> topicRouteData(TopicRouteData::Decode(*block));
+  const ByteArray bodyData((char*)data.data(), data.size());
+  std::unique_ptr<TopicRouteData> topicRouteData(TopicRouteData::Decode(bodyData));
 
   EXPECT_EQ(root["orderTopicConf"], topicRouteData->getOrderTopicConf());
 
diff --git a/test/src/transport/ClientRemotingProcessorTest.cpp b/test/src/transport/ClientRemotingProcessorTest.cpp
index d57fd32..843fa49 100644
--- a/test/src/transport/ClientRemotingProcessorTest.cpp
+++ b/test/src/transport/ClientRemotingProcessorTest.cpp
@@ -22,10 +22,10 @@
 #include <map>
 #include <memory>
 
+#include "ByteArray.h"
 #include "ClientRPCHook.h"
 #include "ClientRemotingProcessor.h"
 #include "ConsumerRunningInfo.h"
-#include "DataBlock.h"
 #include "MQClientConfigImpl.h"
 #include "MQClientInstance.h"
 #include "MQMessageQueue.h"
@@ -47,11 +47,11 @@ using testing::SetArgReferee;
 using Json::FastWriter;
 using Json::Value;
 
+using rocketmq::ByteArray;
 using rocketmq::ClientRemotingProcessor;
 using rocketmq::ClientRPCHook;
 using rocketmq::ConsumerRunningInfo;
 using rocketmq::GetConsumerRunningInfoRequestHeader;
-using rocketmq::MemoryBlock;
 using rocketmq::MQClientConfig;
 using rocketmq::MQClientConfigImpl;
 using rocketmq::MQClientInstance;
diff --git a/test/src/transport/ResponseFutureTest.cpp b/test/src/transport/ResponseFutureTest.cpp
index bc717e0..e199fe0 100644
--- a/test/src/transport/ResponseFutureTest.cpp
+++ b/test/src/transport/ResponseFutureTest.cpp
@@ -66,7 +66,7 @@ TEST(ResponseFutureTest, Response) {
 
   std::unique_ptr<RemotingCommand> responseCommand(new RemotingCommand());
   responseFuture.setResponseCommand(std::move(responseCommand));
-  EXPECT_EQ(responseFuture.getResponseCommand()->getCode(), 0);
+  EXPECT_EQ(responseFuture.getResponseCommand()->code(), 0);
 
   ResponseFuture responseFuture2(MQRequestCode::QUERY_BROKER_OFFSET, 4, 1000);
   uint64_t millis = UtilAll::currentTimeMillis();
diff --git a/test/src/transport/SocketUtilTest.cpp b/test/src/transport/SocketUtilTest.cpp
index 41d200d..e7b8a70 100644
--- a/test/src/transport/SocketUtilTest.cpp
+++ b/test/src/transport/SocketUtilTest.cpp
@@ -23,10 +23,13 @@ using testing::InitGoogleMock;
 using testing::InitGoogleTest;
 using testing::Return;
 
+using rocketmq::ByteArray;
+
 using namespace rocketmq;
 
 TEST(SocketUtilTest, Convert) {
-  struct sockaddr* sa = ipPort2SocketAddress(0x7F000001, 0x276B);
+  char ip[] = {0x7F, 0x00, 0x00, 0x01};
+  struct sockaddr* sa = ipPort2SocketAddress(ByteArray(ip, sizeof(ip)), 0x276B);
   struct sockaddr_in* sin = (struct sockaddr_in*)sa;
   EXPECT_EQ(sin->sin_addr.s_addr, 0x0100007F);
   EXPECT_EQ(sin->sin_port, 0x6B27);


Mime
View raw message