v2_encoder.cpp 2.23 KB
Newer Older
1
/*
2
    Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
3 4 5 6

    This file is part of 0MQ.

    0MQ is free software; you can redistribute it and/or modify it under
7
    the terms of the GNU Lesser General Public License as published by
8 9 10 11 12 13
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    0MQ is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
    GNU Lesser General Public License for more details.
15

16
    You should have received a copy of the GNU Lesser General Public License
17 18 19
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

20 21
#include "v2_protocol.hpp"
#include "v2_encoder.hpp"
22
#include "likely.hpp"
23 24
#include "wire.hpp"

25 26
zmq::v2_encoder_t::v2_encoder_t (size_t bufsize_) :
    encoder_base_t <v2_encoder_t> (bufsize_)
27 28
{
    //  Write 0 bytes to the batch and go to message_ready state.
29
    next_step (NULL, 0, &v2_encoder_t::message_ready, true);
30 31
}

32
zmq::v2_encoder_t::~v2_encoder_t ()
33 34 35
{
}

36
void zmq::v2_encoder_t::message_ready ()
37
{
38 39 40
    //  Encode flags.
    unsigned char &protocol_flags = tmpbuf [0];
    protocol_flags = 0;
41
    if (in_progress->flags () & msg_t::more)
42
        protocol_flags |= v2_protocol_t::more_flag;
43
    if (in_progress->size () > 255)
44
        protocol_flags |= v2_protocol_t::large_flag;
45 46
    if (in_progress->flags () & msg_t::command)
        protocol_flags |= v2_protocol_t::command_flag;
47

48 49 50
    //  Encode the message length. For messages less then 256 bytes,
    //  the length is encoded as 8-bit unsigned integer. For larger
    //  messages, 64-bit unsigned integer in network byte order is used.
51
    const size_t size = in_progress->size ();
52 53 54
    if (unlikely (size > 255)) {
        put_uint64 (tmpbuf + 1, size);
        next_step (tmpbuf, 9, &v2_encoder_t::size_ready, false);
55 56
    }
    else {
57 58
        tmpbuf [1] = static_cast <uint8_t> (size);
        next_step (tmpbuf, 2, &v2_encoder_t::size_ready, false);
59 60
    }
}
61

62
void zmq::v2_encoder_t::size_ready ()
63 64
{
    //  Write message body into the buffer.
65 66
    next_step (in_progress->data (), in_progress->size (),
        &v2_encoder_t::message_ready, true);
67
}