Path: blob/master/thirdparty/icu4c/common/capi_helper.h
9903 views
// © 2018 and later: Unicode, Inc. and others.1// License & terms of use: http://www.unicode.org/copyright.html23#ifndef __CAPI_HELPER_H__4#define __CAPI_HELPER_H__56#include "unicode/utypes.h"78U_NAMESPACE_BEGIN910/**11* An internal helper class to help convert between C and C++ APIs.12*/13template<typename CType, typename CPPType, int32_t kMagic>14class IcuCApiHelper {15public:16/**17* Convert from the C type to the C++ type (const version).18*/19static const CPPType* validate(const CType* input, UErrorCode& status);2021/**22* Convert from the C type to the C++ type (non-const version).23*/24static CPPType* validate(CType* input, UErrorCode& status);2526/**27* Convert from the C++ type to the C type (const version).28*/29const CType* exportConstForC() const;3031/**32* Convert from the C++ type to the C type (non-const version).33*/34CType* exportForC();3536/**37* Invalidates the object.38*/39~IcuCApiHelper();4041private:42/**43* While the object is valid, fMagic equals kMagic.44*/45int32_t fMagic = kMagic;46};474849template<typename CType, typename CPPType, int32_t kMagic>50const CPPType*51IcuCApiHelper<CType, CPPType, kMagic>::validate(const CType* input, UErrorCode& status) {52if (U_FAILURE(status)) {53return nullptr;54}55if (input == nullptr) {56status = U_ILLEGAL_ARGUMENT_ERROR;57return nullptr;58}59auto* impl = reinterpret_cast<const CPPType*>(input);60if (static_cast<const IcuCApiHelper<CType, CPPType, kMagic>*>(impl)->fMagic != kMagic) {61status = U_INVALID_FORMAT_ERROR;62return nullptr;63}64return impl;65}6667template<typename CType, typename CPPType, int32_t kMagic>68CPPType*69IcuCApiHelper<CType, CPPType, kMagic>::validate(CType* input, UErrorCode& status) {70auto* constInput = static_cast<const CType*>(input);71auto* validated = validate(constInput, status);72return const_cast<CPPType*>(validated);73}7475template<typename CType, typename CPPType, int32_t kMagic>76const CType*77IcuCApiHelper<CType, CPPType, kMagic>::exportConstForC() const {78return reinterpret_cast<const CType*>(static_cast<const CPPType*>(this));79}8081template<typename CType, typename CPPType, int32_t kMagic>82CType*83IcuCApiHelper<CType, CPPType, kMagic>::exportForC() {84return reinterpret_cast<CType*>(static_cast<CPPType*>(this));85}8687template<typename CType, typename CPPType, int32_t kMagic>88IcuCApiHelper<CType, CPPType, kMagic>::~IcuCApiHelper() {89// head off application errors by preventing use of of deleted objects.90fMagic = 0;91}929394U_NAMESPACE_END9596#endif // __CAPI_HELPER_H__979899