00001 /* Copyright (C) 2003 MySQL AB 00002 00003 This program is free software; you can redistribute it and/or modify 00004 it under the terms of the GNU General Public License as published by 00005 the Free Software Foundation; either version 2 of the License, or 00006 (at your option) any later version. 00007 00008 This program is distributed in the hope that it will be useful, 00009 but WITHOUT ANY WARRANTY; without even the implied warranty of 00010 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00011 GNU General Public License for more details. 00012 00013 You should have received a copy of the GNU General Public License 00014 along with this program; if not, write to the Free Software 00015 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ 00016 00017 #ifndef __BUFFER_HPP_INCLUDED__ 00018 #define __BUFFER_HPP_INCLUDED__ 00019 00020 #include <ndb_global.h> 00021 00022 /* This class represents a buffer of binary data, where you can append 00023 * data at the end, and later read the entire bunch. 00024 * It will take care of the hairy details of realloc()ing the space 00025 * for you 00026 */ 00027 class UtilBuffer { 00028 public: 00029 UtilBuffer() { data = NULL; len = 0; alloc_size = 0; }; 00030 ~UtilBuffer() { if(data) free(data); data = NULL; len = 0; alloc_size = 0; }; 00031 00032 00033 int reallocate(size_t newsize) { 00034 if(newsize < len) { 00035 errno = EINVAL; 00036 return -1; 00037 } 00038 void *newdata; 00039 if((newdata = realloc(data, newsize)) == NULL) { 00040 errno = ENOMEM; 00041 return -1; 00042 } 00043 alloc_size = newsize; 00044 data = newdata; 00045 return 0; 00046 }; 00047 00048 int grow(size_t l) { 00049 if(l > alloc_size) 00050 return reallocate(l); 00051 return 0; 00052 }; 00053 00054 int append(const void *d, size_t l) { 00055 int ret; 00056 ret = grow(len+l); 00057 if(ret != 0) 00058 return ret; 00059 00060 memcpy((char *)data+len, d, l); 00061 len+=l; 00062 00063 return 0; 00064 }; 00065 00066 void * append(size_t l){ 00067 if(grow(len+l) != 0) 00068 return 0; 00069 00070 void * ret = (char*)data+len; 00071 len += l; 00072 return ret; 00073 } 00074 00075 int assign(const void * d, size_t l) { 00076 if (data) free(data); 00077 data = NULL; 00078 len = 0; 00079 alloc_size = 0; 00080 return append(d, l); 00081 } 00082 00083 void clear() { 00084 len = 0; 00085 } 00086 00087 int length() const { return len; } 00088 00089 void *get_data() const { return data; } 00090 00091 bool empty () const { return len == 0; } 00092 private: 00093 void *data; /* Pointer to data storage */ 00094 size_t len; /* Size of the stored data */ 00095 size_t alloc_size; /* Size of the allocated space, 00096 * i.e. len can grow to this size */ 00097 }; 00098 00099 #endif /* !__BUFFER_HPP_INCLUDED__ */
1.4.7

