jcivelli | dad0cef | 2017-02-16 18:38:59 | [diff] [blame] | 1 | // Copyright 2017 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/file_descriptor_store.h" |
| 6 | |
| 7 | #include <utility> |
| 8 | |
| 9 | #include "base/logging.h" |
| 10 | |
| 11 | namespace base { |
| 12 | |
| 13 | FileDescriptorStore::Descriptor::Descriptor(const std::string& key, |
| 14 | base::ScopedFD fd) |
| 15 | : key(key), |
| 16 | fd(std::move(fd)), |
| 17 | region(base::MemoryMappedFile::Region::kWholeFile) {} |
| 18 | |
| 19 | FileDescriptorStore::Descriptor::Descriptor( |
| 20 | const std::string& key, |
| 21 | base::ScopedFD fd, |
| 22 | base::MemoryMappedFile::Region region) |
| 23 | : key(key), fd(std::move(fd)), region(region) {} |
| 24 | |
| 25 | FileDescriptorStore::Descriptor::Descriptor( |
| 26 | FileDescriptorStore::Descriptor&& other) |
| 27 | : key(other.key), fd(std::move(other.fd)), region(other.region) {} |
| 28 | |
| 29 | FileDescriptorStore::Descriptor::~Descriptor() {} |
| 30 | |
| 31 | // static |
| 32 | FileDescriptorStore& FileDescriptorStore::GetInstance() { |
| 33 | static FileDescriptorStore* store = new FileDescriptorStore; |
| 34 | return *store; |
| 35 | } |
| 36 | |
| 37 | base::ScopedFD FileDescriptorStore::TakeFD( |
| 38 | const std::string& key, |
| 39 | base::MemoryMappedFile::Region* region) { |
| 40 | base::ScopedFD fd = MaybeTakeFD(key, region); |
| 41 | if (!fd.is_valid()) |
| 42 | DLOG(FATAL) << "Unknown global descriptor: " << key; |
| 43 | return fd; |
| 44 | } |
| 45 | |
| 46 | base::ScopedFD FileDescriptorStore::MaybeTakeFD( |
| 47 | const std::string& key, |
| 48 | base::MemoryMappedFile::Region* region) { |
| 49 | auto iter = descriptors_.find(key); |
| 50 | if (iter == descriptors_.end()) |
| 51 | return base::ScopedFD(); |
| 52 | *region = iter->second.region; |
| 53 | base::ScopedFD result = std::move(iter->second.fd); |
| 54 | descriptors_.erase(iter); |
| 55 | return result; |
| 56 | } |
| 57 | |
| 58 | void FileDescriptorStore::Set(const std::string& key, base::ScopedFD fd) { |
| 59 | Set(key, std::move(fd), base::MemoryMappedFile::Region::kWholeFile); |
| 60 | } |
| 61 | |
| 62 | void FileDescriptorStore::Set(const std::string& key, |
| 63 | base::ScopedFD fd, |
| 64 | base::MemoryMappedFile::Region region) { |
| 65 | Descriptor descriptor(key, std::move(fd), region); |
| 66 | descriptors_.insert(std::make_pair(key, std::move(descriptor))); |
| 67 | } |
| 68 | |
| 69 | FileDescriptorStore::FileDescriptorStore() {} |
| 70 | |
| 71 | FileDescriptorStore::~FileDescriptorStore() {} |
| 72 | |
| 73 | } // namespace base |