~ubuntu-branches/ubuntu/vivid/cctools/vivid

« back to all changes in this revision

Viewing changes to dttools/src/buffer.c

  • Committer: Bazaar Package Importer
  • Author(s): Michael Hanke
  • Date: 2011-05-07 09:05:00 UTC
  • Revision ID: james.westby@ubuntu.com-20110507090500-lqpmdtwndor6e7os
Tags: upstream-3.3.2
ImportĀ upstreamĀ versionĀ 3.3.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
Copyright (C) 2005- The University of Notre Dame
 
3
This software is distributed under the GNU General Public License.
 
4
See the file COPYING for details.
 
5
*/
 
6
 
 
7
#include "buffer.h"
 
8
#include "xmalloc.h"
 
9
 
 
10
#include <assert.h>
 
11
#include <stdarg.h>
 
12
#include <stdio.h>
 
13
 
 
14
struct buffer_t {
 
15
  char *buf;
 
16
  size_t size;
 
17
};
 
18
 
 
19
buffer_t *buffer_create (void)
 
20
{
 
21
  buffer_t *b = xxmalloc(sizeof(buffer_t));
 
22
  b->buf = NULL;
 
23
  b->size = 0;
 
24
  return b;
 
25
}
 
26
 
 
27
void buffer_delete (buffer_t *b)
 
28
{
 
29
  free(b->buf);
 
30
  free(b);
 
31
}
 
32
 
 
33
int buffer_vprintf (buffer_t *b, const char *format, va_list va)
 
34
{
 
35
  va_list va2;
 
36
  size_t osize = b->size;
 
37
 
 
38
  va_copy(va2, va);
 
39
  int n = vsnprintf(NULL, 0, format, va2);
 
40
  va_end(va2);
 
41
 
 
42
  if (n < 0) return -1;
 
43
 
 
44
  b->size += n;
 
45
  b->buf = xxrealloc(b->buf, b->size+1); /* extra nul byte */
 
46
  va_copy(va2, va);
 
47
  n = vsnprintf(b->buf+osize, n+1, format, va2);
 
48
  assert(n >= 0);
 
49
  va_end(va2);
 
50
 
 
51
  return 0;
 
52
}
 
53
 
 
54
int buffer_printf (buffer_t *b, const char *format, ...)
 
55
{
 
56
  va_list va;
 
57
  va_start(va, format);
 
58
  int r = buffer_vprintf(b, format, va);
 
59
  va_end(va);
 
60
  return r;
 
61
}
 
62
 
 
63
const char *buffer_tostring (buffer_t *b, size_t *size)
 
64
{
 
65
  if (size != NULL) *size = b->size;
 
66
  return b->buf;
 
67
}