}
#endif
-/* ---------------------------------
-*/
+/*
+ * Return all bytes up to count from dsi->buffer if there are any buffered there
+ */
static size_t from_buf(DSI *dsi, u_int8_t *buf, size_t count)
{
size_t nbe = 0;
return nbe;
}
+/*
+ * Get bytes from buffer dsi->buffer or read from socket
+ *
+ * 1. Check if there are bytes in the the dsi->buffer buffer.
+ * 2. Return bytes from (1) if yes.
+ * Note: this may return fewer bytes then requested in count !!
+ * 3. If the buffer was empty, read from the socket.
+ */
static ssize_t buf_read(DSI *dsi, u_int8_t *buf, size_t count)
{
ssize_t nbe;
if (!count)
return 0;
- nbe = from_buf(dsi, buf, count);
+ nbe = from_buf(dsi, buf, count); /* 1. */
if (nbe)
- return nbe;
+ return nbe; /* 2. */
- return read(dsi->socket, buf, count);
-
+ return read(dsi->socket, buf, count); /* 3. */
}
-/* ---------------------------------------
- * read raw data. return actual bytes read. this will wait until
- * it gets length bytes
+/*
+ * Essentially a loop around buf_read() to ensure "length" bytes are read
+ * from dsi->buffer and/or the socket.
*/
size_t dsi_stream_read(DSI *dsi, void *data, const size_t length)
{
return stored;
}
-/* ---------------------------------------
- * read raw data. return actual bytes read. this will wait until
- * it gets length bytes
+/*
+ * Get "length" bytes from buffer and/or socket. In order to avoid frequent small reads
+ * this tries to read larger chunks (8192 bytes) into a buffer.
*/
static size_t dsi_buffered_stream_read(DSI *dsi, u_int8_t *data, const size_t length)
{
size_t buflen;
dsi_init_buffer(dsi);
- len = from_buf(dsi, data, length);
+ len = from_buf(dsi, data, length); /* read from buffer dsi->buffer */
dsi->read_count += len;
- if (len == length) {
- return len;
+ if (len == length) { /* got enough bytes from there ? */
+ return len; /* yes */
}
-
+
+ /* fill the buffer with 8192 bytes or until buffer is full */
buflen = min(8192, dsi->end - dsi->eof);
if (buflen > 0) {
ssize_t ret;
if (ret > 0)
dsi->eof += ret;
}
- return dsi_stream_read(dsi, data, length -len);
+
+ /* now get the remaining data */
+ len += dsi_stream_read(dsi, data + len, length - len);
+ return len;
}
/* ---------------------------------------