OpenSDN source code
TBufferTransports.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  *
19  * Modifications Copyright (c) Juniper Networks, Inc.
20  * Copyright Contributors to the OpenSDN project
21  */
22 
23 #ifndef _SANDESH_TRANSPORT_TBUFFERTRANSPORTS_H_
24 #define _SANDESH_TRANSPORT_TBUFFERTRANSPORTS_H_ 1
25 
26 #include <cstring>
27 #include "boost/scoped_array.hpp"
28 
29 #include <sandesh/transport/TTransport.h>
30 #include <sandesh/transport/TVirtualTransport.h>
31 
32 #ifdef __GNUC__
33 #define TDB_LIKELY(val) (__builtin_expect((val), 1))
34 #define TDB_UNLIKELY(val) (__builtin_expect((val), 0))
35 #else
36 #define TDB_LIKELY(val) (val)
37 #define TDB_UNLIKELY(val) (val)
38 #endif
39 
40 namespace contrail { namespace sandesh { namespace transport {
41 
42 
53 class TBufferBase : public TVirtualTransport<TBufferBase> {
54 
55  public:
56 
65  int32_t read(uint8_t* buf, uint32_t len) {
66  uint8_t* new_rBase = rBase_ + len;
67  if (TDB_LIKELY(new_rBase <= rBound_)) {
68  std::memcpy(buf, rBase_, len);
69  rBase_ = new_rBase;
70  return len;
71  }
72  return readSlow(buf, len);
73  }
74 
78  int32_t readAll(uint8_t* buf, uint32_t len) {
79  uint8_t* new_rBase = rBase_ + len;
80  if (TDB_LIKELY(new_rBase <= rBound_)) {
81  std::memcpy(buf, rBase_, len);
82  rBase_ = new_rBase;
83  return len;
84  }
85  return contrail::sandesh::transport::readAll(*this, buf, len);
86  }
87 
97  int write(const uint8_t* buf, uint32_t len) {
98  uint8_t* new_wBase = wBase_ + len;
99  if (TDB_LIKELY(new_wBase <= wBound_)) {
100  std::memcpy(wBase_, buf, len);
101  wBase_ = new_wBase;
102  return 0;
103  }
104  return writeSlow(buf, len);
105  }
106 
110  const uint8_t* borrow(uint8_t* buf, uint32_t* len) {
111  if (TDB_LIKELY(static_cast<ptrdiff_t>(*len) <= rBound_ - rBase_)) {
112  // With strict aliasing, writing to len shouldn't force us to
113  // refetch rBase_ from memory. TODO(dreiss): Verify this.
114  *len = static_cast<uint32_t>(rBound_ - rBase_);
115  return rBase_;
116  }
117  return borrowSlow(buf, len);
118  }
119 
123  void consume(uint32_t len) {
124  if (TDB_LIKELY(static_cast<ptrdiff_t>(len) <= rBound_ - rBase_)) {
125  rBase_ += len;
126  } else {
127  LOG(ERROR, __func__ << ": Consume did not follow a borrow.");
128  assert(false);
129  }
130  }
131 
133  void setReadBuffer(uint8_t* buf, uint32_t len) {
134  rBase_ = buf;
135  rBound_ = buf+len;
136  }
137 
139  void setWriteBuffer(uint8_t* buf, uint32_t len) {
140  wBase_ = buf;
141  wBound_ = buf+len;
142  }
143 
144  protected:
145 
147  virtual uint32_t readSlow(uint8_t* buf, uint32_t len) = 0;
148 
150  virtual int writeSlow(const uint8_t* buf, uint32_t len) = 0;
151 
157  virtual const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len) = 0;
158 
167  : rBase_(NULL)
168  , rBound_(NULL)
169  , wBase_(NULL)
170  , wBound_(NULL)
171  {}
172 
173  virtual ~TBufferBase() {}
174 
176  uint8_t* rBase_;
178  uint8_t* rBound_;
179 
181  uint8_t* wBase_;
183  uint8_t* wBound_;
184 };
185 
195 class TMemoryBuffer : public TVirtualTransport<TMemoryBuffer, TBufferBase> {
196  private:
197 
198  // Common initialization done by all constructors.
199  void initCommon(uint8_t* buf, uint32_t size, bool owner, uint32_t wPos) {
200  if (buf == NULL && size != 0) {
201  assert(owner);
202  buf = (uint8_t*)std::malloc(size);
203  if (buf == NULL) {
204  LOG(ERROR, __func__ << ": Allocation of " << size << " bytes FAILED");
205  assert(false);
206  }
207  }
208 
209  buffer_ = buf;
210  bufferSize_ = size;
211 
212  rBase_ = buffer_;
213  rBound_ = buffer_ + wPos;
214  // TODO(dreiss): Investigate NULL-ing this if !owner.
215  wBase_ = buffer_ + wPos;
217 
218  owner_ = owner;
219 
220  // rBound_ is really an artifact. In principle, it should always be
221  // equal to wBase_. We update it in a few places (computeRead, etc.).
222  }
223 
224  public:
225  static const uint32_t defaultSize = 1024;
226 
248  { OBSERVE = 1
249  , COPY = 2
251  };
252 
258  initCommon(NULL, defaultSize, true, 0);
259  }
260 
267  TMemoryBuffer(uint32_t sz) {
268  initCommon(NULL, sz, true, 0);
269  }
270 
281  TMemoryBuffer(uint8_t* buf, uint32_t sz, MemoryPolicy policy = OBSERVE) {
282  if (buf == NULL && sz != 0) {
283  LOG(ERROR, __func__ << ": TMemoryBuffer given null buffer with "
284  "non-zero size.");
285  assert(false);
286  }
287  switch (policy) {
288  case OBSERVE:
289  case TAKE_OWNERSHIP:
290  initCommon(buf, sz, policy == TAKE_OWNERSHIP, sz);
291  break;
292  case COPY:
293  initCommon(NULL, sz, true, 0);
294  this->write(buf, sz);
295  break;
296  default:
297  LOG(ERROR, __func__ << ": Invalid MemoryPolicy for TMemoryBuffer");
298  assert(false);
299  break;
300  }
301  }
302 
304  if (owner_) {
305  std::free(buffer_);
306  }
307  }
308 
309  bool isOpen() {
310  return true;
311  }
312 
313  bool peek() {
314  return (rBase_ < wBase_);
315  }
316 
317  void open() {}
318 
319  void close() {}
320 
321  // TODO(dreiss): Make bufPtr const.
322  void getBuffer(uint8_t** bufPtr, uint32_t* sz) {
323  *bufPtr = rBase_;
324  *sz = static_cast<uint32_t>(wBase_ - rBase_);
325  }
326 
327  std::string getBufferAsString() {
328  if (buffer_ == NULL) {
329  return "";
330  }
331  uint8_t* buf;
332  uint32_t sz;
333  getBuffer(&buf, &sz);
334  return std::string((char*)buf, (std::string::size_type)sz);
335  }
336 
337  void appendBufferToString(std::string& str) {
338  if (buffer_ == NULL) {
339  return;
340  }
341  uint8_t* buf;
342  uint32_t sz;
343  getBuffer(&buf, &sz);
344  str.append((char*)buf, sz);
345  }
346 
347  void resetBuffer() {
348  rBase_ = buffer_;
349  rBound_ = buffer_;
350  wBase_ = buffer_;
351  // It isn't safe to write into a buffer we don't own.
352  if (!owner_) {
353  wBound_ = wBase_;
354  bufferSize_ = 0;
355  }
356  }
357 
359  void resetBuffer(uint8_t* buf, uint32_t sz, MemoryPolicy policy = OBSERVE) {
360  // Use a variant of the copy-and-swap trick for assignment operators.
361  // This is sub-optimal in terms of performance for two reasons:
362  // 1/ The constructing and swapping of the (small) values
363  // in the temporary object takes some time, and is not necessary.
364  // 2/ If policy == COPY, we allocate the new buffer before
365  // freeing the old one, precluding the possibility of
366  // reusing that memory.
367  // I doubt that either of these problems could be optimized away,
368  // but the second is probably no a common case, and the first is minor.
369  // I don't expect resetBuffer to be a common operation, so I'm willing to
370  // bite the performance bullet to make the method this simple.
371 
372  // Construct the new buffer.
373  TMemoryBuffer new_buffer(buf, sz, policy);
374  // Move it into ourself.
375  this->swap(new_buffer);
376  // Our old self gets destroyed.
377  }
378 
380  void resetBuffer(uint32_t sz) {
381  // Construct the new buffer.
382  TMemoryBuffer new_buffer(sz);
383  // Move it into ourself.
384  this->swap(new_buffer);
385  // Our old self gets destroyed.
386  }
387 
388  std::string readAsString(uint32_t len) {
389  std::string str;
390  (void)readAppendToString(str, len);
391  return str;
392  }
393 
394  uint32_t readAppendToString(std::string& str, uint32_t len);
395 
396  // return number of bytes read
397  uint32_t readEnd() {
398  uint32_t bytes = static_cast<uint32_t>(rBase_ - buffer_);
399  if (rBase_ == wBase_) {
400  resetBuffer();
401  }
402  return bytes;
403  }
404 
405  // Return number of bytes written
406  uint32_t writeEnd() {
407  return static_cast<uint32_t>(wBase_ - buffer_);
408  }
409 
410  uint32_t available_read() const {
411  // Remember, wBase_ is the real rBound_.
412  return static_cast<uint32_t>(wBase_ - rBase_);
413  }
414 
415  uint32_t available_write() const {
416  return static_cast<uint32_t>(wBound_ - wBase_);
417  }
418 
419  // Returns a pointer to where the client can write data to append to
420  // the TMemoryBuffer, and ensures the buffer is big enough to accomodate a
421  // write of the provided length. The returned pointer is very convenient for
422  // passing to read(), recv(), or similar. You must call wroteBytes() as soon
423  // as data is written or the buffer will not be aware that data has changed.
424  uint8_t* getWritePtr(uint32_t len) {
425  ensureCanWrite(len);
426  return wBase_;
427  }
428 
429  // Informs the buffer that the client has written 'len' bytes into storage
430  // that had been provided by getWritePtr().
431  void wroteBytes(uint32_t len);
432 
433  /*
434  * TVirtualTransport provides a default implementation of readAll().
435  * We want to use the TBufferBase version instead.
436  */
437  uint32_t readAll(uint8_t* buf, uint32_t len) {
438  return TBufferBase::readAll(buf,len);
439  }
440 
441  protected:
442  void swap(TMemoryBuffer& that) {
443  using std::swap;
444  swap(buffer_, that.buffer_);
446 
447  swap(rBase_, that.rBase_);
448  swap(rBound_, that.rBound_);
449  swap(wBase_, that.wBase_);
450  swap(wBound_, that.wBound_);
451 
452  swap(owner_, that.owner_);
453  }
454 
455  // Make sure there's at least 'len' bytes available for writing.
456  int ensureCanWrite(uint32_t len);
457 
458  // Compute the position and available data for reading.
459  void computeRead(uint32_t len, uint8_t** out_start, uint32_t* out_give);
460 
461  uint32_t readSlow(uint8_t* buf, uint32_t len);
462 
463  int writeSlow(const uint8_t* buf, uint32_t len);
464 
465  const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len);
466 
467  // Data buffer
468  uint8_t* buffer_;
469 
470  // Allocated buffer size
471  uint32_t bufferSize_;
472 
473  // Is this object the owner of the buffer?
474  bool owner_;
475 
476  // Don't forget to update constrctors, initCommon, and swap if
477  // you add new members.
478 };
479 
480 }}} // contrail::sandesh::transport
481 
482 #endif // #ifndef _SANDESH_TRANSPORT_TBUFFERTRANSPORTS_H_
#define TDB_LIKELY(val)
uint8_t * wBound_
Writes may extend to just before here.
int write(const uint8_t *buf, uint32_t len)
uint8_t * rBound_
Reads may extend to just before here.
virtual const uint8_t * borrowSlow(uint8_t *buf, uint32_t *len)=0
int32_t read(uint8_t *buf, uint32_t len)
int32_t readAll(uint8_t *buf, uint32_t len)
void setReadBuffer(uint8_t *buf, uint32_t len)
Convenience mutator for setting the read buffer.
virtual int writeSlow(const uint8_t *buf, uint32_t len)=0
Slow path write.
void setWriteBuffer(uint8_t *buf, uint32_t len)
Convenience mutator for setting the write buffer.
virtual uint32_t readSlow(uint8_t *buf, uint32_t len)=0
Slow path read.
const uint8_t * borrow(uint8_t *buf, uint32_t *len)
void computeRead(uint32_t len, uint8_t **out_start, uint32_t *out_give)
uint32_t readSlow(uint8_t *buf, uint32_t len)
Slow path read.
void resetBuffer(uint8_t *buf, uint32_t sz, MemoryPolicy policy=OBSERVE)
See constructor documentation.
void resetBuffer(uint32_t sz)
See constructor documentation.
int writeSlow(const uint8_t *buf, uint32_t len)
Slow path write.
uint32_t readAll(uint8_t *buf, uint32_t len)
const uint8_t * borrowSlow(uint8_t *buf, uint32_t *len)
void getBuffer(uint8_t **bufPtr, uint32_t *sz)
void initCommon(uint8_t *buf, uint32_t size, bool owner, uint32_t wPos)
uint32_t readAppendToString(std::string &str, uint32_t len)
TMemoryBuffer(uint8_t *buf, uint32_t sz, MemoryPolicy policy=OBSERVE)
#define LOG(_Level, _Msg)
Definition: logging.h:35
int32_t readAll(Transport_ &trans, uint8_t *buf, uint32_t len)
Definition: TTransport.h:38
Definition: regex.h:11