view src/io/io_buf.c @ 0:d39e1d0d75b6

initial add
author paulo@hit-nxdomain.opendns.com
date Sat, 20 Feb 2010 21:18:28 -0800
parents
children
line source
1 /*
2 * $Id: io_buf.c,v 1.2 2003/09/17 17:44:11 hipnod Exp $
3 *
4 * Copyright (C) 2003 giFT project (gift.sourceforge.net)
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 */
17 #include "gt_gnutella.h"
19 #include "io_buf.h"
21 /*****************************************************************************/
23 struct io_buf *io_buf_new (size_t size)
24 {
25 struct io_buf *buf;
26 uint8_t *data;
28 if (!(data = gift_malloc (size + 1)))
29 return NULL;
31 if (!(buf = gift_malloc (sizeof (struct io_buf))))
32 {
33 free (data);
34 return NULL;
35 }
37 buf->data = data;
38 buf->size = size;
39 buf->r_offs = 0;
40 buf->w_offs = 0;
42 /* null terminate the buffer */
43 buf->data[size] = 0;
45 return buf;
46 }
48 void io_buf_free (struct io_buf *buf)
49 {
50 uint8_t *data;
52 if (!buf)
53 return;
55 data = io_buf_free_keep (buf);
56 free (data);
57 }
59 uint8_t *io_buf_free_keep (struct io_buf *buf)
60 {
61 uint8_t *data;
63 data = buf->data;
64 free (buf);
66 return data;
67 }
69 /*
70 * Resize the underlying buffer. This includes +1 for the null terminator.
71 */
72 BOOL io_buf_resize (struct io_buf *buf, size_t len)
73 {
74 uint8_t *resized;
76 if (buf->size >= len)
77 return TRUE;
79 if (!(resized = gift_realloc (buf->data, len + 1)))
80 return FALSE;
82 buf->data = resized;
83 buf->size = len;
85 /* ensure null-termination */
86 buf->data[len] = 0;
88 return TRUE;
89 }
91 void io_buf_reset (struct io_buf *buf)
92 {
93 buf->w_offs = 0;
94 buf->r_offs = 0;
95 }
97 void io_buf_push (struct io_buf *buf, size_t len)
98 {
99 assert (len + buf->w_offs <= buf->size);
100 buf->w_offs += len;
101 }
103 void io_buf_pop (struct io_buf *buf, size_t len)
104 {
105 assert (len + buf->r_offs <= buf->w_offs);
106 buf->r_offs += len;
107 }
109 size_t io_buf_copy (struct io_buf *dst, struct io_buf *src, size_t len)
110 {
111 size_t src_avail = io_buf_read_avail (src);
112 size_t dst_avail = io_buf_write_avail (dst);
114 if (len > src_avail)
115 len = src_avail;
117 if (len > dst_avail)
118 len = dst_avail;
120 memcpy (dst->data + dst->w_offs, src->data + src->r_offs, len);
122 dst->w_offs += len;
123 src->r_offs += len;
125 return len;
126 }