Rocco Rutte:
[apps/madmutt.git] / buffer.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9 #if HAVE_CONFIG_H
10 #include "config.h"
11 #endif
12
13 #include <stdlib.h>
14 #include <string.h>
15
16 #include "buffer.h"
17
18 #include "lib/mem.h"
19 #include "lib/str.h"
20
21 /*
22  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
23  * just initializes. Frees anything already in the buffer.
24  *
25  * Disregards the 'destroy' flag, which seems reserved for caller.
26  * This is bad, but there's no apparent protocol for it.
27  */
28 BUFFER *mutt_buffer_init (BUFFER * b)
29 {
30   if (!b) {
31     b = mem_malloc (sizeof (BUFFER));
32     if (!b)
33       return NULL;
34   }
35   else {
36     mem_free(&b->data);
37   }
38   memset (b, 0, sizeof (BUFFER));
39   return b;
40 }
41
42 /*
43  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
44  * just initializes. Frees anything already in the buffer. Copies in
45  * the seed string.
46  *
47  * Disregards the 'destroy' flag, which seems reserved for caller.
48  * This is bad, but there's no apparent protocol for it.
49  */
50 BUFFER *mutt_buffer_from (BUFFER * b, char *seed)
51 {
52   if (!seed)
53     return NULL;
54
55   b = mutt_buffer_init (b);
56   b->data = str_dup (seed);
57   b->dsize = str_len (seed);
58   b->dptr = (char *) b->data + b->dsize;
59   return b;
60 }
61
62 void mutt_buffer_addstr (BUFFER * buf, const char *s)
63 {
64   mutt_buffer_add (buf, s, str_len (s));
65 }
66
67 void mutt_buffer_addch (BUFFER * buf, char c)
68 {
69   mutt_buffer_add (buf, &c, 1);
70 }
71
72 void mutt_buffer_free (BUFFER ** p)
73 {
74   if (!p || !*p)
75     return;
76
77   mem_free (&(*p)->data);
78   /* dptr is just an offset to data and shouldn't be freed */
79   mem_free (p);
80 }
81
82 /* dynamically grows a BUFFER to accomodate s, in increments of 128 bytes.
83  * Always one byte bigger than necessary for the null terminator, and
84  * the buffer is always null-terminated */
85 void mutt_buffer_add (BUFFER * buf, const char *s, size_t len)
86 {
87   size_t offset;
88
89   if (buf->dptr + len + 1 > buf->data + buf->dsize) {
90     offset = buf->dptr - buf->data;
91     buf->dsize += len < 128 ? 128 : len + 1;
92     mem_realloc ((void **) &buf->data, buf->dsize);
93     buf->dptr = buf->data + offset;
94   }
95   memcpy (buf->dptr, s, len);
96   buf->dptr += len;
97   *(buf->dptr) = '\0';
98 }