mirror of
https://github.com/ruby/ruby.git
synced 2026-10-28 16:36:20 +08:00
The C++ interface is intentionally minimal: it provides only a couple of niceties in order to largely stay out of the way. It is mostly used to provide: * RAII for opaque resources * Safe up and down casting for nodes * string_view for various resources * Iteration over resource lists Note that if consumers want to use it, they must be on C++17 at minimum. https://github.com/ruby/prism/commit/57b8dbe0e9
56 lines
1.2 KiB
C++
56 lines
1.2 KiB
C++
/**
|
|
* @file buffer.hpp
|
|
*
|
|
* Ownership of buffers from C++, and access to their contents.
|
|
*/
|
|
#ifndef PRISM_BUFFER_HPP
|
|
#define PRISM_BUFFER_HPP
|
|
|
|
#include "prism/compiler/cplusplus.hpp"
|
|
#include "prism/compiler/lifetimebound.hpp"
|
|
|
|
#include "prism/buffer.h"
|
|
|
|
#include <memory>
|
|
#include <string_view>
|
|
|
|
namespace prism {
|
|
|
|
/** Frees a buffer with pm_buffer_free. */
|
|
struct buffer_deleter {
|
|
/**
|
|
* Frees the given buffer.
|
|
*
|
|
* @param buffer The buffer to free.
|
|
*/
|
|
void operator()(pm_buffer_t *buffer) const noexcept { pm_buffer_free(buffer); }
|
|
};
|
|
|
|
/** An owned buffer. */
|
|
using unique_buffer = std::unique_ptr<pm_buffer_t, buffer_deleter>;
|
|
|
|
/**
|
|
* Allocate a new empty buffer. Allocation failure aborts, so this never throws.
|
|
*
|
|
* @return A unique_buffer managing the newly allocated buffer.
|
|
*/
|
|
[[nodiscard]] inline unique_buffer
|
|
make_buffer() noexcept {
|
|
return unique_buffer(pm_buffer_new());
|
|
}
|
|
|
|
/**
|
|
* The bytes written to the given buffer so far.
|
|
*
|
|
* @param buffer The buffer to view.
|
|
* @return A string_view of the contents of the buffer.
|
|
*/
|
|
[[nodiscard]] inline std::string_view
|
|
view(const pm_buffer_t *buffer PRISM_LIFETIMEBOUND) noexcept {
|
|
return std::string_view(pm_buffer_value(buffer), pm_buffer_length(buffer));
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|