OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #include <limits> | |
6 | |
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" | |
10 | |
11 namespace mojo { | |
12 namespace test { | |
13 namespace { | |
14 | |
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; | |
20 } | |
21 return true; | |
22 } | |
23 | |
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); | |
28 | |
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); | |
33 | |
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); | |
38 | |
39 // Any more allocations would result in an assert, but we can't test that. | |
40 } | |
41 | |
42 // Tests that FixedBuffer::Leak passes ownership to the caller. | |
43 TEST(FixedBufferTest, Leak) { | |
44 void* ptr = nullptr; | |
45 void* buf_ptr = nullptr; | |
46 { | |
47 internal::FixedBuffer buf(8); | |
48 ASSERT_EQ(8u, buf.size()); | |
49 | |
50 ptr = buf.Allocate(8); | |
51 ASSERT_TRUE(ptr); | |
52 buf_ptr = buf.Leak(); | |
53 | |
54 // The buffer should point to the first element allocated. | |
55 // TODO(mpcomplete): Is this a reasonable expectation? | |
56 EXPECT_EQ(ptr, buf_ptr); | |
57 | |
58 // The FixedBuffer should be empty now. | |
59 EXPECT_EQ(0u, buf.size()); | |
60 EXPECT_FALSE(buf.Leak()); | |
61 } | |
62 | |
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); | |
67 } | |
68 | |
69 #ifdef NDEBUG | |
70 TEST(FixedBufferTest, TooBig) { | |
71 internal::FixedBuffer buf(24); | |
72 | |
73 // A little bit too large. | |
74 EXPECT_EQ(reinterpret_cast<void*>(0), buf.Allocate(32)); | |
75 | |
76 // Move the cursor forward. | |
77 EXPECT_NE(reinterpret_cast<void*>(0), buf.Allocate(16)); | |
78 | |
79 // A lot too large. | |
80 EXPECT_EQ(reinterpret_cast<void*>(0), | |
81 buf.Allocate(std::numeric_limits<size_t>::max() - 1024u)); | |
82 | |
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)); | |
86 } | |
87 #endif | |
88 | |
89 } // namespace | |
90 } // namespace test | |
91 } // namespace mojo | |
OLD | NEW |