shared_file.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2022 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. #ifndef COMPONENTS_WEB_PACKAGE_SHARED_FILE_H_
  5. #define COMPONENTS_WEB_PACKAGE_SHARED_FILE_H_
  6. #include <memory>
  7. #include "base/callback.h"
  8. #include "base/files/file.h"
  9. #include "base/files/file_path.h"
  10. #include "base/memory/ref_counted.h"
  11. #include "mojo/public/cpp/system/data_pipe_producer.h"
  12. namespace web_package {
  13. // A simple wrapper class to share a single base::File instance among multiple
  14. // SharedFileDataSource instances.
  15. class SharedFile final : public base::RefCountedThreadSafe<SharedFile> {
  16. public:
  17. // The callback passed to the constructor will run on a thread that allows
  18. // blocking disk IO.
  19. explicit SharedFile(
  20. base::OnceCallback<std::unique_ptr<base::File>()> open_file_callback);
  21. SharedFile(const SharedFile&) = delete;
  22. SharedFile& operator=(const SharedFile&) = delete;
  23. void DuplicateFile(base::OnceCallback<void(base::File)> callback);
  24. base::File* operator->();
  25. class SharedFileDataSource final : public mojo::DataPipeProducer::DataSource {
  26. public:
  27. SharedFileDataSource(scoped_refptr<SharedFile> file,
  28. uint64_t offset,
  29. uint64_t length);
  30. SharedFileDataSource(const SharedFileDataSource&) = delete;
  31. SharedFileDataSource& operator=(const SharedFileDataSource&) = delete;
  32. ~SharedFileDataSource() override;
  33. private:
  34. // Implements mojo::DataPipeProducer::DataSource. Following methods are
  35. // called on a blockable sequenced task runner.
  36. uint64_t GetLength() const override;
  37. ReadResult Read(uint64_t offset, base::span<char> buffer) override;
  38. scoped_refptr<SharedFile> file_;
  39. MojoResult error_;
  40. const uint64_t offset_;
  41. const uint64_t length_;
  42. };
  43. std::unique_ptr<SharedFileDataSource> CreateDataSource(uint64_t offset,
  44. uint64_t length);
  45. private:
  46. friend class base::RefCountedThreadSafe<SharedFile>;
  47. ~SharedFile();
  48. void SetFile(std::unique_ptr<base::File> file);
  49. base::FilePath file_path_;
  50. std::unique_ptr<base::File> file_;
  51. base::OnceCallback<void(base::File)> duplicate_callback_;
  52. };
  53. } // namespace web_package
  54. #endif // COMPONENTS_WEB_PACKAGE_SHARED_FILE_H_