summaryrefslogtreecommitdiff
path: root/chromium/components/web_package/shared_file.h
blob: e6abaaffa49a9b8337aa2f169d36670ba1057998 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_WEB_PACKAGE_SHARED_FILE_H_
#define COMPONENTS_WEB_PACKAGE_SHARED_FILE_H_

#include <memory>

#include "base/callback.h"
#include "base/files/file.h"
#include "base/memory/ref_counted.h"
#include "base/task/sequenced_task_runner.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"

namespace web_package {

// A simple wrapper class to share a single `base::File` instance among multiple
// `SharedFile::SharedFileDataSource` instances.
class SharedFile final : public base::RefCountedThreadSafe<SharedFile> {
 public:
  // The file passed to this method must have been opened for reading.
  explicit SharedFile(std::unique_ptr<base::File> file);

  SharedFile(const SharedFile&) = delete;
  SharedFile& operator=(const SharedFile&) = delete;

  // Duplicate the underlying `base::File`. This is only needed for APIs that
  // require a `base::File` and cannot use a `SharedFile`.
  void DuplicateFile(base::OnceCallback<void(base::File)> callback);

  // Allow access to the underlying instance of `base::File`.
  base::File* operator->();

  class SharedFileDataSource final : public mojo::DataPipeProducer::DataSource {
   public:
    SharedFileDataSource(scoped_refptr<SharedFile> file,
                         uint64_t offset,
                         uint64_t length);

    SharedFileDataSource(const SharedFileDataSource&) = delete;
    SharedFileDataSource& operator=(const SharedFileDataSource&) = delete;

    ~SharedFileDataSource() override;

   private:
    // Implements `mojo::DataPipeProducer::DataSource`. The following methods
    // are called on a blockable sequenced task runner.
    uint64_t GetLength() const override;
    ReadResult Read(uint64_t offset, base::span<char> buffer) override;

    scoped_refptr<SharedFile> file_;
    MojoResult error_;
    const uint64_t offset_;
    const uint64_t length_;
  };

  std::unique_ptr<SharedFileDataSource> CreateDataSource(uint64_t offset,
                                                         uint64_t length);

 private:
  friend class base::RefCountedThreadSafe<SharedFile>;
  ~SharedFile();

  scoped_refptr<base::SequencedTaskRunner> task_runner_;
  std::unique_ptr<base::File> file_;
};

}  // namespace web_package

#endif  // COMPONENTS_WEB_PACKAGE_SHARED_FILE_H_