1 // Copyright 2014 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.
7 #include "mojo/public/cpp/bindings/lib/bindings_serialization.h"
8 #include "mojo/public/cpp/bindings/lib/fixed_buffer.h"
9 #include "testing/gtest/include/gtest/gtest.h"
15 bool IsZero(void* p_buf
, size_t size
) {
16 char* buf
= reinterpret_cast<char*>(p_buf
);
17 for (size_t i
= 0; i
< size
; ++i
) {
24 // Tests that FixedBuffer allocates memory aligned to 8 byte boundaries.
25 TEST(FixedBufferTest
, Alignment
) {
26 internal::FixedBuffer
buf(internal::Align(10) * 2);
27 ASSERT_EQ(buf
.size(), 16u * 2);
29 void* a
= buf
.Allocate(10);
31 EXPECT_TRUE(IsZero(a
, 10));
32 EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(a
) % 8);
34 void* b
= buf
.Allocate(10);
36 EXPECT_TRUE(IsZero(b
, 10));
37 EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(b
) % 8);
39 // Any more allocations would result in an assert, but we can't test that.
42 // Tests that FixedBuffer::Leak passes ownership to the caller.
43 TEST(FixedBufferTest
, Leak
) {
47 internal::FixedBuffer
buf(8);
48 ASSERT_EQ(8u, buf
.size());
50 ptr
= buf
.Allocate(8);
54 // The buffer should point to the first element allocated.
55 // TODO(mpcomplete): Is this a reasonable expectation?
56 EXPECT_EQ(ptr
, buf_ptr
);
58 // The FixedBuffer should be empty now.
59 EXPECT_EQ(0u, buf
.size());
60 EXPECT_FALSE(buf
.Leak());
63 // Since we called Leak, ptr is still writable after FixedBuffer went out of
70 TEST(FixedBufferTest
, TooBig
) {
71 internal::FixedBuffer
buf(24);
73 // A little bit too large.
74 EXPECT_EQ(reinterpret_cast<void*>(0), buf
.Allocate(32));
76 // Move the cursor forward.
77 EXPECT_NE(reinterpret_cast<void*>(0), buf
.Allocate(16));
80 EXPECT_EQ(reinterpret_cast<void*>(0),
81 buf
.Allocate(std::numeric_limits
<size_t>::max() - 1024u));
83 // A lot too large, leading to possible integer overflow.
84 EXPECT_EQ(reinterpret_cast<void*>(0),
85 buf
.Allocate(std::numeric_limits
<size_t>::max() - 8u));