TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : // Copyright (c) 2026 Steve Gerbino
5 : // Copyright (c) 2026 Andrzej Krzemieński
6 : //
7 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 : //
10 : // Official repository: https://github.com/cppalliance/capy
11 : //
12 :
13 : #ifndef BOOST_CAPY_BUFFERS_HPP
14 : #define BOOST_CAPY_BUFFERS_HPP
15 :
16 : #include <boost/capy/detail/config.hpp>
17 : #include <concepts>
18 : #include <cstddef>
19 : #include <iterator>
20 : #include <memory>
21 : #include <ranges>
22 : #include <type_traits>
23 :
24 : // https://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/reference/ConstBufferSequence.html
25 :
26 : namespace boost {
27 :
28 : namespace asio {
29 : class const_buffer;
30 : class mutable_buffer;
31 : } // asio
32 :
33 : namespace capy {
34 :
35 : class const_buffer;
36 : class mutable_buffer;
37 :
38 : /** A reference to a contiguous region of writable memory.
39 :
40 : Represents a pointer and size pair for a modifiable byte range.
41 : Does not own, allocate, or copy the memory: copying a buffer copies
42 : the pointer and size only. The memory must stay valid until every
43 : operation using the buffer completes. Satisfies
44 : `MutableBufferSequence` (as a single-element sequence) and is
45 : implicitly convertible to `const_buffer`.
46 :
47 : @see @ref const_buffer, @ref MutableBufferSequence
48 : */
49 : class mutable_buffer
50 : {
51 : unsigned char* p_ = nullptr;
52 : std::size_t n_ = 0;
53 :
54 : public:
55 : /// Construct an empty buffer.
56 HIT 22 : mutable_buffer() = default;
57 :
58 : /** Construct a copy.
59 :
60 : @param other The buffer to copy.
61 : */
62 : mutable_buffer(
63 : mutable_buffer const& other) = default;
64 :
65 : /** Assign by copying.
66 :
67 : @param other The buffer to copy.
68 :
69 : @return A reference to `*this`.
70 : */
71 : mutable_buffer& operator=(
72 : mutable_buffer const& other) = default;
73 :
74 : /** Construct from a pointer and size.
75 :
76 : Takes `void*` so a pointer to any object type binds without a
77 : cast, since the buffer represents a raw, untyped writable
78 : region. Stored internally as `unsigned char*` for byte-wise
79 : pointer arithmetic (see `operator+=`).
80 :
81 : @param data A pointer to the first byte of the region.
82 :
83 : @param size The size of the region, in bytes.
84 : */
85 35253 : constexpr mutable_buffer(
86 : void* data, std::size_t size) noexcept
87 35253 : : p_(static_cast<unsigned char*>(data))
88 35253 : , n_(size)
89 : {
90 35253 : }
91 :
92 : /** Return a pointer to the memory region.
93 :
94 : Returns `void*`, symmetric with the constructor, so the
95 : caller can reinterpret the raw region as whatever type it needs.
96 :
97 : @return A pointer to the first byte of the region.
98 : */
99 53966 : constexpr void* data() const noexcept
100 : {
101 53966 : return p_;
102 : }
103 :
104 : /** Return the size in bytes.
105 :
106 : @return The size of the region, in bytes.
107 : */
108 80459 : constexpr std::size_t size() const noexcept
109 : {
110 80459 : return n_;
111 : }
112 :
113 : /** Advance the buffer start, shrinking the region.
114 :
115 : @param n Bytes to skip. Clamped to `size()`.
116 :
117 : @return A reference to `*this`.
118 : */
119 : mutable_buffer&
120 17706 : operator+=(std::size_t n) noexcept
121 : {
122 17706 : if( n > n_)
123 1 : n = n_;
124 17706 : p_ += n;
125 17706 : n_ -= n;
126 17706 : return *this;
127 : }
128 : };
129 :
130 : /** A reference to a contiguous region of read-only memory.
131 :
132 : Represents a pointer and size pair for a non-modifiable byte range.
133 : Does not own, allocate, or copy the memory: copying a buffer copies
134 : the pointer and size only. The memory must stay valid until every
135 : operation using the buffer completes. Satisfies
136 : `ConstBufferSequence` (as a single-element sequence). Implicitly
137 : constructible from `mutable_buffer`.
138 :
139 : @see @ref mutable_buffer, @ref ConstBufferSequence
140 : */
141 : class const_buffer
142 : {
143 : unsigned char const* p_ = nullptr;
144 : std::size_t n_ = 0;
145 :
146 : public:
147 : /// Construct an empty buffer.
148 58 : const_buffer() = default;
149 :
150 : /** Construct a copy.
151 :
152 : @param other The buffer to copy.
153 : */
154 : const_buffer(const_buffer const& other) = default;
155 :
156 : /** Assign by copying.
157 :
158 : @param other The buffer to copy.
159 :
160 : @return A reference to `*this`.
161 : */
162 : const_buffer& operator=(
163 : const_buffer const& other) = default;
164 :
165 : /** Construct from a pointer and size.
166 :
167 : Takes `void const*` so a pointer to any object type binds
168 : without a cast, since the buffer represents a raw, untyped
169 : read-only region. Stored internally as `unsigned char const*`
170 : for byte-wise pointer arithmetic (see `operator+=`).
171 :
172 : @param data A pointer to the first byte of the region.
173 :
174 : @param size The size of the region, in bytes.
175 : */
176 31994 : constexpr const_buffer(
177 : void const* data, std::size_t size) noexcept
178 31994 : : p_(static_cast<unsigned char const*>(data))
179 31994 : , n_(size)
180 : {
181 31994 : }
182 :
183 : /** Construct from mutable_buffer.
184 :
185 : @param b The writable buffer whose region is referenced.
186 : */
187 7852 : constexpr const_buffer(
188 : mutable_buffer const& b) noexcept
189 7852 : : p_(static_cast<unsigned char const*>(b.data()))
190 7852 : , n_(b.size())
191 : {
192 7852 : }
193 :
194 : /** Return a pointer to the memory region.
195 :
196 : Returns `void const*`, symmetric with the constructor, so the
197 : caller can reinterpret the raw region as whatever type it needs.
198 :
199 : @return A pointer to the first byte of the region.
200 : */
201 46530 : constexpr void const* data() const noexcept
202 : {
203 46530 : return p_;
204 : }
205 :
206 : /** Return the size in bytes.
207 :
208 : @return The size of the region, in bytes.
209 : */
210 78372 : constexpr std::size_t size() const noexcept
211 : {
212 78372 : return n_;
213 : }
214 :
215 : /** Advance the buffer start, shrinking the region.
216 :
217 : @param n Bytes to skip. Clamped to `size()`.
218 :
219 : @return A reference to `*this`.
220 : */
221 : const_buffer&
222 17351 : operator+=(std::size_t n) noexcept
223 : {
224 17351 : if( n > n_)
225 1 : n = n_;
226 17351 : p_ += n;
227 17351 : n_ -= n;
228 17351 : return *this;
229 : }
230 : };
231 :
232 : /** Type recognized by the library as a _buffer_ (a handle to contiguous memory region)
233 : with const access to data.
234 :
235 : @par Semantic Requirements
236 :
237 : After the conversion to @ref const_buffer `b`, `b.data()` and `b.size()`
238 : designate a valid contiguous memory region. The region shall remain valid
239 : for the duration of an operation represented by the concept-constrained
240 : function template call.
241 :
242 : @note Function templates in this library constrained by this concept,
243 : such as @ref buffer_size, are often `noexcept`, so if this conversion
244 : throws, this results in calling `std::terminate()`.
245 :
246 : @note `std::convertible_to` implies that @ref const_buffer
247 : can also be explicitly constructed from `T const&` with the same effect as the
248 : implicit conversion.
249 :
250 : @see @ref const_buffer, @ref MutableBuffer
251 : */
252 : template<typename T>
253 : concept ConstBuffer =
254 : std::convertible_to<T const&, const_buffer>;
255 :
256 : /** Type recognized by the library as a _buffer_ (a handle to contiguous memory region)
257 : with mutable access to data.
258 :
259 : @par Semantic Requirements
260 :
261 : After the conversion to @ref mutable_buffer or @ref const_buffer `b`, `b.data()` and `b.size()`
262 : designate a valid contiguous memory region. The region shall remain valid
263 : for the duration of an operation represented by the concept-constrained
264 : function template call.
265 :
266 : @note Function templates in this library constrained by this concept,
267 : such as @ref buffer_size, are often `noexcept`, so if this conversion
268 : throws, this results in calling `std::terminate()`.
269 :
270 : @note `std::convertible_to` implies that @ref mutable_buffer
271 : can also be explicitly constructed from `T const&` with the same effect as the
272 : implicit conversion.
273 :
274 : @see @ref mutable_buffer, @ref ConstBuffer
275 : */
276 : template<typename T>
277 : concept MutableBuffer =
278 : ConstBuffer<T> && std::convertible_to<T const&, mutable_buffer>;
279 :
280 : /** Type recognized by the library as a _sequence_ of buffers with const access to data:
281 : either a type modelling @ref ConstBuffer or a range thereof.
282 :
283 : @par Semantic Requirements
284 :
285 : A copy-constructed buffer sequence shall refer to the same contiguous memory regions as the original.
286 : This can be expressed as:
287 :
288 : @code
289 : bool copy_postcondition(ConstBufferSequence auto const& x)
290 : {
291 : ConstBufferSequence auto y = x;
292 : return std::equal(
293 : buffer_sequence_begin(x), buffer_sequence_end(x),
294 : buffer_sequence_begin(y), buffer_sequence_end(y),
295 : [](const const_buffer& bx, const const_buffer& by)
296 : {
297 : return bx.data() == by.data()
298 : && bx.size() == by.size();
299 : }
300 : );
301 : }
302 : @endcode
303 :
304 : If a type models both @ref ConstBuffer and a range thereof,
305 : then it is treated as @ref ConstBuffer.
306 :
307 : @note Function templates in this library constrained by this concept,
308 : such as @ref buffer_size, are often `noexcept`, so if the operations used
309 : to iterate over the buffer range -- such as `.begin()` or the iterator API --
310 : throw, this results in calling `std::terminate()`.
311 :
312 : @see @ref const_buffer, @ref MutableBufferSequence
313 : */
314 : // tag::const_buffer_sequence_concept[]
315 : template<typename T>
316 : concept ConstBufferSequence =
317 : std::copy_constructible<T> && (
318 : ConstBuffer<T> || (
319 : std::ranges::bidirectional_range<T> &&
320 : ConstBuffer<std::ranges::range_value_t<T>>));
321 : // end::const_buffer_sequence_concept[]
322 :
323 : /** Type recognized by the library as a _sequence_ of buffers with mutable access to data:
324 : either a type modelling @ref MutableBuffer or a range thereof.
325 :
326 : @par Semantic Requirements
327 :
328 : If a type models both @ref MutableBuffer and a range thereof,
329 : then it is treated as @ref MutableBuffer.
330 :
331 : @note A type satisfying @ref ConstBuffer is never considered to be a range of
332 : mutable buffers.
333 :
334 : @note Function templates in this library constrained by this concept,
335 : such as @ref buffer_size, are often `noexcept`, so if the operations used
336 : to iterate over the buffer range — such as `.begin()` or the iterator API —
337 : throw, this results in calling `std::terminate()`.
338 :
339 : @see @ref mutable_buffer, @ref ConstBufferSequence
340 : */
341 : // tag::mutable_buffer_sequence_concept[]
342 : template<typename T>
343 : concept MutableBufferSequence =
344 : ConstBufferSequence<T> && (MutableBuffer<T> || (
345 : !ConstBuffer<T> &&
346 : std::ranges::bidirectional_range<T> &&
347 : MutableBuffer<std::ranges::range_value_t<T>>));
348 : // end::mutable_buffer_sequence_concept[]
349 :
350 : /** Return an iterator to the first buffer in a sequence.
351 :
352 : @functionobject
353 : */
354 : constexpr struct
355 : {
356 : /** Return a pointer to a single buffer, forming a one-element range.
357 :
358 : @param b A single buffer.
359 :
360 : @return A pointer to `b`.
361 : */
362 : template<ConstBuffer ConvertibleToBuffer>
363 6646 : auto operator()(ConvertibleToBuffer const& b) const noexcept -> ConvertibleToBuffer const*
364 : {
365 6646 : return std::addressof(b);
366 : }
367 :
368 : /** Return an iterator to the first buffer of a sequence.
369 :
370 : @param bs The buffer sequence.
371 :
372 : @return An iterator to the first buffer of `bs`.
373 : */
374 : template<ConstBufferSequence BS>
375 : requires (!ConstBuffer<BS>)
376 33653 : auto operator()(BS const& bs) const noexcept
377 : {
378 33653 : return std::ranges::begin(bs);
379 : }
380 :
381 : /** Return an iterator to the first buffer of a sequence.
382 :
383 : @param bs The buffer sequence.
384 :
385 : @return An iterator to the first buffer of `bs`.
386 : */
387 : template<ConstBufferSequence BS>
388 : requires (!ConstBuffer<BS>)
389 9196 : auto operator()(BS& bs) const noexcept
390 : {
391 9196 : return std::ranges::begin(bs);
392 : }
393 : } buffer_sequence_begin {};
394 :
395 : /** Return an iterator past the last buffer in a sequence.
396 :
397 : @functionobject
398 : */
399 : constexpr struct
400 : {
401 : /** Return a pointer one past a single buffer, forming a one-element range.
402 :
403 : @param b A single buffer.
404 :
405 : @return A pointer one past `b`.
406 : */
407 : template<ConstBuffer ConvertibleToBuffer>
408 6649 : auto operator()(ConvertibleToBuffer const& b) const noexcept -> ConvertibleToBuffer const*
409 : {
410 6649 : return std::addressof(b) + 1;
411 : }
412 :
413 : /** Return an iterator past the last buffer of a sequence.
414 :
415 : @param bs The buffer sequence.
416 :
417 : @return An iterator one past the last buffer of `bs`.
418 : */
419 : template<ConstBufferSequence BS>
420 : requires (!ConstBuffer<BS>)
421 33692 : auto operator()(BS const& bs) const noexcept
422 : {
423 33692 : return std::ranges::end(bs);
424 : }
425 :
426 : /** Return an iterator past the last buffer of a sequence.
427 :
428 : @param bs The buffer sequence.
429 :
430 : @return An iterator one past the last buffer of `bs`.
431 : */
432 : template<ConstBufferSequence BS>
433 : requires (!ConstBuffer<BS>)
434 9196 : auto operator()(BS& bs) const noexcept
435 : {
436 9196 : return std::ranges::end(bs);
437 : }
438 : } buffer_sequence_end {};
439 :
440 : /** Return the total byte count across all buffers in a sequence.
441 :
442 : @functionobject
443 : */
444 : constexpr struct
445 : {
446 : // GCC 13 falsely flags reads of arr_[i].n_ in detail::buffer_array
447 : // when iterating here. The class uses union storage with placement
448 : // new for slots 0..n_-1, so reads inside this bounded loop are
449 : // well-defined, but the optimizer can't prove the loop bound and
450 : // warns. The runtime cost of value-initializing all N slots is
451 : // non-trivial for non-trivial value types, so we suppress instead.
452 : #if defined(__GNUC__) && !defined(__clang__)
453 : #pragma GCC diagnostic push
454 : #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
455 : #endif
456 : /** Return the total byte count across all buffers in a sequence.
457 :
458 : Sums the `size()` of each buffer in the sequence. This differs
459 : from `buffers_count` which counts the number of buffer elements.
460 :
461 : @param bs The buffer sequence.
462 :
463 : @return The sum of the sizes of all buffers in `bs`.
464 :
465 : @par Example
466 : @par !example example
467 :
468 : */
469 : template<ConstBufferSequence CB>
470 6289 : constexpr std::size_t operator()(
471 : CB const& bs) const noexcept
472 : {
473 6289 : std::size_t n = 0;
474 6289 : auto const e = capy::buffer_sequence_end(bs);
475 14573 : for(auto it = capy::buffer_sequence_begin(bs); it != e; ++it)
476 8284 : n += const_buffer(*it).size();
477 6289 : return n;
478 : }
479 : #if defined(__GNUC__) && !defined(__clang__)
480 : #pragma GCC diagnostic pop
481 : #endif
482 : } buffer_size {};
483 :
484 : /** Check if a buffer sequence contains no data.
485 :
486 : @functionobject
487 : */
488 : constexpr struct
489 : {
490 : // See note on buffer_size above — same union-storage false positive.
491 : #if defined(__GNUC__) && !defined(__clang__)
492 : #pragma GCC diagnostic push
493 : #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
494 : #endif
495 : /** Check if a buffer sequence contains no data.
496 :
497 : @param bs The buffer sequence.
498 :
499 : @return `true` if all buffers have size zero or the sequence
500 : is empty.
501 : */
502 : template<ConstBufferSequence CB>
503 1567 : constexpr bool operator()(
504 : CB const& bs) const noexcept
505 : {
506 1567 : auto it = buffer_sequence_begin(bs);
507 1567 : auto const end_ = buffer_sequence_end(bs);
508 1615 : while(it != end_)
509 : {
510 1579 : const_buffer b(*it++);
511 1579 : if(b.size() != 0)
512 1531 : return false;
513 : }
514 36 : return true;
515 : }
516 : #if defined(__GNUC__) && !defined(__clang__)
517 : #pragma GCC diagnostic pop
518 : #endif
519 : } buffers_empty {};
520 :
521 : namespace detail {
522 :
523 : template<class It>
524 : auto
525 8 : length_impl(It first, It last, int)
526 : -> decltype(static_cast<std::size_t>(last - first))
527 : {
528 8 : return static_cast<std::size_t>(last - first);
529 : }
530 :
531 : template<class It>
532 : std::size_t
533 : length_impl(It first, It last, long)
534 : {
535 : std::size_t n = 0;
536 : while(first != last)
537 : {
538 : ++first;
539 : ++n;
540 : }
541 : return n;
542 : }
543 :
544 : } // detail
545 :
546 : /** Return the number of buffer elements in a sequence.
547 :
548 : Counts the number of individual buffer objects, not bytes.
549 : For a single buffer, returns 1. For a range, returns the
550 : distance from `buffer_sequence_begin` to `buffer_sequence_end`.
551 :
552 : @param bs The buffer sequence.
553 :
554 : @return The number of buffers in `bs`.
555 :
556 : @see @ref buffer_size
557 : */
558 : template<ConstBufferSequence CB>
559 : std::size_t
560 8 : buffers_count(CB const& bs)
561 : {
562 8 : return detail::length_impl(
563 8 : buffer_sequence_begin(bs), buffer_sequence_end(bs), 0);
564 : }
565 :
566 : /// Names `mutable_buffer` for a mutable sequence, `const_buffer` otherwise.
567 : template<typename BS>
568 : using buffer_type = std::conditional_t<
569 : MutableBufferSequence<BS>,
570 : mutable_buffer, const_buffer>;
571 :
572 : } // capy
573 : } // boost
574 :
575 : #endif
|