- add sources.
[platform/framework/web/crosswalk.git] / src / base / memory / discardable_memory_emulated.cc
1 // Copyright 2013 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 "base/memory/discardable_memory.h"
6
7 #include "base/memory/discardable_memory_provider.h"
8
9 using base::internal::DiscardableMemoryProvider;
10
11 namespace base {
12 namespace {
13
14 class DiscardableMemoryEmulated : public DiscardableMemory {
15  public:
16   explicit DiscardableMemoryEmulated(size_t size) : is_locked_(false) {
17     DiscardableMemoryProvider::GetInstance()->Register(this, size);
18   }
19
20   virtual ~DiscardableMemoryEmulated() {
21     if (is_locked_)
22       Unlock();
23     DiscardableMemoryProvider::GetInstance()->Unregister(this);
24   }
25
26   // DiscardableMemory:
27   virtual LockDiscardableMemoryStatus Lock() OVERRIDE {
28     DCHECK(!is_locked_);
29
30     bool purged = false;
31     memory_ = DiscardableMemoryProvider::GetInstance()->Acquire(this, &purged);
32     if (!memory_)
33       return DISCARDABLE_MEMORY_FAILED;
34
35     is_locked_ = true;
36     return purged ? DISCARDABLE_MEMORY_PURGED : DISCARDABLE_MEMORY_SUCCESS;
37   }
38
39   virtual void Unlock() OVERRIDE {
40     DCHECK(is_locked_);
41     DiscardableMemoryProvider::GetInstance()->Release(this, memory_.Pass());
42     is_locked_ = false;
43   }
44
45   virtual void* Memory() const OVERRIDE {
46     DCHECK(memory_);
47     return memory_.get();
48   }
49
50  private:
51   scoped_ptr<uint8, FreeDeleter> memory_;
52   bool is_locked_;
53
54   DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryEmulated);
55 };
56
57 }  // namespace
58
59 // static
60 bool DiscardableMemory::SupportedNatively() {
61   return false;
62 }
63
64 // static
65 scoped_ptr<DiscardableMemory> DiscardableMemory::CreateLockedMemory(
66     size_t size) {
67   scoped_ptr<DiscardableMemory> memory(new DiscardableMemoryEmulated(size));
68   if (!memory)
69     return scoped_ptr<DiscardableMemory>();
70   if (memory->Lock() != DISCARDABLE_MEMORY_PURGED)
71     return scoped_ptr<DiscardableMemory>();
72   return memory.Pass();
73 }
74
75 // static
76 bool DiscardableMemory::PurgeForTestingSupported() {
77   return true;
78 }
79
80 // static
81 void DiscardableMemory::PurgeForTesting() {
82   DiscardableMemoryProvider::GetInstance()->PurgeAll();
83 }
84
85 }  // namespace base