Skip to content

Commit

Permalink
Move ringbuffer_sink to spdlog::details::circular_q, enhance its API:…
Browse files Browse the repository at this point in the history
… size(), at(i)
  • Loading branch information
eudoxos committed Nov 8, 2019
1 parent acf32be commit 6f0cb63
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
14 changes: 14 additions & 0 deletions include/spdlog/details/circular_q.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ class circular_q
return v_[head_];
}

// Return number of elements actually stored
size_t size() const
{
return (tail_ - head_) % max_items_;
}

// Return const reference to item by index.
// If index is out of range 0…size()-1, the behavior is undefined.
const T &at(size_t i) const
{
assert(i < size());
return v_[(head_+ i) % max_items_];
}

// Pop item from front.
// If there are no elements in the container, the behavior is undefined.
void pop_front()
Expand Down
10 changes: 4 additions & 6 deletions include/spdlog/sinks/ringbuffer_sink-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,21 @@
#include "spdlog/common.h"
#include "spdlog/details/os.h"

#include<boost/circular_buffer.hpp>

namespace spdlog {
namespace sinks {

template<typename Mutex>
SPDLOG_INLINE ringbuffer_sink<Mutex>::ringbuffer_sink(size_t buf_size)
{
buf.set_capacity(buf_size);
buf=details::circular_q<std::string>(buf_size);
}

template<typename Mutex>
SPDLOG_INLINE void ringbuffer_sink<Mutex>::sink_it_(const details::log_msg &msg)
{
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
buf.push_front(fmt::to_string(formatted));
buf.push_back(fmt::to_string(formatted));
}

template<typename Mutex>
Expand All @@ -36,9 +34,9 @@ SPDLOG_INLINE std::vector<std::string> ringbuffer_sink<Mutex>::last(size_t lim)
std::vector<std::string> ret;
ret.reserve(lim);
size_t num=0;
for(const std::string& msg: buf){
for(size_t i=0; i<buf.size(); i++){
num++;
ret.push_back(msg);
ret.push_back(buf.at(i));
if(lim>0 && num==lim) break;
}
return ret;
Expand Down
5 changes: 2 additions & 3 deletions include/spdlog/sinks/ringbuffer_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@
#include "spdlog/details/null_mutex.h"
#include "spdlog/sinks/base_sink.h"
#include "spdlog/details/synchronous_factory.h"
#include "spdlog/details/circular_q.h"

#include <mutex>
#include <string>
#include <vector>

#include<boost/circular_buffer.hpp>

namespace spdlog {
namespace sinks {
/*
Expand All @@ -30,7 +29,7 @@ class ringbuffer_sink final : public base_sink<Mutex>
void flush_() override {};

private:
boost::circular_buffer<std::string> buf;
details::circular_q<std::string> buf;
};

using ringbuffer_sink_mt = ringbuffer_sink<std::mutex>;
Expand Down

0 comments on commit 6f0cb63

Please sign in to comment.