项目作者: janwilmans

项目描述 :
A ring_span implementation that allows zero construction and destruction
高级语言: C++
项目地址: git://github.com/janwilmans/ring_span.git
创建时间: 2020-06-07T00:32:09Z
项目社区:https://github.com/janwilmans/ring_span

开源协议:Boost Software License 1.0

下载


ring_span

Another search for the one ring.
Thanks to Björn Fahller for writing the original code, I modified it to fit my use cases and extended it to make it have ‘the usual methods’ like capacity() and clear().

Usage:

  1. std::vector<int> v;
  2. v.resize(256);
  3. nostd::ring_span rs(v);
  4. rs.push_back(1); // 'normal' push_back
  1. class Foo{ std::vector<int> values; } ;
  2. std::vector<Foo> v;
  3. v.resize(16);
  4. nostd::ring_span rs(v);
  5. Foo & foo = rs.push_back(); // modify / re-use existing elements without re-construction

features:

  • mostly constrexpr (with some obvious exceptions)
  • works on top of an existing container of choice, it must have .data() and .size()
  • allows insertion and removal without construction or destruction of contained objects
  • pushing a value beyond the capacity of the span overwrites the oldest value

restrictions:

  • requires to be used on memory area where the size is a power of 2

The restriction allows the span to be slightly more efficient.

design considerations:

  • keep the span simple
  • the span overwrites the oldest value if a value is pushed in when its full
  • minimal error handling, if needed it can layered on top, see safe_push
  1. // example added exceptions for error handling
  2. template <typename T>
  3. void safe_push(nostd::ring_span<T> rs, T v)
  4. {
  5. if (rs.size() == rs.capacity())
  6. {
  7. throw std::runtime_error("safe_push exceeds span capacity");
  8. }
  9. rs.push_back(v);
  10. }