MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
SocketInputStream2.cpp
1 /* Copyright 2008 Sun Microsystems, Inc.
2  All rights reserved. Use is subject to license terms.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
16 
17 #include <SocketInputStream2.hpp>
18 
19 #include <NdbOut.hpp>
20 
21 bool
22 SocketInputStream2::gets(BaseString& str)
23 {
24  if (get_buffered_line(str))
25  return true;
26 
27  char buf[16];
28  do {
29  ssize_t read_res = read_socket(buf, sizeof(buf));
30  if (read_res == -1)
31  return false;
32 
33  if (!add_buffer(buf, read_res))
34  return false;
35 
36  if (get_buffered_line(str))
37  return true;
38 
39  } while(true);
40 
41  abort(); // Should never come here
42  return false;
43 };
44 
45 
46 bool
47 SocketInputStream2::has_data_to_read()
48 {
49  const int res = ndb_poll(m_socket, true, false, false,
50  m_read_timeout * 1000);
51 
52  if (res == 1)
53  return true; // Yes, there was data
54 
55  if (res == 0)
56  return false; // Timeout occured
57 
58  assert(res == -1);
59  return false;
60 }
61 
62 
63 ssize_t
64 SocketInputStream2::read_socket(char* buf, size_t len)
65 {
66  if (!has_data_to_read())
67  return -1;
68 
69  size_t read_res = my_recv(m_socket, buf, len, 0);
70  if (read_res == 0)
71  return -1; // Has data to read but only EOF received
72 
73  return read_res;
74 }
75 
76 
77 bool
78 SocketInputStream2::get_buffered_line(BaseString& str)
79 {
80  char *start, *ptr;
81  char *end = (char*)m_buffer.get_data() + m_buffer.length();
82  start = ptr =(char*)m_buffer.get_data() + m_buffer_read_pos;
83 
84  while(ptr && ptr < end && *ptr)
85  {
86  if (*ptr == '\n')
87  {
88  size_t len = ptr-start;
89  /* Found end of line, return this part of the buffer */
90  str.assign(start, len);
91 
92  /*
93  Set new read position in buffer, increase with
94  one to step past '\n'
95  */
96  m_buffer_read_pos += (len + 1);
97 
98  return true;
99  }
100  ptr++;
101  }
102  return false;
103 }
104 
105 
106 bool
107 SocketInputStream2::add_buffer(char* buf, ssize_t len)
108 {
109  // ndbout_c("add_buffer: '%.*s'", len, buf);
110  if (m_buffer.append(buf, len) != 0)
111  return false;
112  return true;
113 }