Generator: added a test of a float in an array

This commit is contained in:
Benoît Blanchon
2014-06-24 13:53:30 +02:00
parent aa8cff7101
commit 22ca52326c
2 changed files with 64 additions and 12 deletions

View File

@ -5,48 +5,93 @@
#pragma once #pragma once
#include <stdarg.h>
enum JsonObjectType
{
JSON_STRING,
JSON_NUMBER,
};
union JsonObjectValue
{
const char* string;
double number;
};
struct JsonObject
{
JsonObjectType type;
JsonObjectValue value;
};
template<int N> template<int N>
class JsonArray class JsonArray
{ {
public: public:
JsonArray() JsonArray()
{ {
itemCount = 0; itemCount = 0;
} }
void add(const char* data) void add(const char* value)
{ {
if (itemCount < N) if (itemCount >= N) return;
items[itemCount++] = data;
items[itemCount].type = JSON_STRING;
items[itemCount].value.string = value;
itemCount++;
}
void add(double value)
{
if (itemCount >= N) return;
items[itemCount].type = JSON_NUMBER;
items[itemCount].value.number = value;
itemCount++;
} }
void writeTo(char* buffer, size_t bufferSize) void writeTo(char* buffer, size_t bufferSize)
{ {
buffer[0] = 0; buffer[0] = 0;
append("[", buffer, bufferSize); append(buffer, bufferSize, "[");
for (int i = 0; i < itemCount; i++) for (int i = 0; i < itemCount; i++)
{ {
if (i>0) if (i>0)
append(",", buffer, bufferSize); append(buffer, bufferSize, ",");
append("'", buffer, bufferSize); switch (items[i].type)
append(items[i], buffer, bufferSize); {
append("'", buffer, bufferSize); case JSON_STRING:
append(buffer, bufferSize, "'%s'", items[i].value.string);
break;
case JSON_NUMBER:
append(buffer, bufferSize, "%lg", items[i].value.number);
break;
}
} }
append("]", buffer, bufferSize); append(buffer, bufferSize, "]");
} }
private: private:
const char* items[N]; JsonObject items[N];
int itemCount; int itemCount;
void append(const char* source, char* dest, size_t destSize) void append(char* dest, size_t destSize, const char* format, ...)
{ {
int len = strlen(dest); int len = strlen(dest);
strncpy(dest + len, source, destSize - len);
va_list args;
va_start(args, format);
vsnprintf(dest + len, destSize - len, format, args);
va_end(args);
} }
}; };

View File

@ -40,6 +40,13 @@ namespace JsonGeneratorTests
AssertJsonIs("['hello','world']"); AssertJsonIs("['hello','world']");
} }
TEST_METHOD(OneNumber)
{
arr.add(3.14);
AssertJsonIs("[3.14]");
}
void AssertJsonIs(const char* expected) void AssertJsonIs(const char* expected)
{ {
char buffer[256]; char buffer[256];