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