aboutsummaryrefslogtreecommitdiff
path: root/include/cru/common/io/AutoReadStream.h
blob: b416d050c0cba6fd245c1c785c8c805117b189e1 (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
72
73
#pragma once

#include "../SelfResolvable.h"
#include "BufferStream.h"
#include "Stream.h"

#include <mutex>

namespace cru::io {
struct AutoReadStreamOptions {
  /**
   * @brief Will be passed to BufferStreamOptions::block_size.
   */
  Index block_size = 0;

  /**
   * @brief Will be passed to BufferStreamOptions::total_size_limit.
   */
  Index total_size_limit = 0;

  BufferStreamOptions GetBufferStreamOptions() const {
    BufferStreamOptions options;
    options.block_size = block_size;
    options.total_size_limit = total_size_limit;
    return options;
  }
};

/**
 * @brief A stream that wraps another stream and auto read it into a buffer in a
 * background thread.
 */
class CRU_BASE_API AutoReadStream : public Stream,
                                    public SelfResolvable<AutoReadStream> {
 public:
  /**
   * @brief Wrap a stream and auto read it in background.
   * @param stream The stream to auto read.
   * @param auto_delete Whether to delete the stream object in destructor.
   * @param options Options to modify the behavior.
   */
  AutoReadStream(
      Stream* stream, bool auto_delete,
      const AutoReadStreamOptions& options = AutoReadStreamOptions());

  ~AutoReadStream() override;

 public:
  bool CanSeek() override;
  Index Seek(Index offset, SeekOrigin origin = SeekOrigin::Current) override;

  bool CanRead() override;
  Index Read(std::byte* buffer, Index offset, Index size) override;

  bool CanWrite() override;
  Index Write(const std::byte* buffer, Index offset, Index size) override;

  void Flush() override;

  void Close() override;

 private:
  void BackgroundThreadRun();

 private:
  Stream* stream_;
  bool auto_delete_;

  Index size_per_read_;
  std::unique_ptr<BufferStream> buffer_stream_;
  std::mutex buffer_stream_mutex_;
};
}  // namespace cru::io