static_buffer.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // Copyright (c) 2019-2025 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MYSQL_IMPL_INTERNAL_PROTOCOL_STATIC_BUFFER_HPP
  8. #define BOOST_MYSQL_IMPL_INTERNAL_PROTOCOL_STATIC_BUFFER_HPP
  9. // A very simplified variable-length buffer with fixed max-size
  10. #include <boost/assert.hpp>
  11. #include <boost/core/span.hpp>
  12. #include <array>
  13. #include <cstddef>
  14. #include <cstdint>
  15. #include <cstring>
  16. namespace boost {
  17. namespace mysql {
  18. namespace detail {
  19. template <std::size_t N>
  20. class static_buffer
  21. {
  22. std::array<std::uint8_t, N> buffer_{};
  23. std::size_t size_{};
  24. public:
  25. // Allow inspecting the supplied template argument
  26. static constexpr std::size_t max_size = N;
  27. // Constructors
  28. static_buffer() = default;
  29. static_buffer(std::size_t sz) noexcept : size_(sz) { BOOST_ASSERT(sz <= size_); }
  30. // Size and data
  31. std::size_t size() const noexcept { return size_; }
  32. const std::uint8_t* data() const noexcept { return buffer_.data(); }
  33. std::uint8_t* data() noexcept { return buffer_.data(); }
  34. // Modifiers
  35. void append(span<const std::uint8_t> data) noexcept
  36. {
  37. if (!data.empty())
  38. {
  39. std::size_t new_size = size_ + data.size();
  40. BOOST_ASSERT(new_size <= N);
  41. std::memcpy(buffer_.data() + size_, data.data(), data.size());
  42. size_ = new_size;
  43. }
  44. }
  45. void clear() noexcept { size_ = 0; }
  46. };
  47. } // namespace detail
  48. } // namespace mysql
  49. } // namespace boost
  50. #endif