A client for the SmartREST protocol from Cumulocity.

Dependencies:   SmartRest

Fork of MbedSmartRest by Vincent Wochnik

MbedDataSink.cpp

Committer:
vwochnik
Date:
2014-01-24
Revision:
2:1038411466a6
Child:
13:e76920d5e1ec

File content as of revision 2:1038411466a6:

#include "MbedDataSink.h"
#include <stdlib.h>
#include <stdio.h>

MbedDataSink::MbedDataSink(size_t length)
{
    _len = length;
    _ptr = _buf = (char*)malloc(length);
}

MbedDataSink::~MbedDataSink()
{
    free(_buf);
}

size_t MbedDataSink::write(char c)
{
    if (_ptr - _buf == _len)
        return 0;
    *_ptr++ = c;
    return 1;
}

size_t MbedDataSink::write(void *buf, size_t length)
{
    size_t written = 0;
    char *b = (char*)buf;
    
    while ((length-- > 0) && (write(*b++)))
        written++;

    return written;
}

size_t MbedDataSink::write(const char *str)
{
    size_t written = 0;
    
    for (char c, *p = (char*)str; (c = *p) > 0; ++p) {
        if (!write(c))
            break;
        written++;
    }
    return written;
}

size_t MbedDataSink::write(unsigned long number)
{
    size_t left, len;
    
    left = _len - (_ptr - _buf);
    len = snprintf(_ptr, left, "%ld", number);
    _ptr += len;
    return len;
}

const char * MbedDataSink::buffer()
{
    return _buf;
}

size_t MbedDataSink::length()
{
    return _ptr - _buf;
}