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.
5 #include "base/memory/discardable_memory_shmem_allocator.h"
7 #include "base/lazy_instance.h"
8 #include "base/logging.h"
9 #include "base/memory/discardable_shared_memory.h"
14 class DiscardableMemoryShmemChunkImpl
: public DiscardableMemoryShmemChunk
{
16 explicit DiscardableMemoryShmemChunkImpl(
17 scoped_ptr
<DiscardableSharedMemory
> shared_memory
)
18 : shared_memory_(shared_memory
.Pass()) {}
20 // Overridden from DiscardableMemoryShmemChunk:
21 bool Lock() override
{
22 auto result
= shared_memory_
->Lock(0, 0);
23 DCHECK_NE(result
, DiscardableSharedMemory::PURGED
);
24 return result
== DiscardableSharedMemory::SUCCESS
;
26 void Unlock() override
{ shared_memory_
->Unlock(0, 0); }
27 void* Memory() const override
{ return shared_memory_
->memory(); }
28 bool IsMemoryResident() const override
{
29 return shared_memory_
->IsMemoryResident();
33 scoped_ptr
<DiscardableSharedMemory
> shared_memory_
;
35 DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryShmemChunkImpl
);
38 // Default allocator implementation that allocates in-process
39 // DiscardableSharedMemory instances.
40 class DiscardableMemoryShmemAllocatorImpl
41 : public DiscardableMemoryShmemAllocator
{
43 // Overridden from DiscardableMemoryShmemAllocator:
44 scoped_ptr
<DiscardableMemoryShmemChunk
>
45 AllocateLockedDiscardableMemory(size_t size
) override
{
46 scoped_ptr
<DiscardableSharedMemory
> memory(new DiscardableSharedMemory
);
47 if (!memory
->CreateAndMap(size
))
50 return make_scoped_ptr(new DiscardableMemoryShmemChunkImpl(memory
.Pass()));
54 LazyInstance
<DiscardableMemoryShmemAllocatorImpl
>::Leaky g_default_allocator
=
55 LAZY_INSTANCE_INITIALIZER
;
57 DiscardableMemoryShmemAllocator
* g_allocator
= nullptr;
62 void DiscardableMemoryShmemAllocator::SetInstance(
63 DiscardableMemoryShmemAllocator
* allocator
) {
66 // Make sure this function is only called once before the first call
70 g_allocator
= allocator
;
74 DiscardableMemoryShmemAllocator
*
75 DiscardableMemoryShmemAllocator::GetInstance() {
77 g_allocator
= g_default_allocator
.Pointer();