From 373740374b839d8dca5133aa225be0ba62bbd498 Mon Sep 17 00:00:00 2001 From: lesismal Date: Sat, 21 Sep 2024 23:16:27 +0800 Subject: [PATCH] design: def protocol stack --- protocol_stack.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 protocol_stack.go diff --git a/protocol_stack.go b/protocol_stack.go new file mode 100644 index 00000000..f0267858 --- /dev/null +++ b/protocol_stack.go @@ -0,0 +1,45 @@ +package nbio + +import ( + "net" +) + +type Protocol interface { + Parse(c net.Conn, b []byte, ps *ProtocolStack) (net.Conn, []byte, error) + Write(b []byte) (int, error) +} + +type ProtocolStack struct { + stack []Protocol +} + +func (ps *ProtocolStack) Add(p Protocol) { + ps.stack = append(ps.stack, p) +} + +func (ps *ProtocolStack) Delete(p Protocol) { + for i, v := range ps.stack { + if v == p { + ps.stack[i] = nil + return + } + } +} + +func (ps *ProtocolStack) Parse(c net.Conn, b []byte, ps_ ProtocolStack) (net.Conn, []byte, error) { + var err error + for _, p := range ps.stack { + if p == nil { + continue + } + c, b, err = p.Parse(c, b, ps) + if err != nil { + break + } + } + return c, b, err +} + +func (ps *ProtocolStack) Write(b []byte) (int, error) { + return -1, ErrUnsupported +}