From dc86ace85e437ecb8a2e728e4dce36d02bbb8a6e Mon Sep 17 00:00:00 2001
From: lichao <lichao@aiotlink.com>
Date: 星期五, 23 四月 2021 12:59:50 +0800
Subject: [PATCH] move ref count into msg meta, only 1 poinetr now.

---
 src/msg.cpp |   80 +++++++++++++++++++++++++++++++++++-----
 1 files changed, 70 insertions(+), 10 deletions(-)

diff --git a/src/msg.cpp b/src/msg.cpp
index e8c6d26..ba844da 100644
--- a/src/msg.cpp
+++ b/src/msg.cpp
@@ -16,20 +16,80 @@
  * =====================================================================================
  */
 #include "msg.h"
+#include "bh_util.h"
 
-namespace bhome_shm {
-	
-
-bool MsgMetaV1::Parse(const void *p)
+namespace bhome_msg
 {
-    assert(p);
-    *this = *static_cast<const MsgMetaV1*>(p);
-    return tag_ == kMsgMetaTag;
+/*TODO change msg format, header has proc info;
+reply has errer msg
+    center accept request and route.;
+//*/
+const uint32_t kMsgTag = 0xf1e2d3c4;
+
+void *MsgI::Alloc(SharedMemory &shm, const size_t size)
+{
+	void *p = shm.Alloc(sizeof(Meta) + size);
+	if (p) {
+		auto pmeta = new (p) Meta;
+		p = pmeta + 1;
+	}
+	return p;
+}
+void MsgI::Free(SharedMemory &shm)
+{
+	assert(valid());
+	shm.Dealloc(meta());
+	ptr_ = nullptr;
+	assert(!valid());
 }
 
-void MsgMetaV1::Pack(void *p)
+void *MsgI::Pack(SharedMemory &shm,
+                 const uint32_t head_len, const ToArray &headToArray,
+                 const uint32_t body_len, const ToArray &bodyToArray)
 {
-    *static_cast<MsgMetaV1*>(p) = *this;
+	void *addr = Alloc(shm, sizeof(head_len) + head_len + sizeof(body_len) + body_len);
+	if (addr) {
+		auto p = static_cast<char *>(addr);
+		auto Pack1 = [&p](auto len, auto &writer) {
+			Put32(p, len);
+			p += sizeof(len);
+			writer(p, len);
+			p += len;
+		};
+		Pack1(head_len, headToArray);
+		Pack1(body_len, bodyToArray);
+	}
+	return addr;
 }
 
-} // namespace bhome_shm
+bool MsgI::ParseHead(BHMsgHead &head) const
+{
+	auto p = get<char>();
+	assert(p);
+	uint32_t msg_size = Get32(p);
+	p += 4;
+	return head.ParseFromArray(p, msg_size);
+}
+
+bool MsgI::Make(SharedMemory &shm, void *p)
+{
+	if (!p) {
+		return false;
+	}
+	MsgI(p).swap(*this);
+	return true;
+}
+
+int MsgI::Release(SharedMemory &shm)
+{
+	if (!valid()) {
+		return 0;
+	}
+	auto n = meta()->count_.Dec();
+	if (n == 0) {
+		Free(shm);
+	}
+	return n;
+}
+
+} // namespace bhome_msg

--
Gitblit v1.8.0