Unit tests for SmartRest

Dependencies:   C027 SmartRest mbed

mock/BufferedDataSink.cpp

Committer:
vwochnik
Date:
2014-03-24
Revision:
0:789029e49ea1

File content as of revision 0:789029e49ea1:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "BufferedDataSink.h"

BufferedDataSink::BufferedDataSink()
{
    _size = BDS_MEMORY_INCREMENT;
    _buffer = (char*)malloc(_size*sizeof(char));
    *_buffer = 0;
    _ptr = _buffer;
}

BufferedDataSink::~BufferedDataSink()
{
    free(_buffer);
}

char * BufferedDataSink::value()
{
    return _buffer;
}

void BufferedDataSink::clear()
{
    _ptr = _buffer;
    *_ptr = 0;
}

size_t BufferedDataSink::write(char c)
{
    ensureMinimumFreeMemory(1);
    *_ptr++ = c;
    *_ptr = 0;
    return 1;
}

size_t BufferedDataSink::write(void *buf, size_t length)
{
    ensureMinimumFreeMemory(length);
    memcpy(_ptr, buf, length);
    _ptr += length;
    *_ptr = 0;
    return length;
}

size_t BufferedDataSink::write(const char *str)
{
    return write((void*)str, strlen(str)*sizeof(char));
}

size_t BufferedDataSink::write(unsigned long number)
{
    size_t length;

    length = snprintf(NULL, 0, "%lu", number);

    ensureMinimumFreeMemory(length);
    length = sprintf(_ptr, "%lu", number);
    _ptr += length;
    return length;
}

void BufferedDataSink::ensureMinimumFreeMemory(size_t required)
{
    size_t size = _size, offset = _ptr - _buffer;

    if (required < BDS_MIN_FREE_MEMORY)
        required = BDS_MIN_FREE_MEMORY;
    else
        required++;

    while (size - offset < required)
        size += BDS_MEMORY_INCREMENT;

    if (size == _size)
        return;

    _size = size;
    _buffer = (char*)realloc(_buffer, _size*sizeof(char));
    _ptr = _buffer + offset;
}