2018-12-31 20:04:05 +01:00
|
|
|
//
|
2024-01-01 01:07:21 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2024
|
2018-12-31 20:04:05 +01:00
|
|
|
//
|
|
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
//
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "td/utils/common.h"
|
2019-02-12 21:19:11 +01:00
|
|
|
#include "td/utils/Slice.h"
|
2018-12-31 20:04:05 +01:00
|
|
|
|
|
|
|
namespace td {
|
|
|
|
|
|
|
|
class StackAllocator {
|
2021-11-18 13:42:07 +01:00
|
|
|
public:
|
|
|
|
class AllocatorImpl {
|
|
|
|
public:
|
|
|
|
AllocatorImpl() = default;
|
|
|
|
AllocatorImpl(const AllocatorImpl &) = delete;
|
|
|
|
AllocatorImpl &operator=(const AllocatorImpl &) = delete;
|
|
|
|
AllocatorImpl(AllocatorImpl &&) = delete;
|
|
|
|
AllocatorImpl &operator=(AllocatorImpl &&) = delete;
|
|
|
|
virtual ~AllocatorImpl() = default;
|
|
|
|
|
|
|
|
virtual MutableSlice allocate(size_t size) = 0;
|
|
|
|
|
|
|
|
virtual void free_ptr(char *ptr, size_t size) = 0;
|
|
|
|
};
|
|
|
|
|
|
|
|
private:
|
2018-12-31 20:04:05 +01:00
|
|
|
class Ptr {
|
|
|
|
public:
|
2021-11-18 13:42:07 +01:00
|
|
|
Ptr(AllocatorImpl *allocator, size_t size) : allocator_(allocator), slice_(allocator_->allocate(size)) {
|
2021-11-17 13:15:40 +01:00
|
|
|
}
|
2023-05-05 12:51:19 +02:00
|
|
|
Ptr(const Ptr &) = delete;
|
|
|
|
Ptr &operator=(const Ptr &) = delete;
|
2021-11-18 13:42:07 +01:00
|
|
|
Ptr(Ptr &&other) noexcept : allocator_(other.allocator_), slice_(other.slice_) {
|
|
|
|
other.allocator_ = nullptr;
|
2021-11-17 13:15:40 +01:00
|
|
|
other.slice_ = MutableSlice();
|
|
|
|
}
|
2023-05-05 12:51:19 +02:00
|
|
|
Ptr &operator=(Ptr &&) = delete;
|
2021-11-18 13:42:07 +01:00
|
|
|
~Ptr();
|
2018-12-31 20:04:05 +01:00
|
|
|
|
|
|
|
MutableSlice as_slice() const {
|
2021-11-17 13:15:40 +01:00
|
|
|
return slice_;
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2021-11-18 13:42:07 +01:00
|
|
|
AllocatorImpl *allocator_;
|
2021-11-17 13:15:40 +01:00
|
|
|
MutableSlice slice_;
|
2018-12-31 20:04:05 +01:00
|
|
|
};
|
|
|
|
|
2021-11-18 13:42:07 +01:00
|
|
|
static AllocatorImpl *impl();
|
2021-11-17 13:15:40 +01:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
public:
|
|
|
|
static Ptr alloc(size_t size) {
|
2021-11-18 13:42:07 +01:00
|
|
|
return Ptr(impl(), size);
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace td
|