73 lines
1.8 KiB
C++
73 lines
1.8 KiB
C++
// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary
|
|
// source code may only be used and distributed under the Widevine License
|
|
// Agreement.
|
|
//
|
|
// Reference implementation utilities of OEMCrypto APIs
|
|
//
|
|
#ifndef WVOEC_UTIL_SCOPED_OBJECT_H_
|
|
#define WVOEC_UTIL_SCOPED_OBJECT_H_
|
|
|
|
#include "wv_class_utils.h"
|
|
|
|
namespace wvoec {
|
|
namespace util {
|
|
// A generic wrapper around pointer. This allows for automatic
|
|
// memory clean up when the ScopedObject variable goes out of scope.
|
|
// This is intended to be used with OpenSSL/BoringSSL structs.
|
|
template <typename Type, void Destructor(Type*)>
|
|
class ScopedObject {
|
|
public:
|
|
ScopedObject() : ptr_(nullptr) {}
|
|
ScopedObject(Type* ptr) : ptr_(ptr) {}
|
|
~ScopedObject() {
|
|
if (ptr_) {
|
|
Destructor(ptr_);
|
|
ptr_ = nullptr;
|
|
}
|
|
}
|
|
|
|
// Copy construction and assignment are not allowed.
|
|
WVCDM_DISALLOW_COPY(ScopedObject);
|
|
|
|
// Move construction and assignment are allowed.
|
|
ScopedObject(ScopedObject&& other) : ptr_(other.ptr_) {
|
|
other.ptr_ = nullptr;
|
|
}
|
|
ScopedObject& operator=(ScopedObject&& other) {
|
|
if (ptr_) {
|
|
Destructor(ptr_);
|
|
}
|
|
ptr_ = other.ptr_;
|
|
other.ptr_ = nullptr;
|
|
return *this;
|
|
}
|
|
|
|
bool ok() const { return ptr_ != nullptr; }
|
|
explicit operator bool() const { return ok(); }
|
|
|
|
Type& operator*() { return *ptr_; }
|
|
Type* get() const { return ptr_; }
|
|
Type* operator->() const { return ptr_; }
|
|
|
|
// Releasing the pointer will remove the responsibility of the
|
|
// ScopedObject to clean up the pointer.
|
|
Type* release() {
|
|
Type* temp = ptr_;
|
|
ptr_ = nullptr;
|
|
return temp;
|
|
}
|
|
|
|
void reset(Type* ptr = nullptr) {
|
|
if (ptr_) {
|
|
Destructor(ptr_);
|
|
}
|
|
ptr_ = ptr;
|
|
}
|
|
|
|
private:
|
|
Type* ptr_ = nullptr;
|
|
}; // class ScopedObject
|
|
} // namespace util
|
|
} // namespace wvoec
|
|
#endif // WVOEC_UTIL_SCOPED_OBJECT_H_
|