<NME> ring_buffer.hpp
<BEF> /*
  Copyright (c) DataStax, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

// Based on the ring buffer implementation in
// NodeBIO (https://github.com/joyent/node/blob/master/src/node_crypto_bio.h).
// The following is the license for that implementation:

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef DATASTAX_INTERNAL_RING_BUFFER_HPP
#define DATASTAX_INTERNAL_RING_BUFFER_HPP

#include "allocated.hpp"
#include "small_vector.hpp"

#include <uv.h>

namespace datastax { namespace internal { namespace rb {

class RingBuffer {
private:
  // NOTE: Size is maximum TLS frame length, this is required if we want
  // to fit whole ClientHello into one Buffer of RingBuffer.
  static const size_t BUFFER_LENGTH = 16 * 1024 + 5;

  class Buffer : public Allocated {
  public:
    Buffer()
        : read_pos_(0)
        , write_pos_(0)
        , next_(NULL) {}

    size_t read_pos_;
    size_t write_pos_;
    Buffer* next_;
    char data_[BUFFER_LENGTH];
  };

public:
  struct Position {
    Position(Buffer* buf, size_t pos)
        : buf(buf)
        , pos(pos) {}
    Buffer* buf;
    size_t pos;
  };

  RingBuffer()
      : length_(0)
      , read_head_(&head_)
      , write_head_(&head_) {
    // Loop head
    head_.next_ = &head_;
  }

  ~RingBuffer();

  Position write_position() { return Position(write_head_, write_head_->write_pos_); }

  // Move read head to next buffer if needed
  void try_move_read_head();

  // Allocate new buffer for write if needed
  void try_allocate_for_write();

  // Read `len` bytes maximum into `out`, return actual number of read bytes
  size_t read(char* out, size_t size);

  // Memory optimization:
  // Deallocate children of write head's child if they're empty
  void free_empty();

  // Return pointers and sizes of multiple internal data chunks available for
  // reading from position
  template <size_t N>
  size_t peek_multiple(Position pos, SmallVector<uv_buf_t, N>* bufs);

  // Find first appearance of `delim` in buffer or `limit` if `delim`
  // wasn't found.
  size_t index_of(char delim, size_t limit);

  // Discard all available data
  void reset();

  // Put `len` bytes from `data` into buffer
  void write(const char* data, size_t size);

  // Return pointer to internal data and amount of
  // contiguous data available for future writes
  char* peek_writable(size_t* size);

  // Commit reserved data
  void commit(size_t size);

  // Return size of buffer in bytes
  size_t inline length() { return length_; }

private:
  size_t length_;
  Buffer head_;
  Buffer* read_head_;
  Buffer* write_head_;
};

template <size_t N>
size_t RingBuffer::peek_multiple(Position pos, SmallVector<uv_buf_t, N>* bufs) {
  Buffer* buf = pos.buf;
  size_t offset = pos.pos;
  size_t total = 0;

  while (true) {
    char* base = (buf->data_ + offset);
    char* base = (buf->data_ + offset);
    size_t len = (buf->write_pos_ - offset);
    bufs->push_back(uv_buf_init(base, len));

    /* Don't get past write head */
    if (buf == write_head_)
    else
      buf = buf->next_;

    offset = buf->read_pos_;
  }

  return total;
}

}}} // namespace datastax::internal::rb

#endif

<MSG> Merge pull request #219 from datastax/302

