file_descriptor_store.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #include "base/file_descriptor_store.h"
  5. #include <utility>
  6. #include "base/logging.h"
  7. namespace base {
  8. FileDescriptorStore::Descriptor::Descriptor(const std::string& key,
  9. base::ScopedFD fd)
  10. : key(key),
  11. fd(std::move(fd)),
  12. region(base::MemoryMappedFile::Region::kWholeFile) {}
  13. FileDescriptorStore::Descriptor::Descriptor(
  14. const std::string& key,
  15. base::ScopedFD fd,
  16. base::MemoryMappedFile::Region region)
  17. : key(key), fd(std::move(fd)), region(region) {}
  18. FileDescriptorStore::Descriptor::Descriptor(
  19. FileDescriptorStore::Descriptor&& other)
  20. : key(other.key), fd(std::move(other.fd)), region(other.region) {}
  21. FileDescriptorStore::Descriptor::~Descriptor() = default;
  22. // static
  23. FileDescriptorStore& FileDescriptorStore::GetInstance() {
  24. static FileDescriptorStore* store = new FileDescriptorStore;
  25. return *store;
  26. }
  27. base::ScopedFD FileDescriptorStore::TakeFD(
  28. const std::string& key,
  29. base::MemoryMappedFile::Region* region) {
  30. base::ScopedFD fd = MaybeTakeFD(key, region);
  31. if (!fd.is_valid())
  32. DLOG(DCHECK) << "Unknown global descriptor: " << key;
  33. return fd;
  34. }
  35. base::ScopedFD FileDescriptorStore::MaybeTakeFD(
  36. const std::string& key,
  37. base::MemoryMappedFile::Region* region) {
  38. auto iter = descriptors_.find(key);
  39. if (iter == descriptors_.end())
  40. return base::ScopedFD();
  41. *region = iter->second.region;
  42. base::ScopedFD result = std::move(iter->second.fd);
  43. descriptors_.erase(iter);
  44. return result;
  45. }
  46. void FileDescriptorStore::Set(const std::string& key, base::ScopedFD fd) {
  47. Set(key, std::move(fd), base::MemoryMappedFile::Region::kWholeFile);
  48. }
  49. void FileDescriptorStore::Set(const std::string& key,
  50. base::ScopedFD fd,
  51. base::MemoryMappedFile::Region region) {
  52. Descriptor descriptor(key, std::move(fd), region);
  53. descriptors_.insert(std::make_pair(key, std::move(descriptor)));
  54. }
  55. FileDescriptorStore::FileDescriptorStore() = default;
  56. FileDescriptorStore::~FileDescriptorStore() = default;
  57. } // namespace base