Skip to content

Commit

Permalink
Test that DynamicJsonBuffer can't alloc more than BLOCK_CAPACITY
Browse files Browse the repository at this point in the history
  • Loading branch information
bblanchon committed Dec 13, 2014
1 parent ada588c commit 3cd6f66
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
9 changes: 8 additions & 1 deletion include/ArduinoJson/DynamicJsonBuffer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,21 @@ class DynamicJsonBuffer : public JsonBuffer {

size_t size() const { return _size; }

static const size_t BLOCK_CAPACITY = 32;

protected:
virtual void* alloc(size_t bytes) {
if (bytes > BLOCK_CAPACITY) return NULL;
void* p = _buffer + _size;
_size += bytes;
return p;
}

static const size_t BLOCK_CAPACITY = 32;
bool canStore(size_t bytes) {
// by design a DynamicJsonBuffer can't alloc a block bigger than
// BLOCK_CAPACITY
return bytes < BLOCK_CAPACITY;
}

size_t _size;
uint8_t _buffer[BLOCK_CAPACITY];
Expand Down
22 changes: 16 additions & 6 deletions test/DynamicJsonBuffer_Basic_Tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,24 @@ TEST_F(DynamicJsonBuffer_Basic_Tests, InitialSizeIsZero) {
}

TEST_F(DynamicJsonBuffer_Basic_Tests, GrowsAfterAlloc) {
buffer.alloc(100);
ASSERT_EQ(100, buffer.size());
buffer.alloc(100);
ASSERT_EQ(200, buffer.size());
buffer.alloc(1);
ASSERT_EQ(1, buffer.size());
buffer.alloc(1);
ASSERT_EQ(2, buffer.size());
}

TEST_F(DynamicJsonBuffer_Basic_Tests, CanAllocLessThanBlockCapacity) {
void* p = buffer.alloc(DynamicJsonBuffer::BLOCK_CAPACITY);
ASSERT_TRUE(p);
}

TEST_F(DynamicJsonBuffer_Basic_Tests, CantAllocMoreThanBlockCapacity) {
void* p = buffer.alloc(DynamicJsonBuffer::BLOCK_CAPACITY + 1);
ASSERT_FALSE(p);
}

TEST_F(DynamicJsonBuffer_Basic_Tests, ReturnDifferentPointer) {
void* p1 = buffer.alloc(100);
void* p2 = buffer.alloc(200);
void* p1 = buffer.alloc(1);
void* p2 = buffer.alloc(2);
ASSERT_NE(p1, p2);
}

0 comments on commit 3cd6f66

Please sign in to comment.