Unit tests for SmartRest
Dependencies: C027 SmartRest mbed
Diff: mock/BufferedDataSink.cpp
- Revision:
- 0:789029e49ea1
diff -r 000000000000 -r 789029e49ea1 mock/BufferedDataSink.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mock/BufferedDataSink.cpp Mon Mar 24 10:12:45 2014 +0000 @@ -0,0 +1,82 @@ +#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; +}