1 // Copyright (c) 2012 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/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 (Mapping::const_iterator
42 i = descriptors_.begin(); i != descriptors_.end(); ++i) {
43 if (i->key == key)
44 return i->fd;
45 }
46
47 return -1;
48 }
49
TakeFD(Key key,base::MemoryMappedFile::Region * region)50 base::ScopedFD GlobalDescriptors::TakeFD(
51 Key key,
52 base::MemoryMappedFile::Region* region) {
53 base::ScopedFD fd;
54 for (Mapping::iterator i = descriptors_.begin(); i != descriptors_.end();
55 ++i) {
56 if (i->key == key) {
57 *region = i->region;
58 fd.reset(i->fd);
59 descriptors_.erase(i);
60 break;
61 }
62 }
63 return fd;
64 }
65
Set(Key key,int fd)66 void GlobalDescriptors::Set(Key key, int fd) {
67 Set(key, fd, base::MemoryMappedFile::Region::kWholeFile);
68 }
69
Set(Key key,int fd,base::MemoryMappedFile::Region region)70 void GlobalDescriptors::Set(Key key,
71 int fd,
72 base::MemoryMappedFile::Region region) {
73 for (auto& i : descriptors_) {
74 if (i.key == key) {
75 i.fd = fd;
76 i.region = region;
77 return;
78 }
79 }
80
81 descriptors_.push_back(Descriptor(key, fd, region));
82 }
83
GetRegion(Key key) const84 base::MemoryMappedFile::Region GlobalDescriptors::GetRegion(Key key) const {
85 for (const auto& i : descriptors_) {
86 if (i.key == key)
87 return i.region;
88 }
89 DLOG(DCHECK) << "Unknown global descriptor: " << key;
90 return base::MemoryMappedFile::Region::kWholeFile;
91 }
92
Reset(const Mapping & mapping)93 void GlobalDescriptors::Reset(const Mapping& mapping) {
94 descriptors_ = mapping;
95 }
96
97 GlobalDescriptors::GlobalDescriptors() = default;
98
99 GlobalDescriptors::~GlobalDescriptors() = default;
100
101 } // namespace base
102