aboutsummaryrefslogtreecommitdiffstats
path: root/fnet/src/vespa/fnet/simplepacketstreamer.cpp
blob: cea6b0688558a1dde5d5793d6e30c01db0b42594 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "simplepacketstreamer.h"
#include "databuffer.h"
#include "ipacketfactory.h"
#include "packet.h"

FNET_SimplePacketStreamer::FNET_SimplePacketStreamer(FNET_IPacketFactory *factory)
    : _factory(factory)
{
}


FNET_SimplePacketStreamer::~FNET_SimplePacketStreamer()
{
}


bool
FNET_SimplePacketStreamer::GetPacketInfo(FNET_DataBuffer *src, uint32_t *plen,
                                         uint32_t *pcode, uint32_t *chid,
                                         bool *broken)
{
    (void) broken;

    if (src->GetDataLen() < 3 * sizeof(uint32_t))
        return false;

    *plen  = src->ReadInt32() - 2 * sizeof(uint32_t);
    *pcode = src->ReadInt32();
    *chid  = src->ReadInt32();
    return true;
}


FNET_Packet*
FNET_SimplePacketStreamer::Decode(FNET_DataBuffer *src, uint32_t plen,
                                  uint32_t pcode, FNET_Context context)
{
    FNET_Packet *packet;

    packet = _factory->CreatePacket(pcode, context);
    if (packet != nullptr) {
        if (!packet->Decode(src, plen)) {
            packet->Free();
            packet = nullptr;
        }
    } else {
        src->DataToDead(plen);
    }
    src->AssertValid();
    return packet;
}


void
FNET_SimplePacketStreamer::Encode(FNET_Packet *packet, uint32_t chid,
                                  FNET_DataBuffer *dst)
{
    uint32_t len   = packet->GetLength();
    uint32_t pcode = packet->GetPCODE();
    dst->EnsureFree(len + 3 * sizeof(uint32_t));
    dst->WriteInt32Fast(len + 2 * sizeof(uint32_t));
    dst->WriteInt32Fast(pcode);
    dst->WriteInt32Fast(chid);
    packet->Encode(dst);
    dst->AssertValid();
}