File: strings_buffer.c

package info (click to toggle)
docbook2x 0.8.8-8
  • links: PTS, VCS
  • area: main
  • in suites: lenny, squeeze, wheezy
  • size: 4,532 kB
  • ctags: 321
  • sloc: xml: 16,229; sh: 3,684; perl: 3,445; ansic: 639; makefile: 404; sed: 11
file content (72 lines) | stat: -rw-r--r-- 1,414 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "strings_buffer.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define max(a,b) ((a) > (b)? (a) : (b))

static void *
mallocc(size_t size)
{
    void *p = malloc(size);
    if(p == NULL) {
        fprintf(stderr, "out of memory\n");
        abort();
    }
    return p;
}
        
static struct strings_section *
strings_buffer_new2(size_t size, struct strings_section *ss)
{
    struct strings_section *p;
    p = mallocc(sizeof(struct strings_section));
    
    p->cur_size = p->size = size;
    p->cur = p->start = mallocc(size);
    p->next = ss;

    return p;
}

struct strings_section *
strings_buffer_new(size_t size)
{
    return strings_buffer_new2(size, NULL);
}

void
strings_buffer_delete(struct strings_section *ss)
{
    while(ss != NULL) {
        struct strings_section *p = ss;
        ss = ss->next;
        free(p->start);
        free(p);
    }
}

char *
strings_buffer_add(struct strings_section **ss, const char *s)
{
    struct strings_section *p;
    size_t len = strlen(s)+1;

    for(p=*ss; p != NULL; p=p->next) {
        if(p->cur_size >= len) {
            strcpy(p->cur, s);
            p->cur += len;
            p->cur_size -= len;
            return (p->cur - len);
        }
    }
    
    p = strings_buffer_new2(max((*ss)->size, len), *ss);
    strcpy(p->cur, s);
    p->cur += len;
    p->cur_size -= len;
    *ss = p;
    return (p->cur - len);
}