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 "base/test/test_discardable_memory_allocator.h"
6 
7 #include <cstdint>
8 #include <cstring>
9 
10 #include "base/logging.h"
11 #include "base/memory/discardable_memory.h"
12 #include "base/memory/ptr_util.h"
13 
14 namespace base {
15 namespace {
16 
17 class DiscardableMemoryImpl : public DiscardableMemory {
18  public:
DiscardableMemoryImpl(size_t size)19   explicit DiscardableMemoryImpl(size_t size)
20       : data_(new uint8_t[size]), size_(size) {}
21 
22   // Overridden from DiscardableMemory:
Lock()23   bool Lock() override {
24     DCHECK(!is_locked_);
25     is_locked_ = true;
26     return false;
27   }
28 
Unlock()29   void Unlock() override {
30     DCHECK(is_locked_);
31     is_locked_ = false;
32     // Force eviction to catch clients not correctly checking the return value
33     // of Lock().
34     memset(data_.get(), 0, size_);
35   }
36 
data() const37   void* data() const override {
38     DCHECK(is_locked_);
39     return data_.get();
40   }
41 
CreateMemoryAllocatorDump(const char * name,trace_event::ProcessMemoryDump * pmd) const42   trace_event::MemoryAllocatorDump* CreateMemoryAllocatorDump(
43       const char* name,
44       trace_event::ProcessMemoryDump* pmd) const override {
45     return nullptr;
46   }
47 
48  private:
49   bool is_locked_ = true;
50   std::unique_ptr<uint8_t[]> data_;
51   size_t size_;
52 };
53 
54 }  // namespace
55 
56 std::unique_ptr<DiscardableMemory>
AllocateLockedDiscardableMemory(size_t size)57 TestDiscardableMemoryAllocator::AllocateLockedDiscardableMemory(size_t size) {
58   return std::make_unique<DiscardableMemoryImpl>(size);
59 }
60 
61 }  // namespace base
62