Files
ArduinoJson/JsonGenerator/JsonObjectBase.cpp

92 lines
1.7 KiB
C++
Raw Permalink Normal View History

2014-07-08 21:29:19 +02:00
/*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/
2014-07-22 21:02:16 +02:00
#include "JsonObjectBase.h"
2014-08-02 16:25:18 +02:00
#include <string.h> // for strcmp
using namespace ArduinoJson::Generator;
using namespace ArduinoJson::Internals;
JsonValue JsonObjectBase::nullValue;
2014-07-22 21:02:16 +02:00
size_t JsonObjectBase::printTo(Print& p) const
{
size_t n = 0;
n += p.write('{');
2014-07-08 21:29:19 +02:00
// NB: the code has been optimized for a small size on a 8-bit AVR
const KeyValuePair* current = items;
for (int i = count; i > 0; i--)
{
2014-08-01 15:32:05 +02:00
n += EscapedString::printTo(current->key, p);
n += p.write(':');
n += current->value.printTo(p);
current++;
if (i > 1)
{
n += p.write(',');
}
}
n += p.write('}');
return n;
2014-07-31 18:50:01 +02:00
}
2014-08-03 13:09:07 +02:00
JsonObjectBase::KeyValuePair* JsonObjectBase::getMatchingPair(JsonKey key) const
2014-07-31 18:50:01 +02:00
{
KeyValuePair* p = items;
for (int i = count; i > 0; --i)
2014-07-31 18:50:01 +02:00
{
2014-08-02 16:25:18 +02:00
if (!strcmp(p->key, key))
return p;
p++;
2014-07-31 18:50:01 +02:00
}
2014-08-02 16:25:18 +02:00
return 0;
}
2014-08-03 13:09:07 +02:00
JsonValue& JsonObjectBase::operator[](JsonKey key)
2014-08-02 16:25:18 +02:00
{
KeyValuePair* match = getMatchingPair(key);
2014-08-02 16:25:18 +02:00
if (match)
return match->value;
2014-08-03 13:09:07 +02:00
JsonValue* value;
if (count < capacity)
{
2014-08-02 16:25:18 +02:00
items[count].key = key;
value = &items[count].value;
count++;
}
else
{
value = &nullValue;
}
value->reset();
return *value;
2014-08-02 16:11:02 +02:00
}
2014-08-03 13:09:07 +02:00
bool JsonObjectBase::containsKey(JsonKey key) const
2014-08-02 16:11:02 +02:00
{
2014-08-02 16:25:18 +02:00
return getMatchingPair(key) != 0;
2014-08-03 13:16:35 +02:00
}
void JsonObjectBase::remove(JsonKey key)
{
KeyValuePair* match = getMatchingPair(key);
if (match == 0) return;
*match = items[--count];
}