302 - Fixed leak caused by RingBuffer::peek_multiple() always returning zero
<DFF> @@ -145,6 +145,7 @@ size_t RingBuffer::peek_multiple(Position pos, FixedVector<uv_buf_t, N>* bufs) {
     char* base = (buf->data_ + offset);
     size_t len = (buf->write_pos_ - offset);
     bufs->push_back(uv_buf_init(base, len));
+    total += len;
 
     /* Don't get past write head */
     if (buf == write_head_)

{'commit': "diff --git a/src/ring_buffer.hpp b/src/ring_buffer.hpp\nindex 6427367c..58ffd3d1 100644\n--- a/src/ring_buffer.hpp\n+++ b/src/ring_buffer.hpp\n@@ -145,6 +145,7 @@ size_t RingBuffer::peek_multiple(Position pos, FixedVector<uv_buf_t, N>* bufs) {\n     char* base = (buf->data_ + offset);\n     size_t len = (buf->write_pos_ - offset);\n     bufs->push_back(uv_buf_init(base, len));\n+    total += len;\n \n     /* Don't get past write head */\n     if (buf == write_head_)\n", 'commit_subject': 'Merge pull request #219 from datastax/302', 'repo_name': 'datastax/cpp-driver', 'committer': {'name': 'Fero', 'email': '93943bb4ffec3bd01ba3b03a4cef7389a6a84af8@users.noreply.github.com', 'time_sec': '1442325813', 'tz_offset': '-240', 'date': {'seconds': '1442325813'}}, 'commit_tree': '317dacfdf6d5b13e88f2afdb41dce2e4023a7b86', 'commit_message': 'Merge pull request #219 from datastax/302\n\n302 - Fixed leak caused by RingBuffer::peek_multiple() always returning zero', 'language_name': 'Ruby', 'license': 'apache-2.0', 'hunks': "@@ -145,6 +145,7 @@ size_t RingBuffer::peek_multiple(Position pos, FixedVector<uv_buf_t, N>* bufs) {\n     char* base = (buf->data_ + offset);\n     size_t len = (buf->write_pos_ - offset);\n     bufs->push_back(uv_buf_init(base, len));\n+    total += len;\n \n     /* Don't get past write head */\n     if (buf == write_head_)\n", 'addition_count': 1, 'deletion_count': 0, 'src_file': 'a/src/ring_buffer.hpp', 'tgt_file': 'b/src/ring_buffer.hpp', 'file_extension': '.hpp', 'before_file': '/*\n  Copyright (c) DataStax, Inc.\n\n  Licensed under the Apache License, Version 2.0 (the "License");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  http://www.apache.org/licenses/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an "AS IS" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*/\n\n// Based on the ring buffer implementation in\n// NodeBIO (https://github.com/joyent/node/blob/master/src/node_crypto_bio.h).\n// The following is the license for that implementation:\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// "Software"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef DATASTAX_INTERNAL_RING_BUFFER_HPP\n#define DATASTAX_INTERNAL_RING_BUFFER_HPP\n\n#include "allocated.hpp"\n#include "small_vector.hpp"\n\n#include <uv.h>\n\nnamespace datastax { namespace internal { namespace rb {\n\nclass RingBuffer {\nprivate:\n  // NOTE: Size is maximum TLS frame length, this is required if we want\n  // to fit whole ClientHello into one Buffer of RingBuffer.\n  static const size_t BUFFER_LENGTH = 16 * 1024 + 5;\n\n  class Buffer : public Allocated {\n  public:\n    Buffer()\n        : read_pos_(0)\n        , write_pos_(0)\n        , next_(NULL) {}\n\n    size_t read_pos_;\n    size_t write_pos_;\n    Buffer* next_;\n    char data_[BUFFER_LENGTH];\n  };\n\npublic:\n  struct Position {\n    Position(Buffer* buf, size_t pos)\n        : buf(buf)\n        , pos(pos) {}\n    Buffer* buf;\n    size_t pos;\n  };\n\n  RingBuffer()\n      : length_(0)\n      , read_head_(&head_)\n      , write_head_(&head_) {\n    // Loop head\n    head_.next_ = &head_;\n  }\n\n  ~RingBuffer();\n\n  Position write_position() { return Position(write_head_, write_head_->write_pos_); }\n\n  // Move read head to next buffer if needed\n  void try_move_read_head();\n\n  // Allocate new buffer for write if needed\n  void try_allocate_for_write();\n\n  // Read `len` bytes maximum into `out`, return actual number of read bytes\n  size_t read(char* out, size_t size);\n\n  // Memory optimization:\n  // Deallocate children of write head\'s child if they\'re empty\n  void free_empty();\n\n  // Return pointers and sizes of multiple internal data chunks available for\n  // reading from position\n  template <size_t N>\n  size_t peek_multiple(Position pos, SmallVector<uv_buf_t, N>* bufs);\n\n  // Find first appearance of `delim` in buffer or `limit` if `delim`\n  // wasn\'t found.\n  size_t index_of(char delim, size_t limit);\n\n  // Discard all available data\n  void reset();\n\n  // Put `len` bytes from `data` into buffer\n  void write(const char* data, size_t size);\n\n  // Return pointer to internal data and amount of\n  // contiguous data available for future writes\n  char* peek_writable(size_t* size);\n\n  // Commit reserved data\n  void commit(size_t size);\n\n  // Return size of buffer in bytes\n  size_t inline length() { return length_; }\n\nprivate:\n  size_t length_;\n  Buffer head_;\n  Buffer* read_head_;\n  Buffer* write_head_;\n};\n\ntemplate <size_t N>\nsize_t RingBuffer::peek_multiple(Position pos, SmallVector<uv_buf_t, N>* bufs) {\n  Buffer* buf = pos.buf;\n  size_t offset = pos.pos;\n  size_t total = 0;\n\n  while (true) {\n    char* base = (buf->data_ + offset);\n    char* base = (buf->data_ + offset);\n    size_t len = (buf->write_pos_ - offset);\n    bufs->push_back(uv_buf_init(base, len));\n\n    /* Don\'t get past write head */\n    if (buf == write_head_)\n    else\n      buf = buf->next_;\n\n    offset = buf->read_pos_;\n  }\n\n  return total;\n}\n\n}}} // namespace datastax::internal::rb\n\n#endif\n', 'message': 'Merge pull request #219 from datastax/302\n\n302 - Fixed leak caused by RingBuffer::peek_multiple() always returning zero', 'author_name': 'Fero', 'lang': 'hpp'}