From 89bea931cd01fdfec098068d05640a71c267e72a Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 11 Mar 2023 00:27:08 +0100 Subject: [PATCH] libluna: Add a very simple Buffer class, to help implement tmpfs files --- libluna/CMakeLists.txt | 1 + libluna/include/luna/Buffer.h | 40 +++++++++++++++++++++++++++++++++++ libluna/src/Buffer.cpp | 40 +++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 libluna/include/luna/Buffer.h create mode 100644 libluna/src/Buffer.cpp diff --git a/libluna/CMakeLists.txt b/libluna/CMakeLists.txt index 2ce5bb85..067e2a83 100644 --- a/libluna/CMakeLists.txt +++ b/libluna/CMakeLists.txt @@ -10,6 +10,7 @@ set(FREESTANDING_SOURCES src/Units.cpp src/SystemError.cpp src/Bitmap.cpp + src/Buffer.cpp src/Stack.cpp src/OwnedStringView.cpp src/Utf8.cpp diff --git a/libluna/include/luna/Buffer.h b/libluna/include/luna/Buffer.h new file mode 100644 index 00000000..db42ce89 --- /dev/null +++ b/libluna/include/luna/Buffer.h @@ -0,0 +1,40 @@ +#pragma once +#include +#include + +class Buffer +{ + public: + Buffer(); + ~Buffer(); + + Buffer(Buffer&& other); + Buffer(const Buffer& other) = delete; // For now. + + static Result create_sized(usize size); + + Result try_resize(usize new_size); + + Result create_slice_at_end(usize size); + + u8* data() + { + return m_data; + } + + const u8* data() const + { + return m_data; + } + + usize size() const + { + return m_size; + } + + private: + Buffer(u8* data, usize size); + + u8* m_data { nullptr }; + usize m_size { 0 }; +}; diff --git a/libluna/src/Buffer.cpp b/libluna/src/Buffer.cpp new file mode 100644 index 00000000..a54e1c2d --- /dev/null +++ b/libluna/src/Buffer.cpp @@ -0,0 +1,40 @@ +#include +#include + +Buffer::Buffer() +{ +} + +Buffer::Buffer(u8* data, usize size) : m_data(data), m_size(size) +{ +} + +Buffer::Buffer(Buffer&& other) : m_data(other.data()), m_size(other.size()) +{ + other.m_data = nullptr; +} + +Buffer::~Buffer() +{ + if (m_data) free_impl(m_data); +} + +Result Buffer::create_sized(usize size) +{ + u8* data = (u8*)TRY(malloc_impl(size)); + return Buffer { data, size }; +} + +Result Buffer::try_resize(usize new_size) +{ + m_data = (u8*)TRY(realloc_impl(m_data, new_size)); + m_size = new_size; + return {}; +} + +Result Buffer::create_slice_at_end(usize size) +{ + usize old_size = m_size; + TRY(try_resize(m_size + size)); + return m_data + old_size; +}