libcamera: byte_stream_buffer: Add zero-copy read() variant

Add a read() function to ByteStreamBuffer that returns a pointer to the
data instead of copying it. Overflow check is still handled by the
class, but the caller must check the returned pointer explicitly.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Reviewed-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
This commit is contained in:
Laurent Pinchart 2020-02-29 01:42:01 +02:00
parent 8a1f0321dc
commit 7f2da874cd
2 changed files with 48 additions and 0 deletions

View file

@ -241,6 +241,19 @@ int ByteStreamBuffer::skip(size_t size)
* \retval -ENOSPC no more space is available in the managed memory buffer
*/
/**
* \fn template<typename T> const T *ByteStreamBuffer::read(size_t count)
* \brief Read data from the managed memory buffer without performing a copy
* \param[in] count Number of data items to read
*
* This function reads \a count elements of type \a T from the buffer. Unlike
* the other read variants, it doesn't copy the data but returns a pointer to
* the first element. If data can't be read for any reason (usually due to
* reading more data than available), the function returns nullptr.
*
* \return A pointer to the data on success, or nullptr otherwise
*/
/**
* \fn template<typename T> int ByteStreamBuffer::write(const T *t)
* \brief Write \a t to the managed memory buffer
@ -259,6 +272,32 @@ int ByteStreamBuffer::skip(size_t size)
* \retval -ENOSPC no more space is available in the managed memory buffer
*/
const uint8_t *ByteStreamBuffer::read(size_t size, size_t count)
{
if (!read_)
return nullptr;
if (overflow_)
return nullptr;
size_t bytes;
if (__builtin_mul_overflow(size, count, &bytes)) {
setOverflow();
return nullptr;
}
if (read_ + bytes > base_ + size_) {
LOG(Serialization, Error)
<< "Unable to read " << bytes << " bytes: out of bounds";
setOverflow();
return nullptr;
}
const uint8_t *data = read_;
read_ += bytes;
return data;
}
int ByteStreamBuffer::read(uint8_t *data, size_t size)
{
if (!read_)

View file

@ -9,6 +9,7 @@
#include <stddef.h>
#include <stdint.h>
#include <type_traits>
#include <libcamera/span.h>
@ -43,6 +44,13 @@ public:
data.size_bytes());
}
template<typename T>
const std::remove_reference_t<T> *read(size_t count = 1)
{
using return_type = const std::remove_reference_t<T> *;
return reinterpret_cast<return_type>(read(sizeof(T), count));
}
template<typename T>
int write(const T *t)
{
@ -63,6 +71,7 @@ private:
void setOverflow();
int read(uint8_t *data, size_t size);
const uint8_t *read(size_t size, size_t count);
int write(const uint8_t *data, size_t size);
ByteStreamBuffer *parent_;