dol: initial dol commit
[jump.git] / dol / src / dol / visitor / hdsd / scd / scd_command_writer.cpp
1 #include "scd_command_writer.h"
2
3 #include <string.h>
4
5 #include "scd_logging.h"
6
7
8 scd_command_writer::scd_command_writer():
9     _is_writing(false), _remaining(0) {}
10
11
12 scd_command_writer::~scd_command_writer()
13 {
14     std::list<scd_command*>::iterator iter;
15     for ( iter = _commands.begin(); iter != _commands.end(); iter++)
16         delete *iter;
17 }
18
19
20 void scd_command_writer::set_socket(scd_socket& sock) { _socket = &sock; }
21
22
23 bool scd_command_writer::is_writing() const { return _is_writing; }
24
25
26 bool scd_command_writer::queue_command(scd_command* cmd)
27 {
28     if (cmd->_msglen <= SCD_CM_MAXLEN)
29     {
30         _commands.push_back(cmd);
31         _is_writing = true;
32         return true;
33     }
34     else
35     {
36         scd_warn("command too long");
37         delete cmd;
38         return false;
39     }
40 }
41
42 void scd_command_writer::write()
43 {
44     bool finishedmsg;
45     do
46     {
47         finishedmsg = _send_cmd();
48     }
49     while (finishedmsg);
50
51 } // write()
52
53
54 inline bool scd_command_writer::_send_cmd()
55 {
56     if (!_is_writing)
57         return false;
58
59     if (_remaining == 0)
60     {
61         /* fetch next command */
62         scd_command* cmd = _commands.front();
63         _commands.pop_front();
64
65         // store header to buffer
66         uint16_t* intbuf = reinterpret_cast<uint16_t*>(_buf);
67         intbuf[0] = htons(cmd->_type);
68         intbuf[1] = htons(cmd->_subtype);
69         intbuf[2] = htons(cmd->_msglen);
70
71         // store message to buffer
72         memcpy(_buf + SCD_CM_HEADER, cmd->_msg, cmd->_msglen);
73
74         _remaining = SCD_CM_HEADER + cmd->_msglen;
75         _off = 0;
76         delete cmd;
77     }
78
79     size_t sent = _socket->send(_buf + _off, _remaining);
80
81     _off += sent;
82     _remaining -= sent;
83
84     if (_remaining == 0)
85     {
86         if (_commands.empty())
87             _is_writing = false;
88         return true;
89     }
90     else
91         return false;
92     
93 } // _send_cmd()