Files
ArduinoJson/src/JsonArray.cpp

95 lines
2.2 KiB
C++
Raw Normal View History

2014-10-23 23:39:22 +02:00
// Copyright Benoit Blanchon 2014
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
#include "ArduinoJson/JsonArray.hpp"
2014-10-29 14:24:34 +01:00
2014-10-30 14:03:33 +01:00
#include <new> // required for placement new
2014-10-29 14:24:34 +01:00
#include "ArduinoJson/JsonBuffer.hpp"
#include "ArduinoJson/JsonObject.hpp"
2014-11-03 12:32:47 +01:00
#include "ArduinoJson/Internals/CompactJsonWriter.hpp"
#include "ArduinoJson/Internals/PrettyJsonWriter.hpp"
2014-10-16 16:25:42 +02:00
2014-10-18 23:05:54 +02:00
using namespace ArduinoJson;
using namespace ArduinoJson::Internals;
2014-10-30 14:03:33 +01:00
JsonArray JsonArray::_invalid(NULL);
2014-10-29 14:24:34 +01:00
int JsonArray::size() const {
int nodeCount = 0;
for (JsonArrayNode *node = _firstNode; node; node = node->next) nodeCount++;
return nodeCount;
}
2014-10-30 14:03:33 +01:00
JsonValue &JsonArray::at(int index) const {
2014-10-29 14:24:34 +01:00
JsonArrayNode *node = _firstNode;
while (node && index--) node = node->next;
return node ? node->value : JsonValue::invalid();
}
JsonValue &JsonArray::add() {
2014-10-30 14:03:33 +01:00
JsonArrayNode *node = createNode();
2014-10-29 14:24:34 +01:00
if (!node) return JsonValue::invalid();
addNode(node);
return node->value;
}
2014-10-30 14:03:33 +01:00
JsonArrayNode *JsonArray::createNode() {
2014-10-30 15:31:27 +01:00
if (!_buffer) return NULL;
2014-10-30 14:03:33 +01:00
void *ptr = _buffer->alloc(sizeof(JsonArrayNode));
return ptr ? new (ptr) JsonArrayNode() : NULL;
}
2014-10-29 14:24:34 +01:00
void JsonArray::addNode(JsonArrayNode *newNode) {
if (_firstNode) {
JsonArrayNode *lastNode = _firstNode;
while (lastNode->next) lastNode = lastNode->next;
lastNode->next = newNode;
} else {
_firstNode = newNode;
}
}
2014-10-27 22:50:50 +01:00
2014-10-29 14:24:34 +01:00
JsonArray &JsonArray::createNestedArray() {
if (!_buffer) return JsonArray::invalid();
JsonArray &array = _buffer->createArray();
add(array);
return array;
2014-10-16 16:25:42 +02:00
}
2014-10-29 14:24:34 +01:00
JsonObject &JsonArray::createNestedObject() {
if (!_buffer) return JsonObject::invalid();
JsonObject &object = _buffer->createObject();
add(object);
return object;
2014-10-16 16:25:42 +02:00
}
2014-11-03 12:32:47 +01:00
template <typename T>
void JsonArray::writeTo(T &writer) const {
2014-10-29 14:24:34 +01:00
JsonArrayNode *child = _firstNode;
if (child) {
writer.beginArray();
for (;;) {
child->value.writeTo(writer);
child = child->next;
if (!child) break;
writer.writeComma();
}
writer.endArray();
} else {
writer.writeEmptyArray();
}
}
2014-11-03 12:32:47 +01:00
template void JsonArray::writeTo<CompactJsonWriter>(CompactJsonWriter &) const;
template void JsonArray::writeTo<PrettyJsonWriter>(PrettyJsonWriter &) const;