Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Buffer.cpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2021 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#include "Buffer.hpp"
18
19namespace toolbox {
20inline namespace io {
21
22void Buffer::consume(std::size_t count) noexcept
23{
24 enum { ShrinkThreshold = 1024 };
25
26 if (count == 0) {
27 return;
28 }
29 rpos_ += count;
30
31 // Shrink if the block of unused bytes at the front of the buffer satisfies the following
32 // requirements: 1) greater than or equal to ShrinkThreshold, 1) greater than or equal to half
33 // the total buffer size.
34 if (rpos_ >= ShrinkThreshold && rpos_ >= (buf_.size() >> 1)) {
35
36 // Then move unread portion to front.
37 const auto n = size();
38 if (n > 0) {
39 // Move data to front.
40 std::memmove(buf_.data(), rptr(), n);
41 }
42
43 rpos_ = 0;
44 wpos_ = n;
45 }
46}
47
48ConstBuffer advance(ConstBuffer buf, std::size_t n) noexcept
49{
50 const auto* const data = buffer_cast<const char*>(buf);
51 const std::size_t size = buffer_size(buf);
52 const auto offset = std::min(n, size);
53 return {data + offset, size - offset};
54}
55
56MutableBuffer advance(MutableBuffer buf, std::size_t n) noexcept
57{
58 auto* const data = buffer_cast<char*>(buf);
59 const std::size_t size = buffer_size(buf);
60 const auto offset = std::min(n, size);
61 return {data + offset, size - offset};
62}
63
64} // namespace io
65} // namespace toolbox
void consume(std::size_t count) noexcept
Remove characters from the read sequence.
Definition Buffer.cpp:22
boost::asio::const_buffer ConstBuffer
Definition Buffer.hpp:28
boost::asio::mutable_buffer MutableBuffer
Definition Buffer.hpp:29
const DataT & data(const MsgEvent &ev) noexcept
Definition Event.hpp:54
ConstBuffer advance(ConstBuffer buf, std::size_t n) noexcept
Definition Buffer.cpp:48
constexpr std::size_t size(const detail::Struct< detail::Member< TagsT, ValuesT >... > &s)
Definition Struct.hpp:98
constexpr auto bind() noexcept
Definition Slot.hpp:92