A client for the SmartREST protocol from Cumulocity.

Dependencies:   HTTPClient SmartRest

HTTPBuffer.cpp

Committer:
vwochnik
Date:
2014-04-02
Revision:
12:788dd934f283
Parent:
3:ce2f116369bd

File content as of revision 12:788dd934f283:

#include "HTTPBuffer.h"
#include <stdlib.h>
#include <string.h>

HTTPBuffer::HTTPBuffer()
{
    _rptr = _wptr = _buf = NULL;
    bufferSize(HTTPBUFFER_INITIAL_SIZE);
}

HTTPBuffer::~HTTPBuffer()
{
    if (_buf != NULL)
        free(_buf);
}

char HTTPBuffer::read()
{
    if (_rptr == _wptr)
        return 0;
    return *_rptr++;
}

uint8_t HTTPBuffer::status()
{
    if (_rptr == _wptr)
        return DS_STATUS_CLOSED;
    return DS_STATUS_OK;
}

void HTTPBuffer::writeReset()
{
    _rptr = _wptr = _buf;
    bufferSize(HTTPBUFFER_INITIAL_SIZE);
}

int HTTPBuffer::write(const char* buf, size_t len)
{
    if (_wptr - _buf + len > _len) {
        size_t newLen = _len;
        while (_wptr - _buf + len > newLen)
            newLen += HTTPBUFFER_INCREMENT;
        bufferSize(newLen);
    }
    memcpy(_wptr, buf, len);
    _wptr += len;
}

void HTTPBuffer::setDataType(const char* type)
{
}

void HTTPBuffer::setIsChunked(bool chunked)
{
}

void HTTPBuffer::setDataLen(size_t len)
{
    bufferSize(len);
}


void HTTPBuffer::bufferSize(size_t length)
{
    if (_len == length)
        return;
    
    char *buf = (char*)realloc(_buf, length);
    if (buf == NULL)
        return;
    
    // set pointers
    _wptr = buf + (_wptr - _buf);
    _rptr = buf + (_rptr - _buf);
    _buf = buf;

    _len = length;
}