1 // Copyright 2012 The Chromium Authors
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/posix/global_descriptors.h"
6
7 #include <vector>
8 #include <utility>
9
10 #include "base/logging.h"
11
12 namespace base {
13
Descriptor(Key key,int fd)14 GlobalDescriptors::Descriptor::Descriptor(Key key, int fd)
15 : key(key), fd(fd), region(base::MemoryMappedFile::Region::kWholeFile) {
16 }
17
Descriptor(Key key,int fd,base::MemoryMappedFile::Region region)18 GlobalDescriptors::Descriptor::Descriptor(Key key,
19 int fd,
20 base::MemoryMappedFile::Region region)
21 : key(key), fd(fd), region(region) {
22 }
23
24 // static
GetInstance()25 GlobalDescriptors* GlobalDescriptors::GetInstance() {
26 typedef Singleton<base::GlobalDescriptors,
27 LeakySingletonTraits<base::GlobalDescriptors> >
28 GlobalDescriptorsSingleton;
29 return GlobalDescriptorsSingleton::get();
30 }
31
Get(Key key) const32 int GlobalDescriptors::Get(Key key) const {
33 const int ret = MaybeGet(key);
34
35 if (ret == -1)
36 DLOG(DCHECK) << "Unknown global descriptor: " << key;
37 return ret;
38 }
39
MaybeGet(Key key) const40 int GlobalDescriptors::MaybeGet(Key key) const {
41 for (const auto& i : descriptors_) {
42 if (i.key == key)
43 return i.fd;
44 }
45
46 return -1;
47 }
48
TakeFD(Key key,base::MemoryMappedFile::Region * region)49 base::ScopedFD GlobalDescriptors::TakeFD(
50 Key key,
51 base::MemoryMappedFile::Region* region) {
52 base::ScopedFD fd;
53 for (auto i = descriptors_.begin(); i != descriptors_.end(); ++i) {
54 if (i->key == key) {
55 *region = i->region;
56 fd.reset(i->fd);
57 descriptors_.erase(i);
58 break;
59 }
60 }
61 return fd;
62 }
63
Set(Key key,int fd)64 void GlobalDescriptors::Set(Key key, int fd) {
65 Set(key, fd, base::MemoryMappedFile::Region::kWholeFile);
66 }
67
Set(Key key,int fd,base::MemoryMappedFile::Region region)68 void GlobalDescriptors::Set(Key key,
69 int fd,
70 base::MemoryMappedFile::Region region) {
71 for (auto& i : descriptors_) {
72 if (i.key == key) {
73 i.fd = fd;
74 i.region = region;
75 return;
76 }
77 }
78
79 descriptors_.push_back(Descriptor(key, fd, region));
80 }
81
GetRegion(Key key) const82 base::MemoryMappedFile::Region GlobalDescriptors::GetRegion(Key key) const {
83 for (const auto& i : descriptors_) {
84 if (i.key == key)
85 return i.region;
86 }
87 DLOG(DCHECK) << "Unknown global descriptor: " << key;
88 return base::MemoryMappedFile::Region::kWholeFile;
89 }
90
Reset(const Mapping & mapping)91 void GlobalDescriptors::Reset(const Mapping& mapping) {
92 descriptors_ = mapping;
93 }
94
95 GlobalDescriptors::GlobalDescriptors() = default;
96
97 GlobalDescriptors::~GlobalDescriptors() = default;
98
99 } // namespace base
100