[CleanUp] Move PowerApiManager to power_api and Rename
[chromium-blink-merge.git] / base / memory / discardable_memory_shmem_allocator.cc
blob761204f31220d043e526f6cb35e3548e6eca237f
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"
11 namespace base {
12 namespace {
14 class DiscardableMemoryShmemChunkImpl : public DiscardableMemoryShmemChunk {
15 public:
16 explicit DiscardableMemoryShmemChunkImpl(
17 scoped_ptr<DiscardableSharedMemory> shared_memory)
18 : shared_memory_(shared_memory.Pass()) {}
20 // Overridden from DiscardableMemoryShmemChunk:
21 bool Lock() override { return false; }
22 void Unlock() override {
23 shared_memory_->Unlock(0, 0);
24 shared_memory_.reset();
26 void* Memory() const override { return shared_memory_->memory(); }
28 private:
29 scoped_ptr<DiscardableSharedMemory> shared_memory_;
31 DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryShmemChunkImpl);
34 // Default allocator implementation that allocates in-process
35 // DiscardableSharedMemory instances.
36 class DiscardableMemoryShmemAllocatorImpl
37 : public DiscardableMemoryShmemAllocator {
38 public:
39 // Overridden from DiscardableMemoryShmemAllocator:
40 scoped_ptr<DiscardableMemoryShmemChunk>
41 AllocateLockedDiscardableMemory(size_t size) override {
42 scoped_ptr<DiscardableSharedMemory> memory(new DiscardableSharedMemory);
43 if (!memory->CreateAndMap(size))
44 return nullptr;
46 return make_scoped_ptr(new DiscardableMemoryShmemChunkImpl(memory.Pass()));
50 LazyInstance<DiscardableMemoryShmemAllocatorImpl>::Leaky g_default_allocator =
51 LAZY_INSTANCE_INITIALIZER;
53 DiscardableMemoryShmemAllocator* g_allocator = nullptr;
55 } // namespace
57 // static
58 void DiscardableMemoryShmemAllocator::SetInstance(
59 DiscardableMemoryShmemAllocator* allocator) {
60 DCHECK(allocator);
62 // Make sure this function is only called once before the first call
63 // to GetInstance().
64 DCHECK(!g_allocator);
66 g_allocator = allocator;
69 // static
70 DiscardableMemoryShmemAllocator*
71 DiscardableMemoryShmemAllocator::GetInstance() {
72 if (!g_allocator)
73 g_allocator = g_default_allocator.Pointer();
75 return g_allocator;
78 } // namespace base