summaryrefslogtreecommitdiffstats
path: root/src/growbuf.h
blob: bf6d74e510ee1cf7ad1837e75f7f4343669b65e8 (plain)
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
#ifndef GROWBUF_H
#define GROWBUF_H

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

#define GROW_AMOUNT 1024

/** Class representing a string buffer optimised for growing. */
class GrowBuf
{
  public:
    GrowBuf() : str(0), pos(0), len(0) {}
    GrowBuf(int initialSize) : pos(0), len(initialSize) { str=(char*)malloc(len); }
   ~GrowBuf()         { free(str); str=0; pos=0; len=0; }
    void clear()      { pos=0; }
    void addChar(char c)  { if (pos>=len) { len+=GROW_AMOUNT; str = (char*)realloc(str,len); } 
                        str[pos++]=c; 
                      }
    void addStr(const QCString &s) {
                        if (!s.isEmpty())
                        {
                          int l=s.length();
                          if (pos+l>=len) { len+=l+GROW_AMOUNT; str = (char*)realloc(str,len); }
                          strcpy(&str[pos],s.data());
                          pos+=l;
                        }
                      }
    void addStr(const char *s) {
                        if (s)
                        {
                          int l=strlen(s);
                          if (pos+l>=len) { len+=l+GROW_AMOUNT; str = (char*)realloc(str,len); }
                          strcpy(&str[pos],s);
                          pos+=l;
                        }
                      }
    void addStr(const char *s,int n) {
                        if (s)
                        {
                          int l=strlen(s);
                          if (n<l) l=n;
                          if (pos+l>=len) { len+=l+GROW_AMOUNT; str = (char*)realloc(str,len); }
                          strncpy(&str[pos],s,n);
                          pos+=l;
                        }
                      }
    const char *get()     { return str; }
    int getPos() const    { return pos; }
    void setPos(const int newPos) { pos = newPos; }
    char at(int i) const  { return str[i]; }
  private:
    char *str;
    int pos;
    int len;
};

#endif