bufstr.h

Go to the documentation of this file.
00001 /******************************************************************************
00002  *
00003  * $Id: bufstr.h,v 1.85 2000/11/18 12:58:19 root Exp $
00004  *
00005  *
00006  * Copyright (C) 1997-2008 by Dimitri van Heesch.
00007  *
00008  * Permission to use, copy, modify, and distribute this software and its
00009  * documentation under the terms of the GNU General Public License is hereby 
00010  * granted. No representations are made about the suitability of this software 
00011  * for any purpose. It is provided "as is" without express or implied warranty.
00012  * See the GNU General Public License for more details.
00013  *
00014  * Documents produced by Doxygen are derivative works derived from the
00015  * input used in their production; they are not affected by this license.
00016  *
00017  */
00018 #ifndef _BUFSTR_H
00019 #define _BUFSTR_H
00020 
00021 #include "qtbc.h"
00022 #include <stdio.h>
00023 #include <stdlib.h>
00024 
00030 class BufStr 
00031 {
00032   public:
00033     BufStr(int size) 
00034       : m_size(size), m_writeOffset(0), m_spareRoom(10240), m_buf(0) 
00035     {
00036       m_buf = (char *)malloc(size);
00037     }
00038     ~BufStr()
00039     {
00040       free(m_buf);
00041     }
00042     void addChar(char c)
00043     {
00044       makeRoomFor(1);
00045       m_buf[m_writeOffset++]=c;
00046     }
00047     void addArray(const char *a,int len)
00048     {
00049       makeRoomFor(len);
00050       memcpy(m_buf+m_writeOffset,a,len);
00051       m_writeOffset+=len;
00052     }
00053     void skip(uint s)
00054     {
00055       makeRoomFor(s);
00056       m_writeOffset+=s;
00057     }
00058     void shrink( uint newlen )
00059     {
00060       m_writeOffset=newlen;
00061       resize(newlen);
00062     }
00063     void resize( uint newlen )
00064     {
00065       m_size=newlen;
00066       if (m_writeOffset>=m_size) // offset out of range -> enlarge
00067       {
00068         m_size=m_writeOffset+m_spareRoom;
00069       }
00070       m_buf = (char *)realloc(m_buf,m_size);
00071     }
00072     char *data() const
00073     {
00074       return m_buf;
00075     }
00076     char &at(uint i) const
00077     {
00078       return m_buf[i];
00079     }
00080     bool isEmpty() const
00081     {
00082       return m_writeOffset==0;
00083     }
00084     operator const char *() const
00085     {
00086       return m_buf;
00087     }
00088     uint curPos() const
00089     { 
00090       return m_writeOffset; 
00091     }
00092   private:
00093     void makeRoomFor(uint size)
00094     {
00095       if (m_writeOffset+size>=m_size) 
00096       {
00097         resize(m_size+size+m_spareRoom);
00098       }
00099     }
00100     uint m_size;
00101     uint m_writeOffset;
00102     const int m_spareRoom; // 10Kb extra room to avoid frequent resizing
00103     char *m_buf;
00104 };
00105 
00106 
00107 #endif



Generated on Mon Mar 31 10:58:32 2008 by  doxygen 1.5.1