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