00001 00004 #include "dt_buf.h" 00005 #include <stdlib.h> 00006 #include <string.h> 00007 00008 #ifndef NDEBUG 00009 00010 unsigned dt_buf_instance_count = 0; 00011 #endif 00012 00013 00014 dt_bool dt_buf_init( dt_buf* buf ) 00015 { 00016 enum{ initSize = 32 }; 00017 dt_byte* begin = (dt_byte*)malloc(initSize); 00018 if( ! begin ) 00019 return 0; 00020 buf->begin = begin; 00021 buf->strEnd = begin; 00022 buf->allocEnd = begin + initSize; 00023 #ifndef NDEBUG 00024 ++ dt_buf_instance_count; 00025 #endif 00026 return 1; 00027 } 00028 00029 dt_bool dt_buf_init_data( dt_buf* buf, dt_byte const* data, size_t len ) 00030 { 00031 dt_byte* begin = (dt_byte*)malloc(len); 00032 if( ! begin ) 00033 return 0; 00034 memcpy( begin, data, len ); 00035 buf->begin = begin; 00036 buf->strEnd = buf->allocEnd = begin + len; 00037 #ifndef NDEBUG 00038 ++ dt_buf_instance_count; 00039 #endif 00040 return 1; 00041 } 00042 00043 00044 00045 void dt_buf_free( dt_buf* buf ) 00046 { 00047 free( buf->begin ); 00048 #ifndef NDEBUG 00049 -- dt_buf_instance_count; 00050 #endif 00051 } 00052 00053 void dt_buf_clear( dt_buf* buf ) 00054 { buf->strEnd = buf->begin; } 00055 00056 00057 dt_bool dt_buf_append( dt_buf* buf, int c ) 00058 { 00059 if( buf->strEnd == buf->allocEnd ) 00060 { 00061 size_t oldSize = buf->strEnd - buf->begin; 00062 size_t newSize = (oldSize==0) ? 32 : (2*oldSize); 00063 dt_byte* newAddr = (dt_byte*)realloc( buf->begin, newSize ); 00064 if( newAddr==0 ) 00065 return 0; 00066 buf->begin = newAddr; 00067 buf->strEnd = newAddr+oldSize; 00068 buf->allocEnd = newAddr+newSize; 00069 } 00070 00071 * buf->strEnd++ = c; 00072 return 1; 00073 } 00074 00075 00076 dt_bool dt_buf_growth_reserve( dt_buf* buf, unsigned len ) 00077 { 00078 size_t avail = buf->allocEnd - buf->strEnd; 00079 if( len > avail ) 00080 { 00081 dt_byte* newAddr; 00082 size_t oldSize = buf->strEnd - buf->begin; 00083 size_t newSize = (oldSize==0) ? 32 : (2*oldSize); 00084 if( newSize < oldSize+len ) newSize = oldSize+len; 00085 newAddr = (dt_byte*)realloc( buf->begin, newSize ); 00086 if( newAddr==0 ) 00087 return 0; 00088 buf->begin = newAddr; 00089 buf->strEnd = newAddr+oldSize; 00090 buf->allocEnd = newAddr+newSize; 00091 } 00092 return 1; 00093 } 00094 00095 00096 dt_bool dt_buf_append_data( dt_buf* buf, void const* data, unsigned len ) 00097 { 00098 if( ! dt_buf_growth_reserve( buf, len ) ) 00099 return 0; 00100 memcpy( buf->strEnd, data, len ); 00101 buf->strEnd += len; 00102 return 1; 00103 } 00104 00105 00106 00107 00108