From 708ff9e8af731e2799767ed8bfca7df3b74fc26a Mon Sep 17 00:00:00 2001
From: lichao <lichao@aiotlink.com>
Date: 星期五, 16 四月 2021 19:20:21 +0800
Subject: [PATCH] sendq use less shm, copy data.

---
 src/msg.h |   33 ++++++++++++++++++++++++++++++++-
 1 files changed, 32 insertions(+), 1 deletions(-)

diff --git a/src/msg.h b/src/msg.h
index 10ad0d2..c239956 100644
--- a/src/msg.h
+++ b/src/msg.h
@@ -82,6 +82,15 @@
 		    uint32_t(body.ByteSizeLong()), [&](void *p, int len) { body.SerializeToArray(p, len); });
 	}
 
+	void *Pack(SharedMemory &shm, const std::string &content)
+	{
+		void *addr = shm.Alloc(content.size());
+		if (addr) {
+			memcpy(addr, content.data(), content.size());
+		}
+		return addr;
+	}
+
 	bool MakeRC(SharedMemory &shm, void *addr);
 	bool Make(SharedMemory &shm, void *addr);
 
@@ -111,7 +120,6 @@
 	}
 
 	bool EnableRefCount(SharedMemory &shm);
-
 	template <class Body>
 	inline bool Make(SharedMemory &shm, const BHMsgHead &head, const Body &body)
 	{
@@ -119,6 +127,29 @@
 		auto NeedRefCount = [&]() { return head.type() == kMsgTypePublish; };
 		return NeedRefCount() ? MakeRC(shm, p) : Make(shm, p);
 	}
+	template <class Body>
+	static inline std::string Serialize(const BHMsgHead &head, const Body &body)
+	{
+		uint32_t head_len = head.ByteSizeLong();
+		uint32_t body_len = body.ByteSizeLong();
+		std::string s(4 + head_len + 4 + body_len, '\0');
+		size_t pos = 0;
+		auto add1 = [&](auto &&msg, auto &&size) {
+			Put32(&s[pos], size);
+			pos += 4;
+			msg.SerializeToArray(&s[pos], size);
+			pos += size;
+		};
+		add1(head, head_len);
+		add1(body, body_len);
+		assert(pos == s.size());
+		return s;
+	}
+	inline bool Make(SharedMemory &shm, const std::string &content)
+	{
+		void *p = Pack(shm, content);
+		return Make(shm, p);
+	}
 
 	bool ParseHead(BHMsgHead &head) const;
 	template <class Body>

--
Gitblit v1.8.0