aboutsummaryrefslogtreecommitdiff
path: root/src/stream_mqtt.c
blob: 3864ef30681c9f0f63025be1821f70be11a5bcd9 (plain)
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
69
70
71
72
73
74
75
76
77
78
#include "stream_mqtt.h"

#include <string.h>

int64_t StreamReadMqttString(bstring *buf, Stream *stream)
{
    uint16_t len;
    bstring result;

    if (StreamReadUint16Be(&len, stream) == -1)
        return -1;

    /* We need 1 extra byte for a NULL terminator. bfromcstralloc doesn't do
       any size snapping. */
    result = bfromcstralloc(len+1, "");

    if (!result)
        return -1;

    if (StreamRead(bdata(result), len, stream) == -1)
    {
        bdestroy(result);
        return -1;
    }

    result->slen = len;
    result->data[len] = '\0';

    *buf = result;

    return len+2;
}

int64_t StreamWriteMqttString(const_bstring buf, Stream *stream)
{
    if (StreamWriteUint16Be(blength(buf), stream) == -1)
        return -1;

    if (StreamWrite(bdata(buf), blength(buf), stream) == -1)
        return -1;

    return 2 + blength(buf);
}

int64_t StreamReadRemainingLength(size_t *remainingLength, Stream *stream)
{
    size_t multiplier = 1;
    unsigned char encodedByte;
    *remainingLength = 0;
    do
    {
        if (StreamRead(&encodedByte, 1, stream) != 1)
            return -1;
        *remainingLength += (encodedByte & 127) * multiplier;
        if (multiplier > 128*128*128)
            return -1;
        multiplier *= 128;
    }
    while ((encodedByte & 128) != 0);
    return 0;
}

int64_t StreamWriteRemainingLength(size_t remainingLength, Stream *stream)
{
    size_t nbytes = 0;
    do
    {
        unsigned char encodedByte = remainingLength % 128;
        remainingLength /= 128;
        if (remainingLength > 0)
            encodedByte |= 128;
        if (StreamWrite(&encodedByte, 1, stream) != 1)
            return -1;
        ++nbytes;
    }
    while (remainingLength > 0);
    return nbytes;
}