Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / mojo / public / cpp / bindings / tests / buffer_unittest.cc
blobf881784ab77c168960e799e79bcecfed2009a3b6
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.
5 #include <limits>
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"
11 namespace mojo {
12 namespace test {
13 namespace {
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) {
18 if (buf[i] != 0)
19 return false;
21 return true;
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);
30 ASSERT_TRUE(a);
31 EXPECT_TRUE(IsZero(a, 10));
32 EXPECT_EQ(0, reinterpret_cast<ptrdiff_t>(a) % 8);
34 void* b = buf.Allocate(10);
35 ASSERT_TRUE(b);
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) {
44 void* ptr = NULL;
45 void* buf_ptr = NULL;
47 internal::FixedBuffer buf(8);
48 ASSERT_EQ(8u, buf.size());
50 ptr = buf.Allocate(8);
51 ASSERT_TRUE(ptr);
52 buf_ptr = buf.Leak();
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
64 // scope.
65 memset(ptr, 1, 8);
66 free(buf_ptr);
69 #ifdef NDEBUG
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));
79 // A lot too large.
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));
87 #endif
89 } // namespace
90 } // namespace test
91 } // namespace mojo