1 // Copyright 2019 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 #ifndef PLATFORM_IMPL_TLS_WRITE_BUFFER_H_
6 #define PLATFORM_IMPL_TLS_WRITE_BUFFER_H_
7 
8 #include <atomic>
9 #include <memory>
10 
11 #include "absl/types/span.h"
12 #include "platform/base/macros.h"
13 
14 namespace openscreen {
15 
16 // This class is responsible for buffering TLS Write data. The approach taken by
17 // this class is to allow for a single thread to act as a publisher of data and
18 // for a separate thread to act as the consumer of that data. The data in
19 // question is written to a lockless FIFO queue.
20 class TlsWriteBuffer {
21  public:
22   TlsWriteBuffer();
23   ~TlsWriteBuffer();
24 
25   // Pushes the provided data into the buffer, returning true if successful.
26   // Returns false if there was insufficient space left. Either all or none of
27   // the data is pushed into the buffer.
28   bool Push(const void* data, size_t len);
29 
30   // Returns a subset of the readable region of data. At time of reading, more
31   // data may be available for reading than what is represented in this Span.
32   absl::Span<const uint8_t> GetReadableRegion();
33 
34   // Marks the provided number of bytes as consumed by the consumer thread.
35   void Consume(size_t byte_count);
36 
37   // The amount of space to allocate in the buffer.
38   static constexpr size_t kBufferSizeBytes = 1 << 19;  // 0.5 MB.
39 
40  private:
41   // Buffer where data to be written over the TLS connection is stored.
42   uint8_t buffer_[kBufferSizeBytes];
43 
44   // Total number of bytes read or written so far. Atomics are used both to
45   // ensure that read and write operations are atomic for uint64s on all systems
46   // and to ensure that different values for these values aren't loaded from
47   // each CPU's physical cache.
48   std::atomic_size_t bytes_read_so_far_{0};
49   std::atomic_size_t bytes_written_so_far_{0};
50 
51   OSP_DISALLOW_COPY_AND_ASSIGN(TlsWriteBuffer);
52 };
53 
54 }  // namespace openscreen
55 
56 #endif  // PLATFORM_IMPL_TLS_WRITE_BUFFER_H_
57