1
#include "source/common/buffer/zero_copy_input_stream_impl.h"
2

            
3
#include "source/common/buffer/buffer_impl.h"
4
#include "source/common/common/assert.h"
5

            
6
namespace Envoy {
7
namespace Buffer {
8

            
9
465
ZeroCopyInputStreamImpl::ZeroCopyInputStreamImpl() : buffer_(new Buffer::OwnedImpl) {}
10

            
11
ZeroCopyInputStreamImpl::ZeroCopyInputStreamImpl(Buffer::InstancePtr&& buffer)
12
140634
    : buffer_(std::move(buffer)) {
13
140634
  finish();
14
140634
}
15

            
16
259
void ZeroCopyInputStreamImpl::move(Buffer::Instance& instance) {
17
259
  ASSERT(!finished_);
18

            
19
259
  buffer_->move(instance);
20
259
}
21

            
22
318126
void ZeroCopyInputStreamImpl::drainLastSlice() {
23
318126
  if (position_ != 0) {
24
177305
    buffer_->drain(position_);
25
177305
    position_ = 0;
26
177305
  }
27
318126
}
28

            
29
318115
bool ZeroCopyInputStreamImpl::Next(const void** data, int* size) {
30
318115
  drainLastSlice();
31

            
32
318115
  Buffer::RawSlice slice = buffer_->frontSlice();
33

            
34
318115
  if (slice.len_ > 0) {
35
177433
    *data = slice.mem_;
36
177433
    *size = slice.len_;
37
177433
    position_ = slice.len_;
38
177433
    byte_count_ += slice.len_;
39
177433
    return true;
40
177433
  }
41

            
42
140682
  if (!finished_) {
43
7
    *data = nullptr;
44
7
    *size = 0;
45
7
    return true;
46
7
  }
47
140675
  return false;
48
140682
}
49

            
50
11
bool ZeroCopyInputStreamImpl::Skip(int count) {
51
11
  ASSERT(count >= 0);
52
11
  drainLastSlice();
53

            
54
  // Could not skip more than buffer length.
55
11
  if (static_cast<uint64_t>(count) > buffer_->length()) {
56
3
    return false;
57
3
  }
58

            
59
8
  buffer_->drain(count);
60
8
  byte_count_ += count;
61
8
  return true;
62
11
}
63

            
64
219
void ZeroCopyInputStreamImpl::BackUp(int count) {
65
219
  ASSERT(count >= 0);
66
219
  ASSERT(uint64_t(count) <= position_);
67

            
68
  // Preconditions for BackUp:
69
  // - The last method called must have been Next().
70
  // - count must be less than or equal to the size of the last buffer returned by Next().
71
  // Due to preconditions above, it is safe to just adjust position_ and byte_count_ here, and
72
  // drain in Next().
73
219
  position_ -= count;
74
219
  byte_count_ -= count;
75
219
}
76
} // namespace Buffer
77
} // namespace Envoy