]> sjero.net Git - wget/blob - src/rbuf.c
[svn] Initial revision
[wget] / src / rbuf.c
1 /* Buffering read.
2    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
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; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 /* This is a simple implementation of buffering IO-read functions.  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23
24 #include "wget.h"
25 #include "rbuf.h"
26 #include "connect.h"
27
28 void
29 rbuf_initialize (struct rbuf *rbuf, int fd)
30 {
31   rbuf->fd = fd;
32   rbuf->buffer_pos = rbuf->buffer;
33   rbuf->buffer_left = 0;
34 }
35
36 int
37 rbuf_initialized_p (struct rbuf *rbuf)
38 {
39   return rbuf->fd != -1;
40 }
41
42 void
43 rbuf_uninitialize (struct rbuf *rbuf)
44 {
45   rbuf->fd = -1;
46 }
47
48 /* Currently unused -- see RBUF_READCHAR.  */
49 #if 0
50 /* Function version of RBUF_READCHAR.  */
51 int
52 rbuf_readchar (struct rbuf *rbuf, char *store)
53 {
54   return RBUF_READCHAR (rbuf, store);
55 }
56 #endif
57
58 /* Like rbuf_readchar(), only don't move the buffer position.  */
59 int
60 rbuf_peek (struct rbuf *rbuf, char *store)
61 {
62   if (!rbuf->buffer_left)
63     {
64       int res;
65       rbuf->buffer_pos = rbuf->buffer;
66       rbuf->buffer_left = 0;
67       res = iread (rbuf->fd, rbuf->buffer, sizeof (rbuf->buffer));
68       if (res <= 0)
69         return res;
70       rbuf->buffer_left = res;
71     }
72   *store = *rbuf->buffer_pos;
73   return 1;
74 }
75
76 /* Flush RBUF's buffer to WHERE.  Flush MAXSIZE bytes at most.
77    Returns the number of bytes actually copied.  If the buffer is
78    empty, 0 is returned.  */
79 int
80 rbuf_flush (struct rbuf *rbuf, char *where, int maxsize)
81 {
82   if (!rbuf->buffer_left)
83     return 0;
84   else
85     {
86       int howmuch = MINVAL (rbuf->buffer_left, maxsize);
87
88       if (where)
89         memcpy (where, rbuf->buffer_pos, howmuch);
90       rbuf->buffer_left -= howmuch;
91       rbuf->buffer_pos += howmuch;
92       return howmuch;
93     }
94 }
95
96 /* Discard any cached data in RBUF.  */
97 void
98 rbuf_discard (struct rbuf *rbuf)
99 {
100   rbuf->buffer_left = 0;
101   rbuf->buffer_pos = rbuf->buffer;
102 }