Files
android/libwvdrmengine/oemcrypto/util/include/scoped_object.h
Alex Dale 4a065adc33 Copied OEMCrypto utils to Android.
The OEMCrypto utils have been copied over from the CDM repo.
Tests have been excluded for this CL.

Files represent a snapshot taken from http://go/wvgerrit/148270
and http://go/wvgerrit/148372.

Bug: 205902021
Change-Id: I1a58952cd1436a48974367c5436bf7296163e6f1
2022-03-21 21:22:19 -07:00

71 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_
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.
ScopedObject(const ScopedObject& other) = delete;
ScopedObject& operator=(const ScopedObject& other) = delete;
// 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;
}
explicit operator bool() const { return ptr_ != nullptr; }
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;
};
} // namespace util
} // namespace wvoec
#endif // WVOEC_UTIL_SCOPED_OBJECT_H_