1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "mojo/public/bindings/lib/bindings_serialization.h"
6 #include "mojo/public/bindings/lib/buffer.h"
7 #include "mojo/public/environment/environment.h"
8 #include "testing/gtest/include/gtest/gtest.h"
13 bool IsZero(void* p_buf, size_t size) {
14 char* buf = reinterpret_cast<char*>(p_buf);
15 for (size_t i = 0; i < size; ++i) {
22 // Tests small and large allocations in ScratchBuffer.
23 TEST(ScratchBufferTest, Basic) {
26 // Test that a small allocation is placed on the stack.
27 internal::ScratchBuffer buf;
28 void* small = buf.Allocate(10);
29 EXPECT_TRUE(small >= &buf && small < (&buf + sizeof(buf)));
30 EXPECT_TRUE(IsZero(small, 10));
32 // Large allocations won't be on the stack.
33 void* large = buf.Allocate(100*1024);
34 EXPECT_TRUE(IsZero(large, 100*1024));
35 EXPECT_FALSE(large >= &buf && large < (&buf + sizeof(buf)));
37 // But another small allocation should be back on the stack.
38 small = buf.Allocate(10);
39 EXPECT_TRUE(IsZero(small, 10));
40 EXPECT_TRUE(small >= &buf && small < (&buf + sizeof(buf)));
43 // Tests that Buffer::current() returns the correct value.
44 TEST(ScratchBufferTest, Stacked) {
47 EXPECT_FALSE(Buffer::current());
50 internal::ScratchBuffer a;
51 EXPECT_EQ(&a, Buffer::current());
54 internal::ScratchBuffer b;
55 EXPECT_EQ(&b, Buffer::current());
59 EXPECT_FALSE(Buffer::current());
62 // Tests that FixedBuffer allocates memory aligned to 8 byte boundaries.
63 TEST(FixedBufferTest, Alignment) {
66 internal::FixedBuffer buf(internal::Align(10) * 2);
67 ASSERT_EQ(buf.size(), 16u * 2);
69 void* a = buf.Allocate(10);
71 EXPECT_TRUE(IsZero(a, 10));
72 EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(a) % 8);
74 void* b = buf.Allocate(10);
76 EXPECT_TRUE(IsZero(b, 10));
77 EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(b) % 8);
79 // Any more allocations would result in an assert, but we can't test that.
82 // Tests that FixedBuffer::Leak passes ownership to the caller.
83 TEST(FixedBufferTest, Leak) {
89 internal::FixedBuffer buf(8);
90 ASSERT_EQ(8u, buf.size());
92 ptr = buf.Allocate(8);
94 void* buf_ptr = buf.Leak();
96 // The buffer should point to the first element allocated.
97 // TODO(mpcomplete): Is this a reasonable expectation?
98 EXPECT_EQ(ptr, buf_ptr);
100 // The FixedBuffer should be empty now.
101 EXPECT_EQ(0u, buf.size());
102 EXPECT_FALSE(buf.Leak());
105 // Since we called Leak, ptr is still writable after FixedBuffer went out of