1// Copyright 2013 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 NET_QUIC_IOVECTOR_H_
6#define NET_QUIC_IOVECTOR_H_
7
8#include <stddef.h>
9#include <algorithm>
10#include <vector>
11
12#include "base/basictypes.h"
13#include "base/logging.h"
14#include "net/base/iovec.h"
15#include "net/base/net_export.h"
16
17namespace net {
18
19// Calculate the total number of bytes in an array of iovec structures.
20inline size_t TotalIovecLength(const struct iovec* iov, size_t iovcnt) {
21  size_t length = 0;
22  if (iov != NULL) {
23    for (size_t i = 0; i < iovcnt; ++i) {
24      length += iov[i].iov_len;
25    }
26  }
27  return length;
28}
29
30// IOVector is a helper class that makes it easier to work with POSIX vector I/O
31// struct. It is a thin wrapper by design and thus has no virtual functions and
32// all inlined methods. This class makes no assumptions about the ordering of
33// the pointer values of the blocks appended, it simply counts bytes when asked
34// to consume bytes.
35//
36// IOVector is a bookkeeping object that collects a description of buffers to
37// be read or written together and in order. It does not take ownership of the
38// blocks appended.
39//
40// Because it is used for scatter-gather operations, the order in which the
41// buffer blocks are added to the IOVector is important to the client. The
42// intended usage pattern is:
43//
44//   iovector.Append(p0, len0);
45//   ...
46//   iovector.Append(pn, lenn);
47//   int bytes_written = writev(fd, iovector.iovec(), iovector.Size());
48//   if (bytes_written > 0)
49//     iovector.Consume(bytes_written);
50//
51// The sequence is the same for readv, except that Consume() in this case is
52// used to change the IOVector to only keep track of description of blocks of
53// memory not yet written to.
54//
55// IOVector does not have any method to change the iovec entries that it
56// accumulates. This is due to the block merging nature of Append(): we'd like
57// to avoid accidentally change an entry that is assembled by two or more
58// Append()'s by simply an index access.
59//
60
61class NET_EXPORT_PRIVATE IOVector {
62 public:
63  // Provide a default constructor so it'll never be inhibited by adding other
64  // constructors.
65  IOVector();
66  ~IOVector();
67
68  // Provides a way to convert system call-like iovec representation to
69  // IOVector.
70  void AppendIovec(const struct iovec* iov, size_t iovcnt) {
71    for (size_t i = 0; i < iovcnt; ++i)
72      Append(static_cast<char*>(iov[i].iov_base), iov[i].iov_len);
73  }
74
75  // Appends at most max_bytes from iovec to the IOVector.
76  size_t AppendIovecAtMostBytes(const struct iovec* iov,
77                                size_t iovcnt,
78                                size_t max_bytes) {
79    size_t bytes_appended = 0;
80    for (size_t i = 0; i < iovcnt && max_bytes > 0; ++i) {
81      const size_t length = std::min(max_bytes, iov[i].iov_len);
82      Append(static_cast<char*>(iov[i].iov_base), length);
83      max_bytes -= length;
84      bytes_appended += length;
85    }
86    return bytes_appended;
87  }
88
89  // Append another block to the IOVector. Since IOVector can be used for read
90  // and write, it always takes char*. Clients that writes will need to cast
91  // away the constant of the pointer before appending a block.
92  void Append(char* buffer, size_t length) {
93    if (buffer != NULL && length > 0) {
94      if (iovec_.size() > 0) {
95        struct iovec& last = iovec_.back();
96        // If the new block is contiguous with the last block, just extend.
97        if (static_cast<char*>(last.iov_base) + last.iov_len == buffer) {
98          last.iov_len += length;
99          return;
100        }
101      }
102      struct iovec tmp = {buffer, length};
103      iovec_.push_back(tmp);
104    }
105  }
106
107  // Same as Append, but doesn't do the tail merge optimization.
108  // Intended for testing.
109  void AppendNoCoalesce(char* buffer, size_t length) {
110    if (buffer != NULL && length > 0) {
111      struct iovec tmp = {buffer, length};
112      iovec_.push_back(tmp);
113    }
114  }
115
116  // Remove a number of bytes from the beginning of the IOVector. Since vector
117  // I/O operations always occur at the beginning of the block list, a method
118  // to remove bytes at the end is not provided.
119  // It returns the number of bytes actually consumed (it'll only be smaller
120  // than the requested number if the IOVector contains less data).
121  size_t Consume(size_t length) {
122    if (length == 0) return 0;
123
124    size_t bytes_to_consume = length;
125    std::vector<struct iovec>::iterator iter = iovec_.begin();
126    std::vector<struct iovec>::iterator end = iovec_.end();
127    for (; iter < end && bytes_to_consume >= iter->iov_len; ++iter) {
128      bytes_to_consume -= iter->iov_len;
129    }
130    iovec_.erase(iovec_.begin(), iter);
131    if (iovec_.size() > 0 && bytes_to_consume != 0) {
132      iovec_[0].iov_base =
133          static_cast<char*>(iovec_[0].iov_base) + bytes_to_consume;
134      iovec_[0].iov_len -= bytes_to_consume;
135      return length;
136    }
137    if (iovec_.size() == 0 && bytes_to_consume > 0) {
138      LOG(DFATAL) << "Attempting to consume " << bytes_to_consume
139                  << " non-existent bytes.";
140    }
141    // At this point bytes_to_consume is the number of wanted bytes left over
142    // after walking through all the iovec entries.
143    return length - bytes_to_consume;
144  }
145
146  // TODO(joechan): If capacity is large, swap out for a blank one.
147  // Clears the IOVector object to contain no blocks.
148  void Clear() { iovec_.clear(); }
149
150  // Swap the guts of two IOVector.
151  void Swap(IOVector* other) { iovec_.swap(other->iovec_); }
152
153  // Returns the number of valid blocks in the IOVector (not the number of
154  // bytes).
155  size_t Size() const { return iovec_.size(); }
156
157  // Returns the total storage used by the IOVector in number of blocks (not
158  // the number of bytes).
159  size_t Capacity() const { return iovec_.capacity(); }
160
161  // Returns true if there are no blocks in the IOVector.
162  bool Empty() const { return iovec_.empty(); }
163
164  // Returns the pointer to the beginning of the iovec to be used for vector
165  // I/O operations. If the IOVector has no blocks appened, this function
166  // returns NULL.
167  struct iovec* iovec() { return !Empty() ? &iovec_[0] : NULL; }
168
169  // Const version.
170  const struct iovec* iovec() const { return !Empty() ? &iovec_[0] : NULL; }
171
172  // Returns a pointer to one past the last byte of the last block. If the
173  // IOVector is empty, NULL is returned.
174  const char* LastBlockEnd() const {
175    return iovec_.size() > 0 ?
176        static_cast<char *>(iovec_.back().iov_base) + iovec_.back().iov_len :
177        NULL;
178  }
179
180  // Returns the total number of bytes in the IOVector.
181  size_t TotalBufferSize() const { return TotalIovecLength(iovec(), Size()); }
182
183  void Resize(size_t count) {
184    iovec_.resize(count);
185  }
186
187 private:
188  std::vector<struct iovec> iovec_;
189
190  // IOVector has value-semantics; copy and assignment are allowed.
191  // This class does not explicitly define copy/move constructors or the
192  // assignment operator to preserve compiler-generated copy/move constructors
193  // and assignment operators. Note that since IOVector does not own the
194  // actual buffers that the struct iovecs point to, copies and assignments
195  // result in a shallow copy of the buffers; resulting IOVectors will point
196  // to the same copy of the underlying data.
197};
198
199}  // namespace net
200
201#endif  // NET_QUIC_IOVECTOR_H_
202