OLD | NEW |
| (Empty) |
1 // Copyright 2015 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 "mojo/services/html_viewer/discardable_memory_allocator.h" | |
6 | |
7 #include "base/memory/discardable_memory.h" | |
8 #include "testing/gtest/include/gtest/gtest.h" | |
9 | |
10 namespace html_viewer { | |
11 namespace { | |
12 | |
13 const size_t kOneKilobyte = 1024; | |
14 const size_t kAlmostOneMegabyte = 1023 * kOneKilobyte; | |
15 const size_t kOneMegabyte = 1024 * kOneKilobyte; | |
16 | |
17 TEST(DiscardableMemoryAllocator, Basic) { | |
18 scoped_ptr<base::DiscardableMemory> chunk; | |
19 | |
20 { | |
21 DiscardableMemoryAllocator allocator(kOneMegabyte); | |
22 | |
23 // Make sure the chunk is locked when allocated. In debug mode, we will | |
24 // dcheck. | |
25 chunk = allocator.AllocateLockedDiscardableMemory(kOneKilobyte); | |
26 chunk->Unlock(); | |
27 | |
28 // Make sure we can lock a chunk. | |
29 EXPECT_TRUE(chunk->Lock()); | |
30 chunk->Unlock(); | |
31 } | |
32 | |
33 // The chunk's backing should have disappeared with the allocator. | |
34 EXPECT_FALSE(chunk->Lock()); | |
35 } | |
36 | |
37 TEST(DiscardableMemoryAllocator, DiscardChunks) { | |
38 DiscardableMemoryAllocator allocator(kOneMegabyte); | |
39 | |
40 scoped_ptr<base::DiscardableMemory> chunk_to_remove = | |
41 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); | |
42 chunk_to_remove->Unlock(); | |
43 | |
44 // Allocating a second chunk should deallocate the first one due to memory | |
45 // pressure, since we only have one megabyte available. | |
46 scoped_ptr<base::DiscardableMemory> chunk_to_keep = | |
47 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); | |
48 | |
49 // Fail to get a lock because allocating the second chunk removed the first. | |
50 EXPECT_FALSE(chunk_to_remove->Lock()); | |
51 | |
52 chunk_to_keep->Unlock(); | |
53 } | |
54 | |
55 TEST(DiscardableMemoryAllocator, DontDiscardLiveChunks) { | |
56 DiscardableMemoryAllocator allocator(kOneMegabyte); | |
57 | |
58 scoped_ptr<base::DiscardableMemory> chunk_one = | |
59 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); | |
60 scoped_ptr<base::DiscardableMemory> chunk_two = | |
61 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); | |
62 scoped_ptr<base::DiscardableMemory> chunk_three = | |
63 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); | |
64 | |
65 // These accesses will fail if the underlying weak ptr has been deallocated. | |
66 EXPECT_NE(nullptr, chunk_one->data()); | |
67 EXPECT_NE(nullptr, chunk_two->data()); | |
68 EXPECT_NE(nullptr, chunk_three->data()); | |
69 | |
70 chunk_one->Unlock(); | |
71 chunk_two->Unlock(); | |
72 chunk_three->Unlock(); | |
73 } | |
74 | |
75 } // namespace | |
76 } // namespace html_viewer | |
OLD | NEW |