| 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 "testing/gtest/include/gtest/gtest.h" |
| 8 |
| 9 namespace { |
| 10 |
| 11 const size_t kOneKilobyte = 1024; |
| 12 const size_t kAlmostOneMegabyte = 1023 * kOneKilobyte; |
| 13 const size_t kOneMegabyte = 1024 * kOneKilobyte; |
| 14 |
| 15 } // namespace |
| 16 |
| 17 TEST(DiscardableMemoryAllocator, Basic) { |
| 18 scoped_ptr<base::DiscardableMemoryShmemChunk> chunk; |
| 19 |
| 20 { |
| 21 html_viewer::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 html_viewer::DiscardableMemoryAllocator allocator(kOneMegabyte); |
| 39 |
| 40 scoped_ptr<base::DiscardableMemoryShmemChunk> 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::DiscardableMemoryShmemChunk> 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 |
| 53 TEST(DiscardableMemoryAllocator, DontDiscardLiveChunks) { |
| 54 html_viewer::DiscardableMemoryAllocator allocator(kOneMegabyte); |
| 55 |
| 56 scoped_ptr<base::DiscardableMemoryShmemChunk> chunk_one = |
| 57 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); |
| 58 scoped_ptr<base::DiscardableMemoryShmemChunk> chunk_two = |
| 59 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); |
| 60 scoped_ptr<base::DiscardableMemoryShmemChunk> chunk_three = |
| 61 allocator.AllocateLockedDiscardableMemory(kAlmostOneMegabyte); |
| 62 |
| 63 // These accesses will fail if the underlying weak ptr has been deallocated. |
| 64 EXPECT_NE(nullptr, chunk_one->Memory()); |
| 65 EXPECT_NE(nullptr, chunk_two->Memory()); |
| 66 EXPECT_NE(nullptr, chunk_three->Memory()); |
| 67 } |
| OLD | NEW |