www.pudn.com > NETINFO.rar > CollectLine.cpp
#include "CollectLine.h"
//this class is used to parse CRLF seperated data to individual lines
//usage like this:
// if( object.PutData(data,length) )
// {
// while(object.GetLine(line, lineLen, &writelen))
// {
// process a line......
// }
// if( writelen >= lineLen )
// {
// lineLen is too small to hold a line
// }
// }
CCollectLine::CCollectLine(int bufferSize)
{
m_buffer = new char[bufferSize];
m_bufferSize = bufferSize;
m_count=0;
m_start=0;
}
CCollectLine::~CCollectLine()
{
delete m_buffer;
}
void CCollectLine::ResetContent()
{
m_count = 0;
m_start = 0;
}
//user use this function to put data, if successfully accepted, return TRUE
//else return FALSE
BOOL CCollectLine::PutData(const char* pData, int length)
{
//check size
if( !m_buffer || m_count + length > m_bufferSize )
{
printf("CCollectLine::PutData(): line is too long or buffer is too small\n");
return FALSE;
}
//make data start from begin if end space is not enough to hold data
if( m_start + m_count + length > m_bufferSize )
{
memmove(m_buffer, m_buffer+m_start, m_count);
m_start = 0;
}
//append data
memcpy(m_buffer+m_start+m_count, pData, length);
m_count += length;
return TRUE;
}
//user should repeatedly call this function until return FALSE(no line remained)
//length is length of pData, write returns real count of bytes written
//if there is no line, return FALSE with *write == 0;
//if there is line too large, return FALSE with *write > length
//if there is line properly, return TRUE with *write equal of length of string including
// CRLF and end zero char
BOOL CCollectLine::GetLine(char* pData, int length, int* write, BOOL bEndingWithCRLF)
{
if( !m_buffer || m_count == 0 ) return FALSE;
//look up data for CRLF
for(int i = m_start; i < m_start+m_count-1 && !(m_buffer[i]=='\r' && m_buffer[i+1] == '\n'); i++)NULL;
if( i >= m_start + m_count - 1 ) //not found CRLF, return FALSE
{
*write = 0;
return FALSE;
}
//check size, return FALSE if pData is too small
if( i - m_start + 3 > length )
{
printf("CCollectLine::GetLine(): line size is too small\n");
*write = i - m_start + 3;
return FALSE;
}
//copy data
*write = i - m_start + 3;
memcpy(pData, m_buffer+m_start, i-m_start+2); //include CRLF
pData[i-m_start+2] = 0;
m_count -= i - m_start + 2;
m_start = i+2;
if( !bEndingWithCRLF )
{
(*write) -= 2;
pData[*write - 1] = 0;
}
return TRUE;
}