xbot/ref.hpp

45 lines
1.1 KiB
C++
Raw Normal View History

2025-01-28 19:04:36 -08:00
#pragma once
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <memory>
2025-01-29 09:54:17 -08:00
template <typename> struct RefTraits {};
template <> struct RefTraits<EVP_PKEY> {
static constexpr void (*Free)(EVP_PKEY*) = EVP_PKEY_free;
static constexpr int (*UpRef)(EVP_PKEY*) = EVP_PKEY_up_ref;
};
template <> struct RefTraits<X509> {
static constexpr void (*Free)(X509*) = X509_free;
static constexpr int (*UpRef)(X509*) = X509_up_ref;
};
template <> struct RefTraits<EVP_PKEY_CTX> {
static constexpr void (*Free)(EVP_PKEY_CTX*) = EVP_PKEY_CTX_free;
};
template <typename T>
2025-01-28 19:04:36 -08:00
struct FnDeleter {
2025-01-29 09:54:17 -08:00
auto operator()(T *ptr) const -> void { RefTraits<T>::Free(ptr); }
2025-01-28 19:04:36 -08:00
};
2025-01-29 09:54:17 -08:00
template <typename T>
struct Ref : std::unique_ptr<T, FnDeleter<T>> {
using std::unique_ptr<T, FnDeleter<T>>::unique_ptr;
Ref(const Ref &ref) {
*this = ref;
}
Ref &operator=(const Ref &ref) {
RefTraits<T>::UpRef(ref.get());
this->reset(ref.get());
return *this;
}
};
2025-01-28 19:04:36 -08:00
2025-01-29 09:54:17 -08:00
using EVP_PKEY_CTX_Ref = Ref<EVP_PKEY_CTX>;
using X509_Ref = Ref<X509>;
using EVP_PKEY_Ref = Ref<EVP_PKEY>;