My Project
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
bufstr.h
Go to the documentation of this file.
1 /******************************************************************************
2  *
3  *
4  *
5  *
6  * Copyright (C) 1997-2015 by Dimitri van Heesch.
7  *
8  * Permission to use, copy, modify, and distribute this software and its
9  * documentation under the terms of the GNU General Public License is hereby
10  * granted. No representations are made about the suitability of this software
11  * for any purpose. It is provided "as is" without express or implied warranty.
12  * See the GNU General Public License for more details.
13  *
14  * Documents produced by Doxygen are derivative works derived from the
15  * input used in their production; they are not affected by this license.
16  *
17  */
18 #ifndef _BUFSTR_H
19 #define _BUFSTR_H
20 
21 #include <qglobal.h>
22 #include <qcstring.h>
23 #include <stdlib.h>
24 
30 class BufStr
31 {
32  public:
33  BufStr(int size)
34  : m_size(size), m_writeOffset(0), m_spareRoom(10240), m_buf(0)
35  {
36  m_buf = (char *)calloc(size,1);
37  }
39  {
40  free(m_buf);
41  }
42  void addChar(char c)
43  {
44  makeRoomFor(1);
45  m_buf[m_writeOffset++]=c;
46  }
47  void addArray(const char *a,int len)
48  {
49  makeRoomFor(len);
50  memcpy(m_buf+m_writeOffset,a,len);
51  m_writeOffset+=len;
52  }
53  void skip(uint s)
54  {
55  makeRoomFor(s);
56  m_writeOffset+=s;
57  }
58  void shrink( uint newlen )
59  {
60  m_writeOffset=newlen;
61  resize(newlen);
62  }
63  void resize( uint newlen )
64  {
65  uint oldsize = m_size;
66  m_size=newlen;
67  if (m_writeOffset>=m_size) // offset out of range -> enlarge
68  {
70  }
71  m_buf = (char *)realloc(m_buf,m_size);
72  if (m_size>oldsize)
73  {
74  memset(m_buf+oldsize,0,m_size-oldsize);
75  }
76  }
77  int size() const
78  {
79  return m_size;
80  }
81  char *data() const
82  {
83  return m_buf;
84  }
85  char &at(uint i) const
86  {
87  return m_buf[i];
88  }
89  bool isEmpty() const
90  {
91  return m_writeOffset==0;
92  }
93  operator const char *() const
94  {
95  return m_buf;
96  }
97  uint curPos() const
98  {
99  return m_writeOffset;
100  }
101  void dropFromStart(uint bytes)
102  {
103  if (bytes>m_size) bytes=m_size;
104  if (bytes>0) qmemmove(m_buf,m_buf+bytes,m_size-bytes);
105  m_size-=bytes;
106  m_writeOffset-=bytes;
107  }
108  private:
109  void makeRoomFor(uint size)
110  {
111  if (m_writeOffset+size>=m_size)
112  {
113  resize(m_size+size+m_spareRoom);
114  }
115  }
116  uint m_size;
118  const int m_spareRoom; // 10Kb extra room to avoid frequent resizing
119  char *m_buf;
120 };
121 
122 
123 #endif