]> git.tdb.fi Git - libs/net.git/commitdiff
Add a base id parameter to Protocol's serialization functions
authorMikko Rasa <tdb@tdb.fi>
Sun, 15 Jan 2023 07:36:07 +0000 (09:36 +0200)
committerMikko Rasa <tdb@tdb.fi>
Sun, 15 Jan 2023 07:36:07 +0000 (09:36 +0200)
This allows multiplexing protocols on a single connection by externally
adjusting their packet ID.

source/net/protocol.cpp
source/net/protocol.h

index 63cc6f16c1dac82b14baebad1b4556f245c1b147..c6112923c9692db7f4b646f11d68e0a8e6e753a0 100644 (file)
@@ -44,13 +44,13 @@ const Protocol::PacketDefBase &Protocol::get_packet_by_id(unsigned id) const
        return *get_item(packet_id_defs, id);
 }
 
-size_t Protocol::dispatch(ReceiverBase &rcv, const char *buf, size_t size) const
+size_t Protocol::dispatch(ReceiverBase &rcv, const char *buf, size_t size, unsigned base_id) const
 {
        PacketHeader header;
        const char *ptr = header_def.deserialize(header, buf, buf+size);
        if(header.length>size)
                throw bad_packet("truncated");
-       const PacketDefBase &pdef = get_packet_by_id(header.type);
+       const PacketDefBase &pdef = get_packet_by_id(header.type-base_id);
        ptr = pdef.dispatch(rcv, ptr, ptr+header.length);
        return ptr-buf;
 }
index 8068d3275ca292eea2317e9847725f90a0be7524..0721ec5b5403adebb4013e54a07358700beebecc 100644 (file)
@@ -226,10 +226,10 @@ protected:
 
 public:
        template<typename P>
-       std::size_t serialize(const P &, char *, std::size_t) const;
+       std::size_t serialize(const P &, char *, std::size_t, unsigned = 0) const;
 
        std::size_t get_packet_size(const char *, std::size_t) const;
-       std::size_t dispatch(ReceiverBase &, const char *, std::size_t) const;
+       std::size_t dispatch(ReceiverBase &, const char *, std::size_t, unsigned = 0) const;
 
        std::uint64_t get_hash() const;
 };
@@ -265,14 +265,14 @@ const Protocol::PacketTypeDef<P> &Protocol::get_packet_by_class() const
 }
 
 template<typename P>
-std::size_t Protocol::serialize(const P &pkt, char *buf, std::size_t size) const
+std::size_t Protocol::serialize(const P &pkt, char *buf, std::size_t size, unsigned base_id) const
 {
        const PacketTypeDef<P> &pdef = get_packet_by_class<P>();
        if(!pdef.get_id())
                throw std::invalid_argument("no packet id");
        char *ptr = pdef.serialize(pkt, buf+4, buf+size);
        size = ptr-buf;
-       header_def.serialize(PacketHeader(pdef.get_id(), size), buf, buf+4);
+       header_def.serialize(PacketHeader(base_id+pdef.get_id(), size), buf, buf+4);
        return size;
 }