global_descriptors_posix.cc revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
1// Copyright (c) 2009 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/global_descriptors_posix.h"
6
7#include <vector>
8#include <utility>
9
10#include "base/logging.h"
11
12namespace base {
13
14// static
15GlobalDescriptors* GlobalDescriptors::GetInstance() {
16  typedef Singleton<base::GlobalDescriptors,
17                    LeakySingletonTraits<base::GlobalDescriptors> >
18      GlobalDescriptorsSingleton;
19  return GlobalDescriptorsSingleton::get();
20}
21
22int GlobalDescriptors::Get(Key key) const {
23  const int ret = MaybeGet(key);
24
25  if (ret == -1)
26    LOG(FATAL) << "Unknown global descriptor: " << key;
27  return ret;
28}
29
30int GlobalDescriptors::MaybeGet(Key key) const {
31  for (Mapping::const_iterator
32       i = descriptors_.begin(); i != descriptors_.end(); ++i) {
33    if (i->first == key)
34      return i->second;
35  }
36
37  // In order to make unittests pass, we define a default mapping from keys to
38  // descriptors by adding a fixed offset:
39  return kBaseDescriptor + key;
40}
41
42void GlobalDescriptors::Set(Key key, int fd) {
43  for (Mapping::iterator
44       i = descriptors_.begin(); i != descriptors_.end(); ++i) {
45    if (i->first == key) {
46      i->second = fd;
47      return;
48    }
49  }
50
51  descriptors_.push_back(std::make_pair(key, fd));
52}
53
54void GlobalDescriptors::Reset(const Mapping& mapping) {
55  descriptors_ = mapping;
56}
57
58GlobalDescriptors::GlobalDescriptors() {}
59
60GlobalDescriptors::~GlobalDescriptors() {}
61
62}  // namespace base
63