2021-01-16 17:18:58 +01:00
|
|
|
/*
|
2024-10-04 13:19:50 +02:00
|
|
|
* Copyright (c) 2021, Andreas Kling <andreas@ladybird.org>
|
2022-02-26 09:09:45 -07:00
|
|
|
* Copyright (c) 2022, the SerenityOS developers.
|
2021-01-16 17:18:58 +01:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2021-01-16 17:18:58 +01:00
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2021-11-06 01:20:51 +01:00
|
|
|
#include <AK/Error.h>
|
2021-01-16 17:18:58 +01:00
|
|
|
#include <AK/Noncopyable.h>
|
|
|
|
#include <AK/RefCounted.h>
|
|
|
|
#include <AK/RefPtr.h>
|
|
|
|
#include <AK/Types.h>
|
|
|
|
|
|
|
|
namespace Core {
|
|
|
|
|
|
|
|
class AnonymousBufferImpl final : public RefCounted<AnonymousBufferImpl> {
|
|
|
|
public:
|
2024-10-27 18:13:42 +05:00
|
|
|
static ErrorOr<NonnullRefPtr<AnonymousBufferImpl>> create(size_t);
|
2021-11-06 01:20:51 +01:00
|
|
|
static ErrorOr<NonnullRefPtr<AnonymousBufferImpl>> create(int fd, size_t);
|
2021-01-16 17:18:58 +01:00
|
|
|
~AnonymousBufferImpl();
|
|
|
|
|
|
|
|
int fd() const { return m_fd; }
|
|
|
|
size_t size() const { return m_size; }
|
|
|
|
void* data() { return m_data; }
|
2022-04-01 20:58:27 +03:00
|
|
|
void const* data() const { return m_data; }
|
2021-01-16 17:18:58 +01:00
|
|
|
|
|
|
|
private:
|
|
|
|
AnonymousBufferImpl(int fd, size_t, void*);
|
|
|
|
|
|
|
|
int m_fd { -1 };
|
|
|
|
size_t m_size { 0 };
|
|
|
|
void* m_data { nullptr };
|
|
|
|
};
|
|
|
|
|
|
|
|
class AnonymousBuffer {
|
|
|
|
public:
|
2021-11-06 01:20:51 +01:00
|
|
|
static ErrorOr<AnonymousBuffer> create_with_size(size_t);
|
|
|
|
static ErrorOr<AnonymousBuffer> create_from_anon_fd(int fd, size_t);
|
2021-01-16 17:18:58 +01:00
|
|
|
|
2022-02-26 09:09:45 -07:00
|
|
|
AnonymousBuffer() = default;
|
2021-01-16 17:18:58 +01:00
|
|
|
|
|
|
|
bool is_valid() const { return m_impl; }
|
|
|
|
|
|
|
|
int fd() const { return m_impl ? m_impl->fd() : -1; }
|
|
|
|
size_t size() const { return m_impl ? m_impl->size() : 0; }
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
T* data()
|
|
|
|
{
|
2021-04-10 18:29:06 +04:30
|
|
|
static_assert(IsVoid<T> || IsTrivial<T>);
|
2021-01-16 17:18:58 +01:00
|
|
|
if (!m_impl)
|
|
|
|
return nullptr;
|
|
|
|
return (T*)m_impl->data();
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
2022-10-17 00:06:11 +02:00
|
|
|
T const* data() const
|
2021-01-16 17:18:58 +01:00
|
|
|
{
|
2021-04-10 18:29:06 +04:30
|
|
|
static_assert(IsVoid<T> || IsTrivial<T>);
|
2021-01-16 17:18:58 +01:00
|
|
|
if (!m_impl)
|
|
|
|
return nullptr;
|
2022-10-17 00:06:11 +02:00
|
|
|
return (T const*)m_impl->data();
|
2021-01-16 17:18:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2024-10-27 18:13:42 +05:00
|
|
|
explicit AnonymousBuffer(NonnullRefPtr<AnonymousBufferImpl> impl)
|
|
|
|
: m_impl(move(impl))
|
|
|
|
{
|
|
|
|
}
|
2021-01-16 17:18:58 +01:00
|
|
|
|
|
|
|
RefPtr<AnonymousBufferImpl> m_impl;
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|