add usd-21-11-win64_py39

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:43:55 +01:00
1 parent 41d23e71ba
commit ba5e1f7e67
15684 files changed
+3069957

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
//
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ANY_UNIQUE_PTR_H
#define PXR_BASE_TF_ANY_UNIQUE_PTR_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
/// A simple type-erased container that provides only destruction, moves and
/// immutable, untyped access to the held value.
///
/// There are a couple of facilities that provide fallback or default values
/// in error cases. TfAnyUniquePtr exists to hold these oft-instantiated but
/// rarely accessed values. As such, its design prioritizes compile-time
/// overhead over runtime performance and avoids clever metaprogramming.
/// Please resist the urge to add functionality to this class (e.g. small
/// object optimization, boost::python interoperability.)
class TfAnyUniquePtr
{
public:
template <typename T>
static TfAnyUniquePtr New() {
static_assert(!std::is_array<T>::value, "Array types not supported");
return TfAnyUniquePtr(new T());
}
template <typename T>
static TfAnyUniquePtr New(T const &v) {
static_assert(!std::is_array<T>::value, "Array types not supported");
return TfAnyUniquePtr(new T(v));
}
TfAnyUniquePtr(TfAnyUniquePtr &&other)
: _ptr(other._ptr)
, _delete(other._delete)
{
other._ptr = nullptr;
// We don't set other._delete to nullptr here on purpose. Invoking
// delete on a null pointer is not an error so if we can ensure that
// _delete is never null we can call it unconditionally.
}
TfAnyUniquePtr& operator=(TfAnyUniquePtr &&other) {
if (this != &other) {
_delete(_ptr);
_ptr = other._ptr;
_delete = other._delete;
other._ptr = nullptr;
}
return *this;
}
TfAnyUniquePtr(TfAnyUniquePtr const&) = delete;
TfAnyUniquePtr& operator=(TfAnyUniquePtr const&) = delete;
~TfAnyUniquePtr() {
_delete(_ptr);
}
/// Return a pointer to the owned object.
void const *Get() const {
return _ptr;
}
private:
template <typename T>
explicit TfAnyUniquePtr(T const *ptr)
: _ptr(ptr)
, _delete(&_Delete<T>)
{}
template <typename T>
static void _Delete(void const *ptr) {
delete static_cast<T const *>(ptr);
}
private:
void const *_ptr;
void (*_delete)(void const *);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+317
View File
@@ -0,0 +1,317 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ANY_WEAK_PTR_H
#define PXR_BASE_TF_ANY_WEAK_PTR_H
/// \file tf/anyWeakPtr.h
/// \ingroup group_tf_Memory
/// Type independent WeakPtr holder class
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/cxxCast.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/weakPtr.h"
#ifdef PXR_PYTHON_SUPPORT_ENABLED
#include "pxr/base/tf/pyUtils.h"
#include <boost/python/object.hpp>
#endif // PXR_PYTHON_SUPPORT_ENABLED
#include <boost/operators.hpp>
#include <cstddef>
#include <type_traits>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfAnyWeakPtr
///
/// Provides the ability to hold an arbitrary TfWeakPtr in a non-type-specific
/// manner in order to observe whether it has expired or not
class TfAnyWeakPtr : boost::totally_ordered<TfAnyWeakPtr>
{
struct _Data {
void* space[4];
};
public:
typedef TfAnyWeakPtr This;
/// Construct an AnyWeakPtr watching \a ptr.
template <class Ptr, class = typename
std::enable_if<Tf_SupportsWeakPtr<
typename Ptr::DataType>::value>::type>
TfAnyWeakPtr(Ptr const &ptr) {
static_assert(sizeof(_PointerHolder<Ptr>) <= sizeof(_Data),
"Ptr is too big to fit in a TfAnyWeakPtr");
new (&_ptrStorage) _PointerHolder<Ptr>(ptr);
}
/// Construct an AnyWeakPtr not watching any \a ptr.
TfAnyWeakPtr() {
static_assert(sizeof(_EmptyHolder) <= sizeof(_Data),
"Ptr is too big to fit in a TfAnyWeakPtr");
new (&_ptrStorage) _EmptyHolder;
}
/// Construct and implicitly convert from TfNullPtr.
TfAnyWeakPtr(TfNullPtrType) : TfAnyWeakPtr() {}
/// Construct and implicitly convert from std::nullptr_t.
TfAnyWeakPtr(std::nullptr_t) : TfAnyWeakPtr() {}
TfAnyWeakPtr(TfAnyWeakPtr const &other) {
other._Get()->Clone(&_ptrStorage);
}
TfAnyWeakPtr &operator=(TfAnyWeakPtr const &other) {
if (this != &other) {
_Get()->~_PointerHolderBase();
other._Get()->Clone(&_ptrStorage);
}
return *this;
}
~TfAnyWeakPtr() {
_Get()->~_PointerHolderBase();
}
/// Return true *only* if this expiry checker is watching a weak pointer
/// which has expired.
TF_API bool IsInvalid() const;
/// Return the unique identifier of the WeakPtr this AnyWeakPtr contains
TF_API void const *GetUniqueIdentifier() const;
/// Return the TfWeakBase object of the WeakPtr we are holding
TF_API TfWeakBase const *GetWeakBase() const;
/// bool operator
TF_API operator bool() const;
/// operator !
TF_API bool operator !() const;
/// equality operator
TF_API bool operator ==(const TfAnyWeakPtr &rhs) const;
/// comparison operator
TF_API bool operator <(const TfAnyWeakPtr &rhs) const;
/// returns the type_info of the underlying WeakPtr
TF_API const std::type_info & GetTypeInfo() const;
/// Returns the TfType of the underlying WeakPtr.
TF_API TfType const& GetType() const;
/// Return a hash value for this instance.
size_t GetHash() const {
return reinterpret_cast<uintptr_t>(GetUniqueIdentifier()) >> 3;
}
private:
#ifdef PXR_PYTHON_SUPPORT_ENABLED
// This grants friend access to a function in the wrapper file for this
// class. This lets the wrapper reach down into an AnyWeakPtr to get a
// boost::python wrapped object corresponding to the held type. This
// facility is necessary to get the python API we want.
friend boost::python::api::object
Tf_GetPythonObjectFromAnyWeakPtr(This const &self);
TF_API
boost::python::api::object _GetPythonObject() const;
#endif // PXR_PYTHON_SUPPORT_ENABLED
template <class WeakPtr>
friend WeakPtr TfAnyWeakPtrDynamicCast(const TfAnyWeakPtr &anyWeak, WeakPtr*);
// This is using the standard type-erasure pattern.
struct _PointerHolderBase {
TF_API virtual ~_PointerHolderBase();
virtual void Clone(_Data *target) const = 0;
virtual bool IsInvalid() const = 0;
virtual void const * GetUniqueIdentifier() const = 0;
virtual TfWeakBase const *GetWeakBase() const = 0;
virtual operator bool() const = 0;
virtual bool _IsConst() const = 0;
#ifdef PXR_PYTHON_SUPPORT_ENABLED
virtual boost::python::api::object GetPythonObject() const = 0;
#endif // PXR_PYTHON_SUPPORT_ENABLED
virtual const std::type_info & GetTypeInfo() const = 0;
virtual TfType const& GetType() const = 0;
virtual const void* _GetMostDerivedPtr() const = 0;
virtual bool _IsPolymorphic() const = 0;
};
struct _EmptyHolder : _PointerHolderBase {
TF_API virtual ~_EmptyHolder();
TF_API virtual void Clone(_Data *target) const;
TF_API virtual bool IsInvalid() const;
TF_API virtual void const * GetUniqueIdentifier() const;
TF_API virtual TfWeakBase const *GetWeakBase() const;
TF_API virtual operator bool() const;
TF_API virtual bool _IsConst() const;
#ifdef PXR_PYTHON_SUPPORT_ENABLED
TF_API virtual boost::python::api::object GetPythonObject() const;
#endif // PXR_PYTHON_SUPPORT_ENABLED
TF_API virtual const std::type_info & GetTypeInfo() const;
TF_API virtual TfType const& GetType() const;
TF_API virtual const void* _GetMostDerivedPtr() const;
TF_API virtual bool _IsPolymorphic() const;
};
template <typename Ptr>
struct _PointerHolder : _PointerHolderBase {
_PointerHolder(Ptr const &ptr) : _ptr(ptr) {
}
virtual ~_PointerHolder();
virtual void Clone(_Data *target) const;
virtual bool IsInvalid() const;
virtual void const *GetUniqueIdentifier() const;
virtual TfWeakBase const *GetWeakBase() const;
virtual operator bool() const;
virtual bool _IsConst() const;
#ifdef PXR_PYTHON_SUPPORT_ENABLED
virtual boost::python::api::object GetPythonObject() const;
#endif // PXR_PYTHON_SUPPORT_ENABLED
virtual const std::type_info & GetTypeInfo() const;
virtual TfType const& GetType() const;
virtual const void* _GetMostDerivedPtr() const;
virtual bool _IsPolymorphic() const;
private:
Ptr _ptr;
};
_PointerHolderBase* _Get() const {
return (_PointerHolderBase*)(&_ptrStorage);
}
_Data _ptrStorage;
};
// TfHash support. We don't want to choose the TfAnyWeakPtr overload unless the
// passed argument is exactly TfAnyWeakPtr. By making this a function template
// that's only enabled for TfAnyWeakPtr, C++ will not perform implicit
// conversions since T is deduced.
template <class HashState,
class T, class = typename std::enable_if<
std::is_same<T, TfAnyWeakPtr>::value>::type>
inline void
TfHashAppend(HashState &h, const T& ptr)
{
h.Append(ptr.GetUniqueIdentifier());
}
template <class Ptr>
TfAnyWeakPtr::_PointerHolder<Ptr>::~_PointerHolder() {}
template <class Ptr>
void
TfAnyWeakPtr::_PointerHolder<Ptr>::Clone(_Data *target) const
{
new (target) _PointerHolder<Ptr>(_ptr);
}
template <class Ptr>
bool
TfAnyWeakPtr::_PointerHolder<Ptr>::IsInvalid() const
{
return _ptr.IsInvalid();
}
template <class Ptr>
void const *
TfAnyWeakPtr::_PointerHolder<Ptr>::GetUniqueIdentifier() const
{
return _ptr.GetUniqueIdentifier();
}
template <class Ptr>
TfWeakBase const *
TfAnyWeakPtr::_PointerHolder<Ptr>::GetWeakBase() const
{
return &(_ptr->__GetTfWeakBase__());
}
template <class Ptr>
TfAnyWeakPtr::_PointerHolder<Ptr>::operator bool() const
{
return bool(_ptr);
}
#ifdef PXR_PYTHON_SUPPORT_ENABLED
template <class Ptr>
boost::python::api::object
TfAnyWeakPtr::_PointerHolder<Ptr>::GetPythonObject() const
{
return TfPyObject(_ptr);
}
#endif // PXR_PYTHON_SUPPORT_ENABLED
template <class Ptr>
const std::type_info &
TfAnyWeakPtr::_PointerHolder<Ptr>::GetTypeInfo() const
{
return TfTypeid(_ptr);
}
template <class Ptr>
TfType const&
TfAnyWeakPtr::_PointerHolder<Ptr>::GetType() const
{
return TfType::Find(_ptr);
}
template <class Ptr>
const void *
TfAnyWeakPtr::_PointerHolder<Ptr>::_GetMostDerivedPtr() const
{
if (!_ptr) {
return 0;
}
typename Ptr::DataType const *rawPtr = get_pointer(_ptr);
return TfCastToMostDerivedType(rawPtr);
}
template <class Ptr>
bool
TfAnyWeakPtr::_PointerHolder<Ptr>::_IsPolymorphic() const
{
return std::is_polymorphic<typename Ptr::DataType>::value;
}
template <class Ptr>
bool
TfAnyWeakPtr::_PointerHolder<Ptr>::_IsConst() const
{
return std::is_const<typename Ptr::DataType>::value;
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+47
View File
@@ -0,0 +1,47 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_API_H
#define PXR_BASE_TF_API_H
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define TF_API
# define TF_API_TEMPLATE_CLASS(...)
# define TF_API_TEMPLATE_STRUCT(...)
# define TF_LOCAL
#else
# if defined(TF_EXPORTS)
# define TF_API ARCH_EXPORT
# define TF_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define TF_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define TF_API ARCH_IMPORT
# define TF_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define TF_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define TF_LOCAL ARCH_HIDDEN
#endif
#endif
+119
View File
@@ -0,0 +1,119 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ATOMIC_OFSTREAM_WRAPPER_H
#define PXR_BASE_TF_ATOMIC_OFSTREAM_WRAPPER_H
/// \file tf/atomicOfstreamWrapper.h
/// Atomic file writer with ofstream interface.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <boost/noncopyable.hpp>
#include <fstream>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfAtomicOfstreamWrapper
///
/// A class that wraps a file output stream, providing improved tolerance for
/// write failures. The wrapper opens an output file stream to a temporary
/// file on the same file system as the desired destination file, and if no
/// errors occur while writing the temporary file, it can be renamed
/// atomically to the destination file name. In this way, write failures are
/// encountered while writing the temporary file content, rather than while
/// writing the destination file. This ensures that, if the destination
/// existed prior to writing, it is left untouched in the event of a write
/// failure, and if the destination did not exist, a partial file is not
/// written.
///
/// \section cppcode_AtomicOfstreamWrapper Example
/// \code
/// // Create a new wrapper with the destination file path.
/// TfAtomicOfstreamWrapper wrapper("/home/user/realFile.txt");
///
/// // Open the wrapped stream.
/// string reason;
/// if (not wrapper.Open(&reason)) {
/// TF_RUNTIME_ERROR(reason);
/// }
///
/// // Write content to the wrapped stream.
/// bool ok = WriteContentToStream(wrapper.GetStream());
///
/// if (ok) {
/// // No errors encountered, rename the temporary file to the real name.
/// string reason;
/// if (not wrapper.Commit(&reason)) {
/// TF_RUNTIME_ERROR(reason);
/// }
/// }
///
/// // If wrapper goes out of scope without being Commit()ed, Cancel() is
/// // called, and the temporary file is removed.
/// \endcode
///
class TfAtomicOfstreamWrapper : boost::noncopyable
{
public:
/// Constructor.
TF_API explicit TfAtomicOfstreamWrapper(const std::string& filePath);
/// Destructor. Calls Cancel().
TF_API ~TfAtomicOfstreamWrapper();
/// Opens the temporary file for writing. If the destination directory
/// does not exist, it is created. If the destination directory exists but
/// is unwritable, the destination directory cannot be created, or the
/// temporary file cannot be opened for writing in the destination
/// directory, this method returns false and \p reason is set to the
/// reason for failure.
TF_API bool Open(std::string* reason = 0);
/// Synchronizes the temporary file contents to disk, and renames the
/// temporary file into the file path passed to Open. If the file path
/// passed to the constructor names an existing file, the file, the file
/// is atomically replaced with the temporary file. If the rename fails,
/// false is returned and \p reason is set to the reason for failure.
TF_API bool Commit(std::string* reason = 0);
/// Closes the temporary file and removes it from disk, if it exists.
TF_API bool Cancel(std::string* reason = 0);
/// Returns the stream. If this is called before a call to Open, the
/// returned file stream is not yet initialized. If called after Commit or
/// Cancel, the returned file stream is closed.
std::ofstream& GetStream() { return _stream; }
private:
std::string _filePath;
std::string _tmpFilePath;
std::ofstream _stream;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ATOMIC_OFSTREAM_WRAPPER_H
+82
View File
@@ -0,0 +1,82 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_BIT_UTILS_H
#define PXR_BASE_TF_BIT_UTILS_H
/// \file tf/bitUtils.h
/// \ingroup group_tf_BasicMath
#include "pxr/pxr.h"
#include <cstddef>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
/// Compute the number of bits required to store the given number of values.
///
/// Note that the computed result for a number smaller or equal to zero is
/// undefined. The input number can be any compile-time constant.
///
/// \ingroup group_tf_BasicMath
/// \hideinitializer
#define TF_BITS_FOR_VALUES(n) \
Tf_NumBits<n-1>::type::value
template <size_t N, size_t SUM=0, size_t BIT=sizeof(N)*8/2>
struct Tf_NumBits
{
// The result is computed by divide and conquer; for a given word N the
// bit at position BIT divides the word in an upper and a lower half.
// If the upper half contain any ones, then the result is SUM plus BIT
// plus the result for the upper half. If not, the result is SUM plus
// the result for the lower half.
typedef typename std::conditional<N >= (1ULL<<BIT),
Tf_NumBits<(N>>BIT), SUM+BIT, BIT/2>,
Tf_NumBits<N, SUM, BIT/2> >::type _func;
typedef typename _func::type type;
};
template <size_t N, size_t SUM>
struct Tf_NumBits<N, SUM, 0>
{
typedef std::integral_constant<size_t, SUM+1> type;
};
/// Compute the number of bits required to store the given number of (signed)
/// enum values.
///
/// \note This is intended to be used when storing enum values in a bitfield
/// without casting the enum type to an unsigned integer. (At least GCC
/// considers enums to be signed and hence wastes one bit when all enumerants
/// are non-negative).
///
/// \ingroup group_tf_BasicMath
/// \hideinitializer
#define TF_BITS_FOR_ENUM_VALUES(n) \
(TF_BITS_FOR_VALUES(n) + 1)
PXR_NAMESPACE_CLOSE_SCOPE
#endif /* PXR_BASE_TF_BIT_UTILS_H */
+110
View File
@@ -0,0 +1,110 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_CALL_CONTEXT_H
#define PXR_BASE_TF_CALL_CONTEXT_H
/// \file tf/callContext.h
/// Functions for recording call locations.
///
/// Many macros want to record the location in which they are invoked. In
/// fact, this is the most useful feature that function-like macros have over
/// regular functions. This code provides a standard way to collect and pass
/// that contextual information around. There are two parts. First is a
/// small structure which holds the contextual information. Next is a macro
/// which will produce a temporary structure containing the local contextual
/// information. The intended usage is in a macro.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/functionLite.h"
#include <stddef.h>
PXR_NAMESPACE_OPEN_SCOPE
/// \hideinitializer
#define TF_CALL_CONTEXT \
TfCallContext(__ARCH_FILE__, __ARCH_FUNCTION__, __LINE__, __ARCH_PRETTY_FUNCTION__)
class TfCallContext
{
public:
constexpr TfCallContext()
: _file(nullptr)
, _function(nullptr)
, _line(0)
, _prettyFunction(nullptr)
, _hidden(false) {}
constexpr TfCallContext(char const *file,
char const *function,
size_t line,
char const *prettyFunction) :
_file(file),
_function(function),
_line(line),
_prettyFunction(prettyFunction),
_hidden(false)
{
}
char const *GetFile() const {
return _file;
}
char const *GetFunction() const {
return _function;
}
size_t GetLine() const {
return _line;
}
char const *GetPrettyFunction() const {
return _prettyFunction;
}
TfCallContext const& Hide() const {
_hidden = true;
return *this;
}
bool IsHidden() const {
return _hidden;
}
explicit operator bool() const { return _file && _function; }
private:
char const *_file;
char const *_function;
size_t _line;
char const *_prettyFunction;
mutable bool _hidden;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_CALL_CONTEXT_H
+82
View File
@@ -0,0 +1,82 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_CXX_CAST_H
#define PXR_BASE_TF_CXX_CAST_H
/// \file tf/cxxCast.h
/// C++ Cast Utilities.
#ifndef __cplusplus
#error This include file can only be included in C++ programs.
#endif
#include "pxr/pxr.h"
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
template <class Src, class Dst>
using Tf_CopyConst =
typename std::conditional<std::is_const<Src>::value,
typename std::add_const<Dst>::type, Dst>::type;
template <class Src, class Dst>
using Tf_CopyVolatile =
typename std::conditional<std::is_volatile<Src>::value,
typename std::add_volatile<Dst>::type, Dst>::type;
template <class Src, class Dst>
using Tf_CopyCV = Tf_CopyConst<Src, Tf_CopyVolatile<Src, Dst>>;
/// Return a pointer to the most-derived object.
///
/// A \c dynamic_cast to \c void* is legal only for pointers to polymorphic
/// objects. This function returns the original pointer for non-polymorphic
/// types, and a pointer to the most-derived type of the object.
/// Said differently, given a pointer of static type \c B*, and given that
/// the object really points to an object of type \c D*, this function
/// returns the address of the object considered as a \c D*; however, for
/// non-polymorphic objects, the actual type of an object is taken to be \c B,
/// since one cannot prove that that the type is actually different.
///
/// \warning This function is public, but should be used sparingly (or not all).
template <typename T>
inline typename std::enable_if<
std::is_polymorphic<T>::value, Tf_CopyCV<T, void>*>::type
TfCastToMostDerivedType(T* ptr)
{
return dynamic_cast<Tf_CopyCV<T, void>*>(ptr);
}
template <typename T>
inline typename std::enable_if<
!std::is_polymorphic<T>::value, Tf_CopyCV<T, void>*>::type
TfCastToMostDerivedType(T* ptr)
{
return static_cast<Tf_CopyCV<T, void>*>(ptr);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+576
View File
@@ -0,0 +1,576 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DEBUG_H
#define PXR_BASE_TF_DEBUG_H
/// \file tf/debug.h
/// \ingroup group_tf_DebuggingOutput
/// Conditional debugging output class and macros.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/tf.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include "pxr/base/tf/registryManager.h"
#include "pxr/base/tf/stopwatch.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/arch/hints.h"
#include <atomic>
#include <cstdio>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class Tf_DebugSymbolRegistry;
/// \addtogroup group_tf_DebuggingOutput
///@{
/// \class TfDebug
///
/// Enum-based debugging messages.
///
/// The \c TfDebug class encapsulates a simple enum-based conditional
/// debugging message system. It is meant as a tool for developers, and
/// \e NOT as a means of issuing diagnostic messages to end-users. (This is
/// not strictly true. The TfDebug class is extremely useful and has many
/// properties that make its use attractive for issuing messages to end-users.
/// However, for this purpose, please use the \c TF_INFO macro which more
/// clearly indicates its intent.)
///
/// The features of \c TfDebug are:
/// \li Debugging messages/calls for an entire enum group can be
/// compiled out-of-existence.
/// \li The cost of checking if a specific message should be printed
/// at runtime (assuming the enum group of the message has not been
/// compile-time disabled) is a single inline array lookup,
/// with a compile-time index into a global array.
///
/// The use of the facility is simple:
/// \code
/// // header file
/// #include "pxr/base/tf/debug.h"
/// TF_DEBUG_CODES(MY_E1, MY_E2, MY_E3);
///
/// // source file
/// TF_DEBUG(MY_E2).Msg("something about e2\n");
///
/// TF_DEBUG(MY_E3).Msg("val = %d\n", value);
/// \endcode
///
/// The code in the header file declares the debug symbols to use. Under
/// the hood, this creates an enum with the values given in the argument to
/// TF_DEBUG_CODES, along with a first and last sentinel values and passes
/// that to TF_DEBUG_RANGE.
///
/// If you need to obtain the enum type name, use decltype(SOME_ENUM_VALUE).
///
/// In the source file, the indicated debugging messages are printed
/// only if the debugging symbols are enabled. Effectively, the construct
/// \code
/// TF_DEBUG(MY_E1).Msg(msgExpr)
/// \endcode
/// is translated to
/// \code
/// if (symbol-MY_E1-is-enabled)
/// output(msgExpr)
/// \endcode
///
/// The implications are that \c msgExpr is only evaluated if symbol \c MY_E1
/// symbol is enabled.
///
/// To totally disable TF_DEBUG output for a set of codes at compile time,
/// declare the codes using
/// TF_CONDITIONALLY_COMPILE_TIME_ENABLED_DEBUG_CODES(condition, ...) where
/// ... is all the debug codes. If 'condition' is false at compile time then
/// all TF_DEBUG().Msg()s for these codes are elminated at compile time, so they
/// have zero cost.
///
/// Most commonly debug symbols are inactive by default, but can be turned
/// on either by an environment variable \c TF_DEBUG, or interactively once
/// a program has started.
///
/// \code
/// TfDebug::DisableAll<MyDebugCodes>(); // disable everything
///
/// TfDebug::Enable(MY_E1); // enable just MY_E1
/// \endcode
///
/// Description strings may be associated with debug codes as follows:
/// \code
/// // source file xyz/debugCodes.cpp
///
/// #include "proj/my/debugCodes.h"
/// #include "pxr/base/tf/debug.h"
/// #include "pxr/base/tf/registryManager.h"
///
/// TF_REGISTRY_FUNCTION(TfDebug) {
/// TF_DEBUG_ENVIRONMENT_SYMBOL(MY_E1, "loading of blah-blah files");
/// TF_DEBUG_ENVIRONMENT_SYMBOL(MY_E2, "parsing of mdl code");
/// // etc.
/// }
/// \endcode
///
///
class TfDebug {
enum _NodeState { _NodeUninitialized, _NodeDisabled, _NodeEnabled };
public:
/// Mark debugging as enabled for enum value \c val.
///
/// The default state for all debugging symbols is disabled. Note that the
/// template parameter is deduced from \c val:
/// \code
/// TfDebug::Enable(MY_E3);
/// \endcode
template <class T>
static void Enable(T val) {
_SetNode(_GetNode(val), Tf_DebugGetEnumName(val), true);
}
/// Mark debugging as disabled for enum value \c val.
template <class T>
static void Disable(T val) {
_SetNode(_GetNode(val), Tf_DebugGetEnumName(val), false);
}
/// Mark debugging as enabled for all enum values of type \c T.
///
/// Note that the template parameter must be explicitly supplied:
/// \code
/// TfDebug::EnableAll<MyDebugCodes>()
/// \endcode
template <class T>
static void EnableAll() {
const int n = _Traits<T>::NumCodes;
for (int i = 0; i != n; ++i) {
T code = static_cast<T>(i);
_SetNode(_GetNode(code), Tf_DebugGetEnumName(code), true);
}
}
/// Mark debugging as disabled for all enum values of type \c T.
template <class T>
static void DisableAll() {
const int n = _Traits<T>::NumCodes;
for (int i = 0; i != n; ++i) {
T code = static_cast<T>(i);
_SetNode(_GetNode(code), Tf_DebugGetEnumName(code), false);
}
}
/// True if debugging is enabled for the enum value \c val.
///
/// Note that not only must the specific enum value \c val be marked as
/// enabled, but the enum type \c T must be globally enabled; this is
/// controlled by the first argument to the
/// \c TF_CONDITIONALLY_COMPILE_TIME_ENABLED_DEBUG_CODES() macro.
template <class T>
static bool IsEnabled(T val) {
static_assert(_Traits<T>::IsDeclared,
"Must declare debug codes with TF_DEBUG_CODES()");
if (_Traits<T>::CompileTimeEnabled) {
_Node &node = _GetNode(val);
_NodeState curState = node.state.load();
if (ARCH_UNLIKELY(curState == _NodeUninitialized)) {
_InitializeNode(_GetNode(val), Tf_DebugGetEnumName(val));
curState = node.state.load();
}
return curState == _NodeEnabled;
}
return false;
}
/// True if debugging can be activated at run-time, whether or not it is
/// currently enabled.
template <class T>
static bool IsCompileTimeEnabled() {
static_assert(_Traits<T>::IsDeclared,
"Must declare debug codes with TF_DEBUG_CODES()");
return _Traits<T>::CompileTimeEnabled;
}
/// Return the number of debugging symbols of this type.
///
/// Returns the number of different enums in the range.
template <class T>
static size_t GetNumDebugCodes() {
static_assert(_Traits<T>::IsDeclared,
"Must declare debug codes with TF_DEBUG_CODES()");
return _Traits<T>::NumCodes;
}
#if !defined(doxygen)
struct Helper {
static TF_API void Msg(const std::string& msg);
static TF_API void Msg(const char* msg, ...) ARCH_PRINTF_FUNCTION(1,2);
};
#endif
template <bool B>
struct ScopeHelper {
ScopeHelper(bool enabled, const char* name) {
if ((active = enabled)) {
str = name;
TfDebug::_ScopedOutput(true, str);
}
else
str = NULL;
}
~ScopeHelper() {
if (active)
TfDebug::_ScopedOutput(false, str);
}
bool active;
const char* str;
};
template <bool B>
struct TimedScopeHelper {
TimedScopeHelper(bool enabled, const char* fmt, ...)
ARCH_PRINTF_FUNCTION(3, 4);
~TimedScopeHelper();
bool active;
std::string str;
TfStopwatch stopwatch;
};
/// Set registered debug symbols matching \p pattern to \p value.
///
/// All registered debug symbols matching \p pattern are set to \p value.
/// The only matching is an exact match with \p pattern, or if \p pattern
/// ends with an '*' as is otherwise a prefix of a debug symbols. The
/// names of all debug symbols set by this call are returned as a vector.
TF_API
static std::vector<std::string> SetDebugSymbolsByName(
const std::string& pattern, bool value);
/// True if the specified debug symbol is set.
TF_API
static bool IsDebugSymbolNameEnabled(const std::string& name);
/// Get a description of all debug symbols and their purpose.
///
/// A single string describing all registered debug symbols along with
/// short descriptions is returned.
TF_API
static std::string GetDebugSymbolDescriptions();
/// Get a listing of all debug symbols.
TF_API
static std::vector<std::string> GetDebugSymbolNames();
/// Get a description for the specified debug symbol.
///
/// A short description of the debug symbol is returned. This is the same
/// description string that is embedded in the return value of
/// GetDebugSymbolDescriptions.
TF_API
static std::string GetDebugSymbolDescription(const std::string& name);
/// Direct debug output to \a either stdout or stderr.
///
/// Note that \a file MUST be either stdout or stderr. If not, issue an
/// error and do nothing. Debug output is issued to stdout by default.
/// If the environment variable TF_DEBUG_OUTPUT_FILE is set to 'stderr',
/// then output is issued to stderr by default.
TF_API
static void SetOutputFile(FILE *file);
struct _Node;
// Public, to be used in TF_DEBUG_ENVIRONMENT_SYMBOL() macro,
// but not meant to be used otherwise.
template <class T>
static void _RegisterDebugSymbol(
T enumVal, char const *name, char const *descrip) {
static_assert(_Traits<T>::IsDeclared,
"Must declare debug codes with TF_DEBUG_CODES()");
const int index = static_cast<int>(enumVal);
const int numCodes = _Traits<T>::NumCodes;
if (ARCH_UNLIKELY(index < 0 || index >= numCodes)) {
_ComplainAboutInvalidSymbol(name);
return;
}
_RegisterDebugSymbolImpl(&_GetNode(enumVal), name, descrip);
}
TF_API
static void _RegisterDebugSymbolImpl(_Node *addr, char const *enumName,
char const *descrip);
// Unfortunately, we need to make both _Traits and _Node, below
// public because of their use in macros.
// Please treat both as a private data structures!
template <class T>
struct _Traits {
static constexpr bool IsDeclared = false;
};
// Note: this structure gets initialized statically zero
// (_NodeUninitialized) statically.
struct _Node {
mutable std::atomic<_NodeState> state;
};
private:
template <class T>
struct _Data {
static _Node nodes[_Traits<T>::NumCodes];
};
template <class T>
static _Node &_GetNode(T val) {
return _Data<T>::nodes[static_cast<int>(val)];
}
friend class Tf_DebugSymbolRegistry;
TF_API
static void _InitializeNode(_Node &node, char const *name);
TF_API
static void _ComplainAboutInvalidSymbol(char const *name);
TF_API
static void _SetNode(_Node &node, char const *name, bool state);
TF_API
static void _ScopedOutput(bool start, char const *str);
};
template <class T>
TfDebug::_Node TfDebug::_Data<T>::nodes[];
template <>
struct TfDebug::TimedScopeHelper<false> {
TimedScopeHelper(bool, const char*, ...)
ARCH_PRINTF_FUNCTION(3, 4) {
}
};
/// Define debugging symbols
///
/// This is a simple macro that takes care of declaring debug codes. Use it as
/// follows:
/// \code
/// TF_DEBUG_CODES(
/// MY_E1,
/// MY_E2
/// );
/// \endcode
///
/// \hideinitializer
#define TF_DEBUG_CODES(...) \
TF_CONDITIONALLY_COMPILE_TIME_ENABLED_DEBUG_CODES(true, __VA_ARGS__)
/// Define debugging symbols
///
/// This is a simple macro that takes care of declaring debug codes, subject to
/// a compile-time condition that enables or disables them completely. Use it as
/// follows:
/// \code
/// TF_CONDITIONALLY_COMPILE_TIME_ENABLED_DEBUG_CODES(
/// <Enabled State: a compile-time value convertible to bool>
/// MY_E1,
/// MY_E2
/// );
/// \endcode
///
/// If the Enabled State is true, this is equivalent to the TF_DEBUG_CODES()
/// macro. If it is false, then these debug codes are disabled at compile time
/// and generated code pays no cost for them.
///
/// \hideinitializer
#define TF_CONDITIONALLY_COMPILE_TIME_ENABLED_DEBUG_CODES(condition, ...) \
enum _TF_DEBUG_ENUM_NAME(__VA_ARGS__) { \
__VA_ARGS__ , \
TF_PP_CAT( _TF_DEBUG_ENUM_NAME(__VA_ARGS__), __PAST_END) \
}; \
template <> \
struct TfDebug::_Traits<_TF_DEBUG_ENUM_NAME(__VA_ARGS__)> { \
static constexpr bool IsDeclared = true; \
static constexpr int NumCodes = \
TF_PP_CAT(_TF_DEBUG_ENUM_NAME(__VA_ARGS__), __PAST_END); \
static constexpr bool CompileTimeEnabled = (condition); \
}; \
inline char const * \
Tf_DebugGetEnumName(_TF_DEBUG_ENUM_NAME(__VA_ARGS__) val) { \
constexpr char const *CStrings[] = { \
TF_PP_FOR_EACH(_TF_DEBUG_MAKE_STRING, __VA_ARGS__) \
}; \
return CStrings[static_cast<int>(val)]; \
};
#define _TF_DEBUG_MAKE_STRING(x) #x,
// In the _TF_DEBUG_ENUM_NAME macro below we pass 'dummy' to
// _TF_DEBUG_FIRST_CODE as the second argument to ensure that we always
// have more than one argument as expected by _TF_DEBUG_FIRST_CODE.
#define _TF_DEBUG_ENUM_NAME(...) \
TF_PP_CAT(_TF_DEBUG_FIRST_CODE(__VA_ARGS__, dummy), __DebugCodes)
#define _TF_DEBUG_FIRST_CODE(first, ...) first
/// Evaluate and print debugging message \c msg if \c enumVal is enabled for
/// debugging.
///
/// This macro is a newer, more convenient form of the \c TF_DEBUG() macro.
/// Writing
/// \code
/// TF_DEBUG_MSG(enumVal, msg, ...);
/// \endcode
/// is equivalent to
/// \code
/// TF_DEBUG(enumVal).Msg(msg, ...);
/// \endcode
///
/// The TF_DEBUG_MSG() macro allows either an std::string argument or
/// a printf-like format string followed by a variable number of arguments:
/// \code
/// TF_DEBUG_MSG(enumVal, "opening file %s\n", file.c_str());
///
/// TF_DEBUG_MSG(enumVal, "opening file " + file);
/// \endcode
///
/// \hideinitializer
#define TF_DEBUG_MSG(enumVal, ...) \
if (!TfDebug::IsEnabled(enumVal)) /* empty */ ; else TfDebug::Helper().Msg(__VA_ARGS__)
/// Evaluate and print debugging message \c msg if \c enumVal is enabled for
/// debugging.
///
/// The \c TF_DEBUG() macro is used as follows:
/// \code
/// TF_DEBUG(enumVal).Msg("opening file %s, count = %d\n",
/// file.c_str(), count);
/// \endcode
///
/// If \c enumVal is of enumerated type \c enumType, and \c enumType
/// has been enabled for debugging (see \c TF_DEBUG_CODES()), and
/// the specific value \c enumVal has been enabled for debugging by a call
/// to \c TfDebug::Enable(), then the arguments in the \c Msg() call are
/// evaluated and printed. The argument to \c Msg() may either be a
/// \c const \c char* and a variable number of arguments, using standard
/// printf-formatting rules, or a \c std::string variable:
/// \code
/// TF_DEBUG(enumVal).Msg("opening file " + file + "\n");
/// \endcode
///
/// Note that the arguments to \c Msg() are unevaluated when the value
/// \c enumVal is not enabled for debugging, so \c Msg() must be free
/// of side-effects; however, when \c enumVal is not enabled, there is
/// no expense incurred in computing the arguments to \c Msg(). Note
/// that if the entire enum type corresponding to \c enumVal is
/// disabled (a compile-time determination) then the code for the \e
/// entire \c TF_DEBUG().Msg() statement will typically not even be
/// generated!
///
/// \sa TF_DEBUG_MSG()
///
/// \hideinitializer
#define TF_DEBUG(enumVal) \
if (!TfDebug::IsEnabled(enumVal)) /* empty */ ; else TfDebug::Helper()
/// Evaluate and print diagnostic messages intended for end-users.
///
/// The TF_INFO(x) macro is cosmetic; it actually just calls the TF_DEBUG
/// macro (see above). This macro should be used if its output is intended to
/// be seen by end-users.
///
/// \hideinitializer
#define TF_INFO(x) TF_DEBUG(x)
/// Print description and time spent in scope upon beginning and exiting it if
/// \p enumVal is enabled for debugging.
///
/// The \c TF_DEBUG_TIMED_SCOPE() macro is used as follows:
/// \code
/// void Attribute::Compute()
/// {
/// TF_DEBUG_TIMED_SCOPE(ATTR_COMPUTE, "Computing %s", name.c_str());
/// ...
/// }
/// \endcode
///
/// When the \c TF_DEBUG_TIMED_SCOPE macro is invoked, a timer is started and
/// the supplied description is printed. When the enclosing scope is exited
/// (in the example, when Attribute::Compute() finishes) the timer is stopped
/// and the scope description and measured time are printed. This allows for
/// very fine-grained timing of operations.
///
/// Note that if the entire enum type corresponding to \p enumVal is disabled
/// (a compile-time determination) then the presence of a
/// \c TF_DEBUG_TIMED_SCOPE() macro should not produce any extra generated
/// code (in an optimized build). If the enum type is enabled, but the
/// particular value \p enumVal is disabled, the cost of the macro should be
/// quite minimal; still, it would be best not to embed the macro in functions
/// that are called in very tight loops, in final released code.
///
/// \hideinitializer
#define TF_DEBUG_TIMED_SCOPE(enumVal, ...) \
TfDebug::TimedScopeHelper< \
TfDebug::_Traits< \
std::decay<decltype(enumVal)>::type>::CompileTimeEnabled> \
TF_PP_CAT(local__TfScopeDebugSwObject, __LINE__)( \
TfDebug::IsEnabled(enumVal), __VA_ARGS__)
/// Register description strings with enum symbols for debugging.
///
/// This call should be used in source files, not header files, and should
/// This macro should usually appear within a
/// \c TF_REGISTRY_FUNCTION(TfDebug,...) call. The first argument should be
/// the literal name of the enum symbol, while the second argument should be a
/// (short) description of what debugging will be enabled if the symbol is
/// activated. The enum being registered must be one which is contained in
/// some TF_DEBUG_CODES() call. For example:
/// \code
/// TF_REGISTRY_FUNCTION(TfDebug) {
/// TF_DEBUG_ENVIRONMENT_SYMBOL(MY_E1, "loading of blah-blah files");
/// TF_DEBUG_ENVIRONMENT_SYMBOL(MY_E2, "parsing of mdl code");
/// // etc.
/// }
/// \endcode
///
/// \hideinitializer
#define TF_DEBUG_ENVIRONMENT_SYMBOL(VAL, descrip) \
if (TfDebug::_Traits< \
std::decay<decltype(VAL)>::type>::CompileTimeEnabled) { \
TF_ADD_ENUM_NAME(VAL); \
TfDebug::_RegisterDebugSymbol(VAL, #VAL, descrip); \
}
///@}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+56
View File
@@ -0,0 +1,56 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DEBUG_NOTICE_H
#define PXR_BASE_TF_DEBUG_NOTICE_H
/// \file tf/debugNotice.h
#include "pxr/pxr.h"
#include "pxr/base/tf/notice.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfDebugSymbolsChangedNotice
///
/// Sent when the list of available debug symbol names has changed.
class TfDebugSymbolsChangedNotice : public TfNotice
{
public:
TfDebugSymbolsChangedNotice() {}
virtual ~TfDebugSymbolsChangedNotice();
};
/// \class TfDebugSymbolEnableChangedNotice
///
/// Sent when a debug symbol has been enabled or disabled.
class TfDebugSymbolEnableChangedNotice : public TfNotice
{
public:
TfDebugSymbolEnableChangedNotice() {}
virtual ~TfDebugSymbolEnableChangedNotice();
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+95
View File
@@ -0,0 +1,95 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DECLARE_PTRS_H
#define PXR_BASE_TF_DECLARE_PTRS_H
/// \file tf/declarePtrs.h
/// Standard pointer typedefs.
///
/// This file provides typedefs for standard pointer types.
#include "pxr/pxr.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/refPtr.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \struct TfDeclarePtrs
/// Templated struct used for type definition macros.
template<typename T> struct TfDeclarePtrs {
typedef TfWeakPtr< T > Ptr;
typedef TfWeakPtr< const T > ConstPtr;
typedef std::vector< Ptr > PtrVector;
typedef std::vector< ConstPtr > ConstPtrVector;
typedef TfRefPtr< T > RefPtr;
typedef TfRefPtr< const T > ConstRefPtr;
typedef std::vector< RefPtr > RefPtrVector;
typedef std::vector< ConstRefPtr > ConstRefPtrVector;
};
/// Define standard weak pointer types.
///
/// \param type is a class name.
///
/// \c TF_DECLARE_WEAK_PTRS(Class) declares ClassPtr, ClassConstPtr,
/// ClassPtrVector and ClassConstPtrVector.
///
/// \hideinitializer
#define TF_DECLARE_WEAK_PTRS(type) \
typedef TfDeclarePtrs< class type >::Ptr type##Ptr; \
typedef TfDeclarePtrs< class type >::ConstPtr type##ConstPtr; \
typedef TfDeclarePtrs< class type >::PtrVector type##PtrVector; \
typedef TfDeclarePtrs< class type >::ConstPtrVector type##ConstPtrVector
/// Define standard ref pointer types.
///
/// \param type is a class name.
///
/// \c TF_DECLARE_REF_PTRS(Class) declares ClassRefPtr and ClassConstRefPtr.
///
/// \hideinitializer
#define TF_DECLARE_REF_PTRS(type) \
typedef TfDeclarePtrs< class type >::RefPtr type##RefPtr; \
typedef TfDeclarePtrs< class type >::ConstRefPtr type##ConstRefPtr; \
typedef TfDeclarePtrs< class type >::RefPtrVector type##RefPtrVector; \
typedef TfDeclarePtrs< class type >::ConstRefPtrVector type##ConstRefPtrVector
/// Define standard weak, ref, and vector pointer types.
///
/// \param type is a class name.
///
/// \c TF_DECLARE_WEAK_AND_REF_PTRS(Class) declares ClassPtr, ClassConstPtr,
/// ClassPtrVector, ClassConstPtrVector, ClassRefPtr and ClassConstRefPtr.
///
/// \hideinitializer
#define TF_DECLARE_WEAK_AND_REF_PTRS(type) \
TF_DECLARE_WEAK_PTRS(type); \
TF_DECLARE_REF_PTRS(type)
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+633
View File
@@ -0,0 +1,633 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DENSE_HASH_MAP_H
#define PXR_BASE_TF_DENSE_HASH_MAP_H
/// \file tf/denseHashMap.h
#include "pxr/pxr.h"
#include "pxr/base/tf/hashmap.h"
#include <memory>
#include <vector>
#include <boost/compressed_pair.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/utility.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfDenseHashMap
///
/// This is a space efficient container that mimics the TfHashMap API that
/// uses a vector for storage when the size of the map is small.
///
/// When the map gets bigger than \p Threshold a TfHashMap is allocated
/// that is used to accelerate lookup in the vector.
///
/// \warning This differs from a TfHashMap in so far that inserting and
/// removing elements invalidate all iterators of the container.
///
template <
class Key,
class Data,
class HashFn,
class EqualKey = std::equal_to<Key>,
unsigned Threshold = 128
>
class TfDenseHashMap
{
public:
typedef std::pair<const Key, Data> value_type;
typedef Key key_type;
typedef Data mapped_type;
////////////////////////////////////////////////////////////////////////////////
private:
// This helper implements a std::pair with an assignment operator that
// uses placement new instead of assignment. The benefit here is that
// the two elements of the pair may be const.
//
struct _InternalValueType
{
_InternalValueType() {}
_InternalValueType(const Key &k, const Data &d)
: _value(k, d) {}
_InternalValueType &operator=(const _InternalValueType &rhs) {
if (this != &rhs) {
// Since value_type's first member is const we need to
// use placement new to put the new element in place. Just
// make sure we destruct the element we are about to overwrite.
_value.value_type::~value_type();
new (&_value) value_type(rhs.GetValue());
}
return *this;
}
value_type &GetValue() {
return _value;
}
const value_type &GetValue() const {
return _value;
}
void swap(_InternalValueType &rhs) {
using std::swap;
// We do this in order to take advantage of a potentially fast
// swap implementation.
Key tmp = _value.first;
_value.first.Key::~Key();
new (const_cast<Key *>(&_value.first)) Key(rhs._value.first);
rhs._value.first.Key::~Key();
new (const_cast<Key *>(&rhs._value.first)) Key(tmp);
swap(_value.second, rhs._value.second);
}
private:
// Data hold by _InternalValueType. Note that the key portion of
// value_type maybe const.
value_type _value;
};
// The vector type holding all data for this dense hash map.
typedef std::vector<_InternalValueType> _Vector;
// The hash map used when the map holds more than Threshold elements.
typedef TfHashMap<Key, size_t, HashFn, EqualKey> _HashMap;
// Note that we don't just use _Vector::iterator for accessing elements
// of the TfDenseHashMap. This is because the vector's iterator would
// expose the _InternalValueType _including_ its assignment operator
// that allows overwriting keys.
//
// Clearly not a good thing.
//
// Therefore we use boost::iterator_facade to create an iterator that uses
// the map's value_type as externally visible type.
//
template <class ElementType, class UnderlyingIterator>
class _IteratorBase :
public boost::iterator_facade<
_IteratorBase<ElementType, UnderlyingIterator>,
ElementType,
boost::bidirectional_traversal_tag>
{
public:
// Empty ctor.
_IteratorBase() {}
// Allow conversion of an iterator to a const_iterator.
template<class OtherIteratorType>
_IteratorBase(const OtherIteratorType &rhs)
: _iter(rhs._GetUnderlyingIterator()) {}
private:
friend class TfDenseHashMap;
friend class boost::iterator_core_access;
// Ctor from an underlying iterator.
_IteratorBase(const UnderlyingIterator &iter)
: _iter(iter) {}
template<class OtherIteratorType>
bool equal(const OtherIteratorType &rhs) const {
return _iter == rhs._iter;
}
void increment() {
++_iter;
}
void decrement() {
--_iter;
}
ElementType &dereference() const {
// The dereference() method accesses the correct value_type (ie.
// the one with potentially const key_type. This way, clients don't
// see the assignment operator of _InternalValueType.
return _iter->GetValue();
}
UnderlyingIterator _GetUnderlyingIterator() const {
return _iter;
}
private:
UnderlyingIterator _iter;
};
////////////////////////////////////////////////////////////////////////////////
public:
/// An iterator type for this map. Note that it provides access to the
/// This::value_type only.
typedef
_IteratorBase<value_type, typename _Vector::iterator>
iterator;
/// An iterator type for this map. Note that it provides access to the
/// This::value_type only.
typedef
_IteratorBase<const value_type, typename _Vector::const_iterator>
const_iterator;
/// Return type for insert() method.
typedef std::pair<iterator, bool> insert_result;
public:
/// Ctor.
///
explicit TfDenseHashMap(
const HashFn &hashFn = HashFn(),
const EqualKey &equalKey = EqualKey())
{
_hash() = hashFn;
_equ() = equalKey;
}
/// Construct with range.
///
template <class Iterator>
TfDenseHashMap(Iterator begin, Iterator end) {
insert(begin, end);
}
/// Construct from an initializer_list.
///
TfDenseHashMap(std::initializer_list<value_type> l) {
insert(l.begin(), l.end());
}
/// Copy Ctor.
///
TfDenseHashMap(const TfDenseHashMap &rhs)
: _vectorHashFnEqualFn(rhs._vectorHashFnEqualFn) {
if (rhs._h) {
_h.reset(new _HashMap(*rhs._h));
}
}
/// Move Ctor.
///
TfDenseHashMap(TfDenseHashMap &&rhs) = default;
/// Copy assignment operator.
///
TfDenseHashMap &operator=(const TfDenseHashMap &rhs) {
if (this != &rhs) {
TfDenseHashMap temp(rhs);
temp.swap(*this);
}
return *this;
}
/// Move assignment operator.
///
TfDenseHashMap &operator=(TfDenseHashMap &&rhs) = default;
/// Assignment from an initializer_list.
///
TfDenseHashMap &operator=(std::initializer_list<value_type> l) {
clear();
insert(l.begin(), l.end());
return *this;
}
/// Equality operator.
///
bool operator==(const TfDenseHashMap &rhs) const {
if (size() != rhs.size())
return false;
//XXX: Should we compare the HashFn and EqualKey too?
const_iterator tend = end(), rend = rhs.end();
for(const_iterator iter = begin(); iter != tend; ++iter) {
const_iterator riter = rhs.find(iter->first);
if (riter == rend)
return false;
if (iter->second != riter->second)
return false;
}
return true;
}
bool operator!=(const TfDenseHashMap &rhs) const {
return !(*this == rhs);
}
/// Erases all of the elements
///
void clear() {
_vec().clear();
_h.reset();
}
/// Swaps the contents of two maps.
///
void swap(TfDenseHashMap &rhs) {
_vectorHashFnEqualFn.swap(rhs._vectorHashFnEqualFn);
_h.swap(rhs._h);
}
/// \c true if the \c map's size is 0.
///
bool empty() const {
return _vec().empty();
}
/// Returns the size of the map.
///
size_t size() const {
return _vec().size();
}
/// Returns an const_iterator pointing to the beginning of the map.
///
iterator begin() {
return _vec().begin();
}
/// Returns an const_iterator pointing to the end of the map.
///
iterator end() {
return _vec().end();
}
/// Returns an const_iterator pointing to the beginning of the map.
///
const_iterator begin() const {
return _vec().begin();
}
/// Returns an const_iterator pointing to the end of the map.
///
const_iterator end() const {
return _vec().end();
}
/// Finds the element with key \p k.
///
iterator find(const key_type &k) {
if (_h) {
typename _HashMap::const_iterator iter = _h->find(k);
if (iter == _h->end())
return end();
return _vec().begin() + iter->second;
} else {
return _FindInVec(k);
}
}
/// Finds the element with key \p k.
///
const_iterator find(const key_type &k) const {
if (_h) {
typename _HashMap::const_iterator iter = _h->find(k);
if (iter == _h->end())
return end();
return _vec().begin() + iter->second;
} else {
return _FindInVec(k);
}
}
/// Returns the number of elements with key \p k. Which is either 0 or 1.
///
size_t count(const key_type &k) const {
return find(k) != end();
}
/// Returns a pair of <iterator, bool> where iterator points to the element
/// in the list and bool is true if a new element was inserted.
///
insert_result insert(const value_type &v) {
if (_h) {
// Attempt to insert the new index. If this fails, we can't insert
// v.
std::pair<typename _HashMap::iterator, bool> res =
_h->insert(std::make_pair(v.first, size()));
if (!res.second)
return insert_result(_vec().begin() + res.first->second, false);
} else {
// Bail if already inserted.
iterator iter = _FindInVec(v.first);
if (iter != end())
return insert_result(iter, false);
}
// Insert at end and create table if necessary.
_vec().push_back(_InternalValueType(v.first, v.second));
_CreateTableIfNeeded();
return insert_result(std::prev(end()), true);
}
/// Insert a range into the hash map. Note that \p i0 and \p i1 can't
/// point into the hash map.
///
template<class IteratorType>
void insert(IteratorType i0, IteratorType i1) {
// Assume elements are more often than not unique, so if the sum of the
// current size and the size of the range is greater than or equal to
// the threshold, we create the table immediately so we don't do m*n
// work before creating the table.
if (size() + std::distance(i0, i1) >= Threshold)
_CreateTable();
// Insert elements.
for(IteratorType iter = i0; iter != i1; ++iter)
insert(*iter);
}
/// Insert a range of unique elements into the container. [begin, end)
/// *must not* contain any duplicate elements.
///
template <class Iterator>
void insert_unique(Iterator begin, Iterator end) {
// Special-case empty container.
if (empty()) {
_vec().assign(begin, end);
_CreateTableIfNeeded();
} else {
// Just insert, since duplicate checking will use the hash.
insert(begin, end);
}
}
/// Indexing operator. Inserts a default constructed DataType() for \p key
/// if there is no value for \p key already.
///
/// Returns a reference to the value type for \p key.
///
Data &operator[](const key_type &key) {
return insert(value_type(key, Data())).first->second;
}
/// Erase element with key \p k. Returns the number of elements erased.
///
size_t erase(const key_type &k) {
iterator iter = find(k);
if (iter != end()) {
erase(iter);
return 1;
}
return 0;
}
/// Erases element pointed to by \p iter.
///
void erase(const iterator &iter) {
// Erase key from hash table if applicable.
if (_h)
_h->erase(iter->first);
// If we are not removing that last element...
if (iter != std::prev(end())) {
// Need to get the underlying vector iterator directly, because
// we want to operate on the vector.
typename _Vector::iterator vi = iter._GetUnderlyingIterator();
// ... move the last element into the erased placed.
vi->swap(_vec().back());
// ... and update the moved element's index.
if (_h)
(*_h)[vi->GetValue().first] = vi - _vec().begin();
}
_vec().pop_back();
}
/// Erases a range from the map.
///
void erase(iterator i0, iterator i1) {
if (_h) {
for(iterator iter = i0; iter != i1; ++iter)
_h->erase(iter->first);
}
typename _Vector::const_iterator vremain = _vec().erase(
i0._GetUnderlyingIterator(), i1._GetUnderlyingIterator());
if (_h) {
for(; vremain != _vec().end(); ++vremain)
(*_h)[vremain->GetValue().first] = vremain - _vec().begin();
}
}
/// Optimize storage space.
///
void shrink_to_fit() {
// Shrink the vector to best size.
_vec().shrink_to_fit();
if (!_h)
return;
size_t sz = size();
// If we have a hash map and are underneath the threshold, discard it.
if (sz < Threshold) {
_h.reset();
} else {
// Otherwise, allocate a new hash map with the optimal size.
_h.reset(new _HashMap(sz, _hash(), _equ()));
for(size_t i=0; i<sz; ++i)
_h->insert(std::make_pair(_vec()[i].GetValue().first, i));
}
}
/// Reserve space.
///
void reserve(size_t n) {
_vec().reserve(n);
}
////////////////////////////////////////////////////////////////////////////////
private:
// Helper to access the storage vector.
_Vector &_vec() {
return _vectorHashFnEqualFn.first().first();
}
// Helper to access the hash functor.
HashFn &_hash() {
return _vectorHashFnEqualFn.first().second();
}
// Helper to access the equality functor.
EqualKey &_equ() {
return _vectorHashFnEqualFn.second();
}
// Helper to access the storage vector.
const _Vector &_vec() const {
return _vectorHashFnEqualFn.first().first();
}
// Helper to access the hash functor.
const HashFn &_hash() const {
return _vectorHashFnEqualFn.first().second();
}
// Helper to access the equality functor.
const EqualKey &_equ() const {
return _vectorHashFnEqualFn.second();
}
// Helper to linear-search the vector for a key.
inline iterator _FindInVec(const key_type &k) {
_Vector &vec = _vec();
EqualKey &equ = _equ();
typename _Vector::iterator iter = vec.begin(), end = vec.end();
for (; iter != end; ++iter) {
if (equ(iter->GetValue().first, k))
break;
}
return iter;
}
// Helper to linear-search the vector for a key.
inline const_iterator _FindInVec(const key_type &k) const {
_Vector const &vec = _vec();
EqualKey const &equ = _equ();
typename _Vector::const_iterator iter = vec.begin(), end = vec.end();
for (; iter != end; ++iter) {
if (equ(iter->GetValue().first, k))
break;
}
return iter;
}
// Helper to create the acceleration table if size dictates.
inline void _CreateTableIfNeeded() {
if (size() >= Threshold) {
_CreateTable();
}
}
// Unconditionally create the acceleration table if it doesn't already
// exist.
inline void _CreateTable() {
if (!_h) {
_h.reset(new _HashMap(Threshold, _hash(), _equ()));
for(size_t i=0; i < size(); ++i)
_h->insert(std::make_pair(_vec()[i].GetValue().first, i));
}
}
// Vector holding all elements along with the EqualKey functor. Since
// sizeof(EqualKey) == 0 in many cases we use a compressed_pair to not
// pay a size penalty.
typedef
boost::compressed_pair<
boost::compressed_pair<_Vector, HashFn>,
EqualKey>
_VectorHashFnEqualFn;
_VectorHashFnEqualFn _vectorHashFnEqualFn;
// Optional hash map that maps from keys to vector indices.
std::unique_ptr<_HashMap> _h;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DENSE_HASH_MAP_H
+455
View File
@@ -0,0 +1,455 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DENSE_HASH_SET_H
#define PXR_BASE_TF_DENSE_HASH_SET_H
/// \file tf/denseHashSet.h
#include "pxr/pxr.h"
#include "pxr/base/tf/hashmap.h"
#include <memory>
#include <vector>
#include <boost/compressed_pair.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/utility.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfDenseHashSet
///
/// This is a space efficient container that mimics the TfHashSet API that
/// uses a vector for storage when the size of the set is small.
///
/// When the set gets bigger than \p Threshold a TfHashMap is allocated
/// that is used to accelerate lookup in the vector.
///
/// \warning This differs from a TfHashSet in so far that inserting and
/// removing elements invalidate all iterators of the container.
///
template <
class Element,
class HashFn,
class EqualElement = std::equal_to<Element>,
unsigned Threshold = 128
>
class TfDenseHashSet
{
public:
typedef Element value_type;
////////////////////////////////////////////////////////////////////////////////
private:
// The vector type holding all data for this dense hash set.
typedef std::vector<Element> _Vector;
// The hash map used when the map holds more than Threshold elements.
typedef TfHashMap<Element, size_t, HashFn, EqualElement> _HashMap;
////////////////////////////////////////////////////////////////////////////////
public:
/// An iterator type for this set. Note that this one is const as well,
/// as we can't allow in-place modification of elements due to the
/// potentially allocated hash map.
typedef typename _Vector::const_iterator iterator;
/// A const_iterator type for this set.
typedef typename _Vector::const_iterator const_iterator;
/// Return type for insert() method.
typedef std::pair<const_iterator, bool> insert_result;
public:
/// Ctor.
///
explicit TfDenseHashSet(
const HashFn &hashFn = HashFn(),
const EqualElement &equalElement = EqualElement())
{
_hash() = hashFn;
_equ() = equalElement;
}
/// Copy Ctor.
///
TfDenseHashSet(const TfDenseHashSet &rhs)
: _vectorHashFnEqualFn(rhs._vectorHashFnEqualFn) {
if (rhs._h) {
_h.reset(new _HashMap(*rhs._h));
}
}
/// Move Ctor.
///
TfDenseHashSet(TfDenseHashSet &&rhs) = default;
/// Construct from range.
///
template <class Iterator>
TfDenseHashSet(Iterator begin, Iterator end) {
insert(begin, end);
}
/// Construct from an initializer_list.
///
TfDenseHashSet(std::initializer_list<Element> l) {
insert(l.begin(), l.end());
}
/// Copy assignment operator.
///
TfDenseHashSet &operator=(const TfDenseHashSet &rhs) {
if (this != &rhs) {
TfDenseHashSet temp(rhs);
temp.swap(*this);
}
return *this;
}
/// Move assignment operator.
///
TfDenseHashSet &operator=(TfDenseHashSet &&rhs) = default;
/// Assignment from an initializer_list.
///
TfDenseHashSet &operator=(std::initializer_list<Element> l) {
clear();
insert(l.begin(), l.end());
return *this;
}
/// Equality operator.
///
bool operator==(const TfDenseHashSet &rhs) const {
if (size() != rhs.size())
return false;
//XXX: Should we compare the HashFn and EqualElement too?
const_iterator tend = end();
for(const_iterator iter = begin(); iter != tend; ++iter) {
if (!rhs.count(*iter))
return false;
}
return true;
}
bool operator!=(const TfDenseHashSet &rhs) const {
return !(*this == rhs);
}
/// Erases all of the elements
///
void clear() {
_vec().clear();
_h.reset();
}
/// Swaps the contents of two sets.
///
void swap(TfDenseHashSet &rhs) {
_vectorHashFnEqualFn.swap(rhs._vectorHashFnEqualFn);
_h.swap(rhs._h);
}
/// \c true if the \c set's size is 0.
///
bool empty() const {
return _vec().empty();
}
/// Returns the size of the set.
///
size_t size() const {
return _vec().size();
}
/// Returns an const_iterator pointing to the beginning of the set.
///
const_iterator begin() const {
return _vec().begin();
}
/// Returns an const_iterator pointing to the end of the set.
///
const_iterator end() const {
return _vec().end();
}
/// Finds the element with key \p k.
///
const_iterator find(const Element &k) const {
if (_h) {
typename _HashMap::const_iterator iter = _h->find(k);
if (iter == _h->end())
return end();
return _vec().begin() + iter->second;
}
typename _Vector::const_iterator iter, end = _vec().end();
for(iter = _vec().begin(); iter != end; ++iter)
if (_equ()(*iter, k))
break;
return iter;
}
/// Returns the number of elements with key \p k. Which is either 0 or 1.
///
size_t count(const Element &k) const {
return find(k) != end();
}
/// Returns a pair of <iterator, bool> where iterator points to the element
/// in the list and bool is true if a new element was inserted.
///
insert_result insert(const value_type &v) {
if (_h) {
// Attempt to insert the new index. If this fails, we can't
// insert v.
std::pair<typename _HashMap::iterator, bool> res =
_h->insert(std::make_pair(v, size()));
if (!res.second)
return insert_result(_vec().begin() + res.first->second, false);
} else {
// Bail if already inserted.
const_iterator iter = find(v);
if (iter != end())
return insert_result(iter, false);
}
// Insert at end and create table if necessary.
_vec().push_back(v);
_CreateTableIfNeeded();
return insert_result(std::prev(end()), true);
}
/// Insert a range into the hash set. Note that \p i0 and \p i1 can't
/// point into the hash set.
///
template<class IteratorType>
void insert(IteratorType i0, IteratorType i1) {
// Assume elements are more often than not unique, so if the sum of the
// current size and the size of the range is greater than or equal to
// the threshold, we create the table immediately so we don't do m*n
// work before creating the table.
if (size() + std::distance(i0, i1) >= Threshold)
_CreateTable();
// Insert elements.
for (IteratorType iter = i0; iter != i1; ++iter)
insert(*iter);
}
/// Insert a range of unique elements into the container. [begin, end)
/// *must not* contain any duplicate elements.
///
template <class Iterator>
void insert_unique(Iterator begin, Iterator end) {
// Special-case empty container.
if (empty()) {
_vec().assign(begin, end);
_CreateTableIfNeeded();
} else {
// Just insert, since duplicate checking will use the hash.
insert(begin, end);
}
}
/// Erase element with key \p k. Returns the number of elements erased.
///
size_t erase(const Element &k) {
const_iterator iter = find(k);
if (iter != end()) {
erase(iter);
return 1;
}
return 0;
}
/// Erases element pointed to by \p iter.
///
void erase(const iterator &iter) {
// Erase key from hash table if applicable.
if (_h)
_h->erase(*iter);
// If we are not removing that last element...
if (iter != std::prev(end())) {
using std::swap;
// ... move the last element into the erased placed.
// Note that we can cast constness away because we explicitly update
// the TfHashMap _h below.
swap(*const_cast<Element *>(&(*iter)), _vec().back());
// ... and update the moved element's index.
if (_h)
(*_h)[*iter] = iter - _vec().begin();
}
_vec().pop_back();
}
/// Erases a range from the set.
///
void erase(const iterator &i0, const iterator &i1) {
if (_h) {
for(const_iterator iter = i0; iter != i1; ++iter)
_h->erase(iter->first);
}
const_iterator vremain = _vec().erase(i0, i1);
if (_h) {
for(; vremain != _vec().end(); ++vremain)
(*_h)[*vremain] = vremain - _vec().begin();
}
}
/// Optimize storage space.
///
void shrink_to_fit() {
// Shrink the vector to best size.
_vec().shrink_to_fit();
if (!_h)
return;
size_t sz = size();
// If we have a hash map and are underneath the threshold, discard it.
if (sz < Threshold) {
_h.reset();
} else {
// Otherwise, allocate a new hash map with the optimal size.
_h.reset(new _HashMap(sz, _hash(), _equ()));
for(size_t i=0; i<sz; ++i)
(*_h)[_vec()[i]] = i;
}
}
/// Index into set via \p index.
///
const Element &operator[](size_t index) const {
TF_VERIFY(index < size());
return _vec()[index];
}
////////////////////////////////////////////////////////////////////////////////
private:
// Helper to access the storage vector.
_Vector &_vec() {
return _vectorHashFnEqualFn.first().first();
}
// Helper to access the hash functor.
HashFn &_hash() {
return _vectorHashFnEqualFn.first().second();
}
// Helper to access the equality functor.
EqualElement &_equ() {
return _vectorHashFnEqualFn.second();
}
// Helper to access the storage vector.
const _Vector &_vec() const {
return _vectorHashFnEqualFn.first().first();
}
// Helper to access the hash functor.
const HashFn &_hash() const {
return _vectorHashFnEqualFn.first().second();
}
// Helper to access the equality functor.
const EqualElement &_equ() const {
return _vectorHashFnEqualFn.second();
}
// Helper to create the acceleration table if size dictates.
inline void _CreateTableIfNeeded() {
if (size() >= Threshold) {
_CreateTable();
}
}
// Unconditionally create the acceleration table if it doesn't already
// exist.
inline void _CreateTable() {
if (!_h) {
_h.reset(new _HashMap(Threshold, _hash(), _equ()));
for(size_t i=0; i < size(); ++i)
(*_h)[_vec()[i]] = i;
}
}
// Vector holding all elements along with the EqualElement functor. Since
// sizeof(EqualElement) == 0 in many cases we use a compressed_pair to not
// pay a size penalty.
typedef
boost::compressed_pair<
boost::compressed_pair<_Vector, HashFn>,
EqualElement>
_VectorHashFnEqualFn;
_VectorHashFnEqualFn _vectorHashFnEqualFn;
// Optional hash map that maps from keys to vector indices.
std::unique_ptr<_HashMap> _h;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DENSE_HASH_SET_H
+483
View File
@@ -0,0 +1,483 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DIAGNOSTIC_H
#define PXR_BASE_TF_DIAGNOSTIC_H
/// \file tf/diagnostic.h
/// \ingroup group_tf_Diagnostic
/// Low-level utilities for informing users of various internal and external
/// diagnostic conditions.
///
/// lib/tf supports a range of error-reporting routines.
///
/// For a more detailed explanation of when each of the facilities described
/// in this file is appropriate, (and more importantly, when they're not!)
/// see \ref page_tf_Diagnostic.
#include "pxr/pxr.h"
#include "pxr/base/arch/function.h"
#include "pxr/base/tf/diagnosticLite.h"
#include "pxr/base/tf/api.h"
#if defined(__cplusplus) || defined (doxygen)
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/diagnosticHelper.h"
#include <stddef.h>
#include <stdarg.h>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
// Note: diagnosticLite.h defines the various macros, but we'll document
// them here. The following block is only for doxygen, not seen by a real
// compile. To see the actual macro definition, look in diagnosticLite.h.
#if defined(doxygen)
/// \addtogroup group_tf_Diagnostic
///@{
/// Issue an internal programming error, but continue execution.
///
/// Please see \ref page_tf_TfError for more information about how to use
/// TF_ERROR().
///
/// This is safe to call in secondary threads.
///
/// \hideinitializer
#define TF_ERROR(...)
/// Issue an internal programming error, but continue execution.
///
/// This macro is a convenience. It produces a TF_ERROR() with an error code
/// indicating a coding error. It takes a printf-like format specification or a
/// std::string. Generally, an error handling delegate will take action to turn
/// this error into a python exception, and if it remains unhandled at the end of
/// an application iteration will roll-back the undo stack to a last-known-good
/// state.
///
/// This is safe to call in secondary threads.
///
/// \hideinitializer
#define TF_CODING_ERROR(fmt, args)
/// Issue a generic runtime error, but continue execution.
///
/// This macro is a convenience. It produces a TF_ERROR() with an error code
/// indicating a generic runtime error. It is preferred over TF_ERROR(0),
/// but using a specific error code is preferred over this. It takes a
/// printf-like format specification or a std::string. Generally, an error
/// handling delegate will take action to turn this error into a python
/// exception, and if it remains unhandled at the end of an application iteration
/// will roll-back the undo stack to a last-known-good state.
///
/// This is safe to call in secondary threads.
///
/// \hideinitializer
#define TF_RUNTIME_ERROR(fmt, args)
/// Issue a fatal error and end the program.
///
/// This macro takes a printf-like format specification or a std::string. The
/// program will generally terminate upon a fatal error.
///
/// \hideinitializer
#define TF_FATAL_ERROR(fmt, args)
/// Issue a warning, but continue execution.
///
/// This macro works with a variety of argument sets. It supports simple
/// printf-like format specification or a std::string. It also supports
/// specification of a diagnostic code and a piece of arbitrary information in
/// the form of a TfDiagnosticInfo. The following is a full list of supported
/// argument lists:
///
/// \code
/// TF_WARN(const char *) // plain old string
/// TF_WARN(const char *, ...) // printf like formatting
/// TF_WARN(std::string) // stl string
/// \endcode
///
/// A diagnostic code can be passed in along with the warning message. See
/// \ref DiagnosticEnumConventions for an example of registering an enum type
/// and it's values as diagnostic codes.
///
/// \code
/// TF_WARN(DIAGNOSTIC_ENUM, const char *)
/// TF_WARN(DIAGNOSTIC_ENUM, const char *, ...)
/// TF_WARN(DIAGNOSTIC_ENUM, std::string)
/// \endcode
///
/// A piece of arbitrary data can also be passed in along with the diagnostic
/// code and warning message as follows:
///
/// \code
/// TF_WARN(info, DIAGNOSTIC_ENUM, const char *)
/// TF_WARN(info, DIAGNOSTIC_ENUM, const char *, ...)
/// TF_WARN(info, DIAGNOSTIC_ENUM, std::string)
/// \endcode
///
/// Generally, no adjustment to program state should occur as the result of
/// this macro. This is in contrast with errors as mentioned above.
///
/// This is safe to call in secondary threads.
///
/// \hideinitializer
#define TF_WARN(...)
/// Issue a status message, but continue execution.
///
/// This macro works with a variety of argument sets. It supports simple
/// printf-like format specification or a std::string. It also supports
/// specification of a diagnostic code and a piece of arbitrary information in
/// the form of a TfDiagnosticInfo. The following is a full list of supported
/// argument lists:
///
/// \code
/// TF_STATUS(const char *) // plain old string
/// TF_STATUS(const char *, ...) // printf like formatting
/// TF_STATUS(std::string) // stl string
/// \endcode
///
/// A diagnostic code can be passed in along with the status message. See
/// \ref DiagnosticEnumConventions for an example of registering an enum type
/// and it's values as diagnostic codes.
///
/// \code
/// TF_STATUS(DIAGNOSTIC_ENUM, const char *)
/// TF_STATUS(DIAGNOSTIC_ENUM, const char *, ...)
/// TF_STATUS(DIAGNOSTIC_ENUM, std::string)
/// \endcode
///
/// A piece of arbitrary data can also be passed in along with the diagnostic
/// code and status message as follows:
///
/// \code
/// TF_STATUS(info, DIAGNOSTIC_ENUM, const char *)
/// TF_STATUS(info, DIAGNOSTIC_ENUM, const char *, ...)
/// TF_STATUS(info, DIAGNOSTIC_ENUM, std::string)
/// \endcode
///
/// Generally, no adjustment to program state should occur as the result of
/// this macro. This is in contrast with errors as mentioned above.
///
/// This is safe to call in secondary threads.
///
/// \hideinitializer
#define TF_STATUS(...)
/// Aborts if the condition \c cond is not met.
///
/// \param cond is any expression convertible to bool; if the condition evaluates
/// to \c false, program execution ends with this call.
///
/// Note that the diagnostic message sent is the code \c cond, in the form of
/// a string. Unless the condition expression is self-explanatory, use
/// \c TF_FATAL_ERROR(). See \ref DiagnosticTF_FATAL_ERROR for further
/// discussion.
///
/// Currently, a \c TF_AXIOM() statement is not made a no-op in optimized
/// builds; however, it always possible that either (a) the axiom statement
/// might be removed at some point if the code is deemed correct or (b) in the
/// future, some flavor of build might choose to make axioms be no-ops. Thus,
/// programmers must make \e certain that the code in \p cond is entirely free
/// of side effects.
///
/// \hideinitializer
#define TF_AXIOM(cond)
/// The same as TF_AXIOM, but compiled only in dev builds.
///
/// \param cond is any expression convertible to bool; if the condition evaluates
/// to \c false, program execution ends with this call.
///
/// This macro has the same behavior as TF_AXIOM, but it is compiled only
/// in dev builds. This version should only be used in code that is
/// known (not just suspected!) to be performance critical.
///
/// \hideinitializer
#define TF_DEV_AXIOM(cond)
/// Checks a condition and reports an error if it evaluates false.
///
/// This can be thought of as something like a softer, recoverable TF_AXIOM.
///
/// The macro expands to an expression whose value is either true or false
/// depending on \c cond. If \c cond evaluates to false, issues a coding error
/// indicating the failure.
///
/// \param cond is any expression convertible to bool.
///
/// Usage generally follows patterns like these:
/// \code
/// // Simple check. This is like a non-fatal TF_AXIOM.
/// TF_VERIFY(condition);
///
/// // Avoiding code that requires the condition be met.
/// if (TF_VERIFY(condition)) {
/// // code requiring condition be met.
/// }
///
/// // Executing recovery code in case the condition is not met.
/// if (not TF_VERIFY(condition)) {
/// // recovery code to execute since condition was not met.
/// }
/// \endcode
///
/// Here are some examples:
/// \code
/// // List should be empty. If not, issue an error, clear it out and continue.
/// if (not TF_VERIFY(list.empty()) {
/// // The list was unexpectedly not empty. TF_VERIFY will have
/// // issued a coding error with details. We clear the list and continue.
/// list.clear();
/// }
///
/// // Only add to string if ptr is valid.
/// string result = ...;
/// if (TF_VERIFY(ptr != NULL)) {
/// result += ptr->Method();
/// }
/// \endcode
///
/// The macro also optionally accepts printf-style arguments to generate a
/// message emitted in case the condition is not met. For example:
/// \code
/// if (not TF_VERIFY(index < size,
/// "Index out of bounds (%zu >= %zu)", index, size)) {
/// // Recovery code...
/// }
/// \endcode
///
/// Unmet conditions generate TF_CODING_ERRORs by default, but setting the
/// environment variable TF_FATAL_VERIFY to 1 will make unmet conditions
/// generate TF_FATAL_ERRORs instead and abort the program. This is intended for
/// testing.
///
/// This is safe to call in secondary threads.
///
/// \hideinitializer
#define TF_VERIFY(cond [, format, ...])
#endif /* defined(doxygen) */
//
// The rest of this is seen by a regular compile (or doxygen).
//
#if defined(__cplusplus) || defined(doxygen)
/// Get the name of the current function as a \c std::string.
///
/// This macro will return the name of the current function, nicely
/// formatted, as an \c std::string. This is meant primarily for
/// diagnostics. Code should not rely on a specific format, because it
/// may change in the future or vary across architectures. For example,
/// \code
/// void YourClass::SomeMethod(int x) {
/// cout << "Debugging info about function " << TF_FUNC_NAME() << "." << endl;
/// ...
/// }
/// \endcode
/// Should display something like:
/// "Debugging info about function YourClass::SomeMethod."
///
/// \hideinitializer
#define TF_FUNC_NAME() \
ArchGetPrettierFunctionName(__ARCH_FUNCTION__, __ARCH_PRETTY_FUNCTION__)
void Tf_TerminateHandler();
#if !defined(doxygen)
// Redefine these macros from DiagnosticLite to versions that will accept
// either string or printf-like args.
#ifdef TF_CODING_ERROR
#undef TF_CODING_ERROR
#endif
#define TF_CODING_ERROR(...) \
Tf_PostErrorHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_CODING_ERROR_TYPE, __VA_ARGS__)
#ifdef TF_FATAL_CODING_ERROR
#undef TF_FATAL_CODING_ERROR
#endif
#define TF_FATAL_CODING_ERROR \
Tf_DiagnosticHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_CODING_ERROR_TYPE).IssueFatalError
#ifdef TF_CODING_WARNING
#undef TF_CODING_WARNING
#endif
#define TF_CODING_WARNING(...) \
Tf_PostWarningHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_CODING_ERROR_TYPE, __VA_ARGS__)
#ifdef TF_DIAGNOSTIC_WARNING
#undef TF_DIAGNOSTIC_WARNING
#endif
#define TF_DIAGNOSTIC_WARNING \
Tf_DiagnosticHelper(TF_CALL_CONTEXT.Hide(), \
TF_DIAGNOSTIC_WARNING_TYPE).IssueWarning
#ifdef TF_RUNTIME_ERROR
#undef TF_RUNTIME_ERROR
#endif // TF_RUNTIME_ERROR
#define TF_RUNTIME_ERROR(...) \
Tf_PostErrorHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_RUNTIME_ERROR_TYPE, __VA_ARGS__)
#ifdef TF_FATAL_ERROR
#undef TF_FATAL_ERROR
#endif // TF_FATAL_ERROR
#define TF_FATAL_ERROR \
Tf_DiagnosticHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_FATAL_ERROR_TYPE).IssueFatalError
#ifdef TF_DIAGNOSTIC_FATAL_ERROR
#undef TF_DIAGNOSTIC_FATAL_ERROR
#endif // TF_DIAGNOSTIC_FATAL_ERROR
#define TF_DIAGNOSTIC_FATAL_ERROR \
Tf_DiagnosticHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_RUNTIME_ERROR_TYPE).IssueFatalError
#ifdef TF_DIAGNOSTIC_NONFATAL_ERROR
#undef TF_DIAGNOSTIC_NONFATAL_ERROR
#endif // TF_DIAGNOSTIC_NONFATAL_ERROR
#define TF_DIAGNOSTIC_NONFATAL_ERROR \
Tf_DiagnosticHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_WARNING_TYPE).IssueWarning
// Redefine the following three macros from DiagnosticLite to versions that will
// accept the following sets of arguments:
// * MACRO(const char *, ...)
// * MACRO(const std::string &msg)
// * MACRO(ENUM, const char *, ...)
// * MACRO(ENUM, const std::string *msg)
// * MACRO(TfDiagnosticInfo, ENUM, const char *, ...)
// * MACRO(TfDiagnosticInfo, ENUM, const std::string *msg)
#ifdef TF_WARN
#undef TF_WARN
#endif // TF_WARN
#define TF_WARN(...) \
Tf_PostWarningHelper(TF_CALL_CONTEXT, __VA_ARGS__)
#ifdef TF_STATUS
#undef TF_STATUS
#endif // TF_STATUS
#define TF_STATUS(...) \
Tf_PostStatusHelper(TF_CALL_CONTEXT, __VA_ARGS__)
#ifdef TF_ERROR
#undef TF_ERROR
#endif // TF_ERROR
#define TF_ERROR(...) \
Tf_PostErrorHelper(TF_CALL_CONTEXT, __VA_ARGS__)
#ifdef TF_QUIET_ERROR
#undef TF_QUIET_ERROR
#endif // TF_ERROR
#define TF_QUIET_ERROR(...) \
Tf_PostQuietlyErrorHelper(TF_CALL_CONTEXT, __VA_ARGS__)
// See documentation above.
#define TF_VERIFY(cond, ...) \
(ARCH_LIKELY(cond) ? true : \
Tf_FailedVerifyHelper(TF_CALL_CONTEXT, # cond, \
Tf_VerifyStringFormat(__VA_ARGS__)))
// Helpers for TF_VERIFY.
TF_API bool
Tf_FailedVerifyHelper(TfCallContext const &context,
char const *condition, char const *msg);
// Helpers for TF_VERIFY.
inline char const *
Tf_VerifyStringFormat() { return nullptr; }
TF_API char const *
Tf_VerifyStringFormat(const char *format, ...) ARCH_PRINTF_FUNCTION(1, 2);
#endif // !doxygen
#endif // __cplusplus || doxygen
/// Sets program name for reporting errors.
///
/// This function simply calls to ArchSetProgramNameForErrors().
void TfSetProgramNameForErrors(std::string const& programName);
/// Returns currently set program info.
///
/// This function simply calls to ArchGetProgramNameForErrors().
std::string TfGetProgramNameForErrors();
/// \private
struct Tf_DiagnosticHelper {
Tf_DiagnosticHelper(TfCallContext const &context,
TfDiagnosticType type) :
_context(context),
_type(type)
{
}
TfCallContext const &GetContext() const { return _context; }
TfDiagnosticType GetType() const { return _type; }
TF_API void IssueError(std::string const &msg) const;
TF_API void IssueError(char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
TF_API void IssueFatalError(std::string const &msg) const;
TF_API void IssueFatalError(char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
TF_API void IssueWarning(std::string const &msg) const;
TF_API void IssueWarning(char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
TF_API void IssueStatus(std::string const &msg) const;
TF_API void IssueStatus(char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
private:
TfCallContext _context;
TfDiagnosticType _type;
};
#endif
/// (Re)install Tf's crash handler. This should not generally need to be
/// called since Tf does this itself when loaded. However, when run in 3rd
/// party environments that install their own signal handlers, possibly
/// overriding Tf's, this provides a way to reinstall them, in hopes that
/// they'll stick.
///
/// This calls std::set_terminate() and installs signal handlers for SIGSEGV,
/// SIGBUS, SIGFPE, and SIGABRT.
TF_API
void TfInstallTerminateAndCrashHandlers();
///@}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DIAGNOSTIC_H
+214
View File
@@ -0,0 +1,214 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DIAGNOSTIC_BASE_H
#define PXR_BASE_TF_DIAGNOSTIC_BASE_H
/// \file tf/diagnosticBase.h
#include "pxr/pxr.h"
#include "pxr/base/tf/callContext.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/arch/function.h"
#include <boost/any.hpp>
#include <cstdarg>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
typedef boost::any TfDiagnosticInfo;
class TfDiagnosticMgr;
/// \class TfDiagnosticBase
/// \ingroup group_tf_TfError
///
/// Represents the base class of an object representing a diagnostic message.
///
/// This forms the base class for specific types associated with errors,
/// warnings and status messages. It associates a diagnostic code (which is an
/// enum value) with the message. It can also hold on to arbitrary information
/// associated with the message in a TfDiagnosticInfo.
///
/// See \ref page_tf_TfError in the C++ API reference for a detailed example.
/// For a description of how to post an error, warning or a status message see
/// \c TF_ERROR(), \c TF_WARN and \c TF_STATUS also in the C++ API reference.
///
class TfDiagnosticBase {
public:
/// Return the call context where the message was issued.
const TfCallContext &GetContext() const {
return _context;
}
/// Return the source file name that the diagnostic message was posted from.
std::string GetSourceFileName() const {
return _context.GetFile();
}
/// Return the source line number that the diagnostic message was posted
/// from.
size_t GetSourceLineNumber() const {
return _context.GetLine();
}
/// Return the commentary string describing this diagnostic message.
std::string const &GetCommentary() const {
return _commentary;
}
/// Return the source function that the diagnostic message was posted from.
std::string GetSourceFunction() const {
return ArchGetPrettierFunctionName(_context.GetFunction(),
_context.GetPrettyFunction());
}
/// Add to the commentary string describing this diagnostic message.
///
/// Note: each string added to the commentary is separated from
/// the previous one with a newline. This means that
/// you the string \c s should \e not end with a newline. Thus,
/// \code
/// cout << e.GetCommentary() << "\n";
/// \endcode
/// always prints the entire commentary string as a newline
/// separated sequence of messages.
void AugmentCommentary(const std::string& s) {
if (_commentary.empty())
_commentary = s;
else {
_commentary += "\n";
_commentary += s;
}
}
/// Return the diagnostic code posted.
TfEnum GetDiagnosticCode() const {
return _code;
}
/// Return the diagnostic code posted as a string.
///
/// If the enum value posted with the message has been registered
/// with \c TF_ADD_ENUM_NAME(), then \c GetDiagnosticCodeAsString() will
/// return the symbolic name of the enum.
///
/// If the enum has not been registered, then code of the form
/// \code
/// TF_ERROR(PUCE).Post("is an ugly color");
/// \endcode
/// will still result in \c GetDiagnosticCodeAsString() returning the string
/// "PUCE"; however, code of the form
/// \code
/// MyErrorCode c = PUCE;
/// TF_ERROR(c).Post("is still ugly");
/// \endcode
/// will result in \c GetDiagnosticCodeAsString() returning the
/// (uninformative) string "c".
const std::string& GetDiagnosticCodeAsString() const {
return _codeString;
}
/// Return a (possibly NULL) const pointer to the info object associated
/// with this message.
///
/// If this message was posted without supplying an \c info argument to
/// Post(), e.g.
/// \code
/// TF_ERROR(SOME_CODE).Post("something went wrong");
/// \endcode
///
/// then \c GetInfo() returns NULL. Otherwise, when info is supplied,
/// e.g.
/// \code
/// T myInfo = ...
/// TF_ERROR(SOME_CODE).Post("something went wrong")->SetInfo(myInfo);
/// \endcode
///
/// then a const pointer to a copy of myInfo in the above example is
/// returned by GetInfo<T>(). If the type T doesn't match the held type
/// then GetInfo() returns NULL.
template <typename T>
const T* GetInfo() const {
return boost::any_cast<T>(&_info);
}
/// Set the info object associated with this diagnostic message.
/// \see GetInfo()
void SetInfo(TfDiagnosticInfo any) {
_info = any;
}
/// Return true if the message was posted via \c PostQuietly().
///
/// Notices sent from \c PostQuietly() are indicating that an immediate
/// printout of the error is not desirable, because someone higher up on
/// the stack may actually handle this error. This is rare, but it does
/// happen on occasion.
bool GetQuiet() const {
return _quiet;
}
/// Return the commentary string.
std::string GetPrettyPrintString() const;
/// Return true if this diagnostic's code is a fatal code.
bool IsFatal() const;
/// Return true if this diagnostic's code is either a fatal or nonfatal
/// coding error.
bool IsCodingError() const;
/// Construct an instance.
TfDiagnosticBase(TfEnum code, char const *codeString,
TfCallContext const &context,
const std::string& commentary,
TfDiagnosticInfo info, bool quiet);
protected:
TfCallContext _context;
std::string _commentary;
TfEnum _code;
std::string _codeString;
TfDiagnosticInfo _info;
size_t _serial = 0;
bool _quiet = false;
friend class TfDiagnosticMgr;
friend class TfErrorTransport;
friend class TfErrorMark;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DIAGNOSTIC_BASE_H
+197
View File
@@ -0,0 +1,197 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DIAGNOSTIC_HELPER_H
#define PXR_BASE_TF_DIAGNOSTIC_HELPER_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/attributes.h"
// XXX: This include is a hack to avoid build errors due to
// incompatible macro definitions in pyport.h on macOS.
#include <locale>
#include <boost/any.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
typedef boost::any TfDiagnosticInfo;
class TfCallContext;
enum TfDiagnosticType : int;
class TfEnum;
class TfError;
TF_API bool
Tf_PostErrorHelper(
const TfCallContext &context,
const TfEnum &code,
const std::string &msg);
TF_API bool
Tf_PostErrorHelper(
const TfCallContext &context,
TfDiagnosticType code,
const std::string &msg);
TF_API bool
Tf_PostErrorHelper(
const TfCallContext &context,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(3, 4);
TF_API bool
Tf_PostErrorHelper(
const TfCallContext &context,
TfDiagnosticType code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(3, 4);
TF_API bool
Tf_PostErrorHelper(
const TfCallContext &context,
const TfDiagnosticInfo &info,
const TfEnum &code,
const std::string &msg);
TF_API bool
Tf_PostErrorHelper(
const TfCallContext &context,
const TfDiagnosticInfo &info,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(4, 5);
TF_API bool
Tf_PostQuietlyErrorHelper(
const TfCallContext &context,
const TfEnum &code,
const TfDiagnosticInfo &info,
const std::string &msg);
TF_API bool
Tf_PostQuietlyErrorHelper(
const TfCallContext &context,
const TfEnum &code,
const TfDiagnosticInfo &info,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(4, 5);
TF_API bool
Tf_PostQuietlyErrorHelper(
const TfCallContext &context,
const TfEnum &code,
const std::string &msg);
TF_API bool
Tf_PostQuietlyErrorHelper(
const TfCallContext &context,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(3, 4);
// Helper functions for posting a warning with TF_WARN.
TF_API void
Tf_PostWarningHelper(const TfCallContext &context,
const std::string &msg);
TF_API void
Tf_PostWarningHelper(const TfCallContext &context,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(2, 3);
TF_API void
Tf_PostWarningHelper(
const TfCallContext &context,
const TfEnum &code,
const std::string &msg);
TF_API void
Tf_PostWarningHelper(
const TfCallContext &context,
TfDiagnosticType code,
const std::string &msg);
TF_API void
Tf_PostWarningHelper(
const TfCallContext &context,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(3, 4);
TF_API void
Tf_PostWarningHelper(
const TfCallContext &context,
TfDiagnosticType code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(3, 4);
TF_API void
Tf_PostWarningHelper(
const TfCallContext &context,
const TfDiagnosticInfo &info,
const TfEnum &code,
const std::string &msg);
TF_API void
Tf_PostWarningHelper(
const TfCallContext &context,
const TfDiagnosticInfo &info,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(4, 5);
TF_API void
Tf_PostStatusHelper(
const TfCallContext &context,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(2, 3);
TF_API void
Tf_PostStatusHelper(
const TfCallContext &context,
const std::string &msg);
TF_API void
Tf_PostStatusHelper(
const TfCallContext &context,
const TfEnum &code,
const std::string &msg);
TF_API void
Tf_PostStatusHelper(
const TfCallContext &context,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(3, 4);
TF_API void
Tf_PostStatusHelper(
const TfCallContext &context,
const TfDiagnosticInfo &info,
const TfEnum &code,
const std::string &msg);
TF_API void
Tf_PostStatusHelper(
const TfCallContext &context,
const TfDiagnosticInfo &info,
const TfEnum &code,
const char *fmt, ...) ARCH_PRINTF_FUNCTION(4, 5);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DIAGNOSTIC_HELPER_H
+150
View File
@@ -0,0 +1,150 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DIAGNOSTIC_LITE_H
#define PXR_BASE_TF_DIAGNOSTIC_LITE_H
/// \file tf/diagnosticLite.h
/// Stripped down version of \c diagnostic.h that doesn't define \c std::string.
///
/// This file provides the same functionality as \c diagnostic.h, except that
/// all strings must be passed as plain \c const \c char*, and not by
/// \c std::string, and the macro \c TF_FUNCTION_NAME() is only defined by
/// \c diagnostic.h
///
/// In particular, this header file does not include the C++ header file
/// \c < \c string \c >, making inclusion of this file a very light-weight
/// addition. Include this file, as opposed to pxr/base/tf/diagnostic.h in
/// header files that need to remain as light-weight as possible.
///
/// These macros are safe to use in multiple threads.
#include "pxr/pxr.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/buildMode.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/callContext.h"
#include <stddef.h>
PXR_NAMESPACE_OPEN_SCOPE
/// \enum TfDiagnosticType
/// Enum describing various diagnostic conditions.
enum TfDiagnosticType : int {
TF_DIAGNOSTIC_INVALID_TYPE = 0,
TF_DIAGNOSTIC_CODING_ERROR_TYPE,
TF_DIAGNOSTIC_FATAL_CODING_ERROR_TYPE,
TF_DIAGNOSTIC_RUNTIME_ERROR_TYPE,
TF_DIAGNOSTIC_FATAL_ERROR_TYPE,
TF_DIAGNOSTIC_NONFATAL_ERROR_TYPE,
TF_DIAGNOSTIC_WARNING_TYPE,
TF_DIAGNOSTIC_STATUS_TYPE,
TF_APPLICATION_EXIT_TYPE,
};
#if !defined(doxygen)
struct Tf_DiagnosticLiteHelper {
constexpr Tf_DiagnosticLiteHelper(TfCallContext const &context,
TfDiagnosticType type)
: _context(context),
_type(type)
{
}
TF_API void IssueError(
char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
TF_API void IssueFatalError(
char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
TF_API void IssueWarning(
char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
TF_API void IssueStatus(
char const *fmt, ...) const ARCH_PRINTF_FUNCTION(2,3);
private:
TfCallContext _context;
TfDiagnosticType _type;
};
#define TF_CODING_ERROR \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_CODING_ERROR_TYPE).IssueError
#define TF_CODING_WARNING \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_CODING_ERROR_TYPE).IssueWarning \
#define TF_FATAL_CODING_ERROR \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_CODING_ERROR_TYPE).IssueFatalError
#define TF_RUNTIME_ERROR \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_RUNTIME_ERROR_TYPE).IssueError
#define TF_FATAL_ERROR \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_FATAL_ERROR_TYPE).IssueFatalError
#define TF_DIAGNOSTIC_FATAL_ERROR \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_RUNTIME_ERROR_TYPE).IssueFatalError
#define TF_DIAGNOSTIC_NONFATAL_ERROR \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_WARNING_TYPE).IssueWarning
#define TF_DIAGNOSTIC_WARNING \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT.Hide(), \
TF_DIAGNOSTIC_WARNING_TYPE).IssueWarning
#define TF_WARN \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_WARNING_TYPE).IssueWarning
#define TF_STATUS \
Tf_DiagnosticLiteHelper(TF_CALL_CONTEXT, \
TF_DIAGNOSTIC_STATUS_TYPE).IssueStatus
constexpr bool
Tf_AxiomHelper(bool val, TfCallContext const &ctx, char const *txt) {
return (ARCH_LIKELY(val)) ? true :
(Tf_DiagnosticLiteHelper(ctx, TF_DIAGNOSTIC_FATAL_ERROR_TYPE).
IssueFatalError("Failed axiom: ' %s '", txt), false);
}
#define TF_AXIOM(cond) \
Tf_AxiomHelper(static_cast<bool>((cond)), TF_CALL_CONTEXT, #cond)
#define TF_DEV_AXIOM(cond) \
Tf_AxiomHelper(!ARCH_DEV_BUILD || \
static_cast<bool>((cond)), TF_CALL_CONTEXT, #cond)
#endif // !defined(doxygen)
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DIAGNOSTIC_LITE_H
+473
View File
@@ -0,0 +1,473 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DIAGNOSTIC_MGR_H
#define PXR_BASE_TF_DIAGNOSTIC_MGR_H
/// \file tf/diagnosticMgr.h
#include "pxr/pxr.h"
#include "pxr/base/tf/callContext.h"
#include "pxr/base/tf/debug.h"
#include "pxr/base/tf/diagnosticLite.h"
#include "pxr/base/tf/error.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/status.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/warning.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/arch/functionLite.h"
#include <tbb/enumerable_thread_specific.h>
#include <tbb/spin_rw_mutex.h>
#include <atomic>
#include <cstdarg>
#include <list>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
TF_DEBUG_CODES(
TF_LOG_STACK_TRACE_ON_ERROR,
TF_LOG_STACK_TRACE_ON_WARNING,
TF_ERROR_MARK_TRACKING,
TF_PRINT_ALL_POSTED_ERRORS_TO_STDERR
);
class TfError;
class TfErrorMark;
/// \class TfDiagnosticMgr
/// \ingroup group_tf_Diagnostic
///
/// Singleton class through which all errors and diagnostics pass.
class TfDiagnosticMgr : public TfWeakBase {
public:
typedef TfDiagnosticMgr This;
typedef std::list<TfError> ErrorList;
/// Synonym for standard STL iterator to traverse the error list.
///
/// The error list for a thread is an STL list. The \c ErrorIterator type
/// is an STL iterator and can be used without restriction in any way that
/// it is legal to use an STL iterator.
///
/// Given an iterator, one accesses the error in the standard STL fashion:
/// \code
/// TfErrorMark m;
///
/// ... ;
/// if (!m.IsClean()) {
/// TfErrorMark::Iterator i;
/// for (i = m.GetBegin(); i != m.GetEnd(); ++i) {
/// cout << "file = " << i->GetSourceFileName()
/// << "line = " << i->GetSourceLineNumber() << "\n";
/// }
/// \endcode
typedef ErrorList::iterator ErrorIterator;
/// Returns the name of the given diagnostic code.
TF_API
static std::string GetCodeName(const TfEnum &code);
/// Return a human-readable diagnostic message. The TfDiagnosticMgr uses
/// this function to print diagnostics when no diagnostic delegates are
/// installed. Diagnostic delegate implementations can call this to produce
/// messages in the same format, if desired.
TF_API
static std::string FormatDiagnostic(const TfEnum &code,
const TfCallContext &context, const std::string &msg,
const TfDiagnosticInfo &info);
/// \class Delegate
/// One may set a delegate with the \c TfDiagnosticMgr which will be
/// called to respond to errors and diagnostics.
///
/// \note None of the methods in \c TfDiagnosticMgr::Delegate can be
/// reentrant.
///
/// Practically speaking, this means they cannot invoke:
///
/// - TF_ERROR
/// - TF_RUNTIME_ERROR
/// - TF_CODING_ERROR
/// - TF_WARN
/// - TF_STATUS
///
/// For a more complete list, see diagnostic.h
///
class Delegate {
public:
TF_API
virtual ~Delegate() = 0;
/// Called when a \c TfError is posted.
virtual void IssueError(TfError const &err) = 0;
/// Called when a \c TF_FATAL_ERROR is issued (or a failed
/// \c TF_AXIOM).
virtual void IssueFatalError(TfCallContext const &context,
std::string const &msg) = 0;
/// Called when a \c TF_STATUS() is issued.
virtual void IssueStatus(TfStatus const &status) = 0;
/// Called when a \c TF_WARNING() is issued.
virtual void IssueWarning(TfWarning const &warning) = 0;
protected:
/// Abort the program, but avoid the session logging mechanism. This
/// is intended to be used for fatal error cases where any information
/// has already been logged.
TF_API
void _UnhandledAbort() const;
};
/// Return the singleton instance.
TF_API static This &GetInstance() {
return TfSingleton<This>::GetInstance();
}
/// Add the delegate \p delegate to the list of current delegates.
///
/// This will add the delegate even if it already exists in the list.
///
/// Each delegate will be called when diagnostics and errors are invoked
///
/// This function is thread safe.
TF_API
void AddDelegate(Delegate* delegate);
/// Removes all delegates equal to \p delegate from the current delegates.
///
/// This function is thread safe.
TF_API
void RemoveDelegate(Delegate* delegate);
/// Set whether errors, warnings and status messages should be printed out
/// to the terminal.
TF_API
void SetQuiet(bool quiet) { _quiet = quiet; }
/// Return an iterator to the beginning of this thread's error list.
ErrorIterator GetErrorBegin() { return _errorList.local().begin(); }
/// Return an iterator to the end of this thread's error list.
ErrorIterator GetErrorEnd() { return _errorList.local().end(); }
/// Remove error specified by iterator \p i.
/// \deprecated Use TfErrorMark instead.
TF_API
ErrorIterator EraseError(ErrorIterator i);
/// Remove all the errors in [first, last) from this thread's error
/// stream. This should generally not be invoked directly. Use TfErrorMark
/// instead.
TF_API
ErrorIterator EraseRange(ErrorIterator first, ErrorIterator last);
/// Append an error to the list of active errors. This is generally not
/// meant to be called by user code. It is public so that the system
/// which translates tf errors to and from python exceptions can manage
/// errors.
TF_API
void AppendError(TfError const &e);
/// This method will create a TfError, append it to the error list, and
/// pass it to all delegates.
///
/// If no delegates have been registered and no error mark is active, this
/// method will print the error to stderr.
TF_API
void PostError(TfEnum errorCode, const char* errorCodeString,
TfCallContext const &context,
const std::string& commentary, TfDiagnosticInfo info,
bool quiet);
/// This method will create a TfError, append it to the error list, and
/// pass it to all delegates.
///
/// If no delegates have been registered and no error mark is active, this
/// method will print the error to stderr.
TF_API
void PostError(const TfDiagnosticBase& diagnostic);
/// This method will create a TfWarning and pass it to all delegates.
///
/// If no delegates have been registered, this method will print the
/// warning msg to stderr.
TF_API
void PostWarning(TfEnum warningCode, const char *warningCodeString,
TfCallContext const &context, std::string const &commentary,
TfDiagnosticInfo info, bool quiet) const;
/// This method will create a TfWarning and pass it to all delegates.
///
/// If no delegates have been registered, this method will print the
/// warning msg to stderr.
TF_API
void PostWarning(const TfDiagnosticBase& diagnostic) const;
/// This method will create a TfStatus and pass it to all delegates.
///
/// If no delegates have been registered, this method will print the
/// status msg to stderr.
TF_API
void PostStatus(TfEnum statusCode, const char *statusCodeString,
TfCallContext const &context, std::string const &commentary,
TfDiagnosticInfo info, bool quiet) const;
/// This method will create a TfStatus and pass it to all delegates.
///
/// If no delegates have been registered, this method will print the
/// status msg to stderr.
TF_API
void PostStatus(const TfDiagnosticBase& diagnostic) const;
/// This method will issue a fatal error to all delegates.
///
/// If no delegates have been registered, this method will print the error
/// msg and abort the process.
TF_API
void PostFatal(TfCallContext const &context, TfEnum statusCode,
std::string const &msg) const;
/// Return true if an instance of TfErrorMark exists in the current thread
/// of execution, false otherwise.
bool HasActiveErrorMark() { return _errorMarkCounts.local() > 0; }
#if !defined(doxygen)
//
// Public, but *only* meant to be used by the TF_ERROR() macro.
//
/// \private
class ErrorHelper {
public:
ErrorHelper(TfCallContext const &context, TfEnum errorCode,
const char* errorCodeString)
: _context(context), _errorCode(errorCode),
_errorCodeString(errorCodeString)
{
}
TF_API
void Post(const char* fmt, ...) const
ARCH_PRINTF_FUNCTION(2,3);
TF_API
void PostQuietly(const char* fmt, ...) const
ARCH_PRINTF_FUNCTION(2,3);
TF_API
void Post(const std::string& msg) const;
TF_API
void PostWithInfo(
const std::string& msg,
TfDiagnosticInfo info = TfDiagnosticInfo()) const;
TF_API
void PostQuietly(const std::string& msg,
TfDiagnosticInfo info = TfDiagnosticInfo()) const;
private:
TfCallContext _context;
TfEnum _errorCode;
const char *_errorCodeString;
};
struct WarningHelper {
WarningHelper(TfCallContext const &context, TfEnum warningCode,
const char *warningCodeString)
: _context(context), _warningCode(warningCode),
_warningCodeString(warningCodeString)
{
}
TF_API
void Post(const char* fmt, ...) const
ARCH_PRINTF_FUNCTION(2,3);
TF_API
void PostQuietly(const char* fmt, ...) const
ARCH_PRINTF_FUNCTION(2,3);
TF_API
void Post(const std::string &str) const;
TF_API
void PostWithInfo(
const std::string& msg,
TfDiagnosticInfo info = TfDiagnosticInfo()) const;
TF_API
void PostQuietly(const std::string& msg) const;
private:
TfCallContext _context;
TfEnum _warningCode;
const char *_warningCodeString;
};
struct StatusHelper {
StatusHelper(TfCallContext const &context, TfEnum statusCode,
const char *statusCodeString)
: _context(context), _statusCode(statusCode),
_statusCodeString(statusCodeString)
{
}
TF_API
void Post(const char* fmt, ...) const
ARCH_PRINTF_FUNCTION(2,3);
TF_API
void PostQuietly(const char* fmt, ...) const
ARCH_PRINTF_FUNCTION(2,3);
TF_API
void Post(const std::string &str) const;
TF_API
void PostWithInfo(
const std::string& msg,
TfDiagnosticInfo info = TfDiagnosticInfo()) const;
TF_API
void PostQuietly(const std::string& msg) const;
private:
TfCallContext _context;
TfEnum _statusCode;
const char *_statusCodeString;
};
struct FatalHelper {
FatalHelper(TfCallContext const &context, TfEnum statusCode)
: _context(context),
_statusCode(statusCode)
{
}
void Post(const std::string &str) const {
This::GetInstance().PostFatal(_context, _statusCode, str);
}
private:
TfCallContext _context;
TfEnum _statusCode;
};
#endif
private:
TfDiagnosticMgr();
virtual ~TfDiagnosticMgr();
friend class TfSingleton<This>;
// Return an iterator to the first error with serial number >= mark, or the
// past-the-end iterator, if no such errors exist.
TF_API
ErrorIterator _GetErrorMarkBegin(size_t mark, size_t *nErrors);
// Invoked by ErrorMark ctor.
inline void _CreateErrorMark() { ++_errorMarkCounts.local(); }
// Invoked by ErrorMark dtor.
inline bool _DestroyErrorMark() { return --_errorMarkCounts.local() == 0; }
// Report an error, either via delegate or print to stderr, and issue a
// notice if this thread of execution is the main thread.
void _ReportError(const TfError &err);
// Splice the errors in src into this thread's local list. Also reassign
// serial numbers to all the spliced errors to ensure they work correctly
// with local error marks.
void _SpliceErrors(ErrorList &src);
// Helper to append pending error messages to the crash log.
void _AppendErrorsToLogText(ErrorIterator i);
// Helper to fully rebuild the crash log error text when errors are erased
// from the middle.
void _RebuildErrorLogText();
// Helper to actually publish log text into the Arch crash handler.
void _SetLogInfoForErrors(std::vector<std::string> const &logText) const;
// A guard used to protect reentrency when adding/removing
// delegates as well as posting errors/warnings/statuses
mutable tbb::enumerable_thread_specific<bool> _reentrantGuard;
// The registered delegates.
std::vector<Delegate*> _delegates;
mutable tbb::spin_rw_mutex _delegatesMutex;
// Global serial number for sorting.
std::atomic<size_t> _nextSerial;
// Thread-specific error list.
tbb::enumerable_thread_specific<ErrorList> _errorList;
// Thread-specific diagnostic log text for pending errors.
struct _LogText {
void AppendAndPublish(ErrorIterator i, ErrorIterator end);
void RebuildAndPublish(ErrorIterator i, ErrorIterator end);
std::pair<std::vector<std::string>,
std::vector<std::string>> texts;
bool parity = false;
private:
void _AppendAndPublishImpl(bool clear,
ErrorIterator i, ErrorIterator end);
};
tbb::enumerable_thread_specific<_LogText> _logText;
// Thread-specific error mark counts. Use a native key for best performance
// here.
tbb::enumerable_thread_specific<
size_t, tbb::cache_aligned_allocator<size_t>,
tbb::ets_key_per_instance> _errorMarkCounts;
bool _quiet;
friend class TfError;
friend class TfErrorTransport;
friend class TfErrorMark;
};
TF_API_TEMPLATE_CLASS(TfSingleton<TfDiagnosticMgr>);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_DIAGNOSTIC_MGR_H
+78
View File
@@ -0,0 +1,78 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_DL_H
#define PXR_BASE_TF_DL_H
/// \file tf/dl.h
/// \ingroup group_tf_SystemsExt
/// Interface for opening code libraries.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/library.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \addtogroup group_tf_SystemsExt
///@{
/// Open a dynamic library and notify \c lib/tf that a new module has been
/// loaded.
///
/// This is a wrapper around ArchLibraryOpen() in the sense that this function
/// calls \c ArchLibraryOpen(\p filename, \p flag) but it will additionally
/// load script bindings if scripting is initialized and loading is requested.
///
/// If \p error is not \c NULL it will be set to a system reported error
/// if opening the library failed, otherwise it will be cleared.
///
/// If you set TF_DLOPEN in the TF_DEBUG environment variable then debug
/// output will be reported on each invocation of this function.
///
/// This returns an opaque handle to the opened library or \c NULL on
/// failure.
TF_API
void* TfDlopen(const std::string &filename,
int flag,
std::string *error = NULL,
bool loadScriptBindings = true);
/// Close a dynamic library.
TF_API
int TfDlclose(void* handle);
/// \private
TF_API
bool Tf_DlOpenIsActive();
/// \private
TF_API
bool Tf_DlCloseIsActive();
///@}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+457
View File
@@ -0,0 +1,457 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ENUM_H
#define PXR_BASE_TF_ENUM_H
/// \file tf/enum.h
/// \ingroup group_tf_RuntimeTyping
#include "pxr/pxr.h"
#include "pxr/base/arch/defines.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/preprocessorUtils.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include "pxr/base/tf/safeTypeCompare.h"
#include "pxr/base/tf/api.h"
#include <boost/operators.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <iosfwd>
#include <string>
#include <typeinfo>
#include <type_traits>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfEnum
/// \ingroup group_tf_RuntimeTyping
///
/// An enum class that records both enum type and enum value.
///
/// \section cppcode_runtimeTyping Run-Time Typing
///
/// A \c TfEnum can hold an enum variable of any enum type, while still
/// being able to distinguish between various enum types.
/// Here is an example:
///
/// \code
/// enum Monsters { SULLEY = 0, MIKE, ROZ };
/// enum Fish { NEMO = 0, FATHER, DORY };
///
/// TfEnum t1 = MIKE,
/// t2 = NEMO;
///
/// t1 == MIKE; // yields true
/// t2 == NEMO; // yields true
/// t1 == t2; // yields false
/// t1 == SULLEY; // yields false
///
/// t1.IsA<Monsters>(); // yields true
/// t1.IsA<Fish>(); // yields false
/// \endcode
///
/// Even though \c NEMO and \c SULLEY both are represented with integral
/// value zero, \c t1 and \c t2 compare false. A \c TfEnum can be passed
/// by value, assigned, etc. just like a regular \c Enum variable.
/// A \c TfEnum can also hold a plain integer, which will compare false against
/// any other enum variable.
///
/// \section cppcode_enumvals Associating Names with Enumerated Values
///
/// The \c TfEnum class can also be used to represent enumerated values
/// as strings. This can be useful for storing enum values in files for
/// later retrieval.
///
/// Use the \c TF_ADD_ENUM_NAME() macro to set up and enable strings
/// for the values of an enum. Once this is done, several static
/// \c TfEnum methods may be used to look up names corresponding to enum
/// values and vice-versa.
///
/// For example, see \c TfRegistryManager to understand the use of
/// the \c TF_REGISTRY_FUNCTION() macro below:
///
/// \section cppcode_enumRegMacro Enum Registration Macro
///
/// \code
/// // header file
/// // Declare an enumerated type with some values
/// enum Season {
/// SPRING,
/// SUMMER = 3, // It's ok to have initializers
/// AUTUMN,
/// WINTER
/// };
///
/// // source file
/// #include "pxr/base/tf/registryManager.h"
/// TF_REGISTRY_FUNCTION(TfEnum) {
/// // Register the names for the values:
/// TF_ADD_ENUM_NAME(SPRING);
/// TF_ADD_ENUM_NAME(SUMMER);
/// TF_ADD_ENUM_NAME(AUTUMN);
/// TF_ADD_ENUM_NAME(WINTER);
/// }
///
/// // another source file:
///
/// // Look up the name for a value:
/// string name1 = TfEnum::GetName(SUMMER); // Returns "SUMMER"
/// string name2 = TfEnum::GetFullName(SUMMER); // Returns "Season::SUMMER"
///
/// // Look up the value for a name:
/// bool found;
/// Season s1 = TfEnum::GetValueFromName<Season>("AUTUMN", &found);
/// // Returns 4, sets found to true
/// Season s2 = TfEnum::GetValueFromName<Season>("MONDAY", &found);
/// // Returns -1, sets found to false
///
/// // Look up a fully-qualified name. Since this is not a templated
/// // function, it has to return a generic value type, so we use
/// // TfEnum.
/// TfEnum s3 = TfEnum::GetValueFromFullName("Season::WINTER", &found);
/// // Returns 5, sets found to \c true
/// \endcode
///
class TfEnum : boost::totally_ordered<TfEnum>
{
public:
/// Default constructor assigns integer value zero.
TfEnum()
: _typeInfo(&typeid(int)), _value(0)
{
}
/// Initializes value to enum variable \c value of enum type \c T.
template <class T>
TfEnum(T value,
std::enable_if_t<std::is_enum<T>::value> * = 0)
: _typeInfo(&typeid(T)), _value(int(value))
{
}
/// Initializes value to integral value \p value with enum type \c ti.
///
/// \warning This is only for use in extreme circumstances; there is no
/// way for an implementation to guarantee that \p ti is really an enum
/// type, and/or that \p value is a valid value for that enum type.
TfEnum(const std::type_info& ti, int value)
: _typeInfo(&ti), _value(value)
{
}
/// True if \c *this and \c t have both the same type and value.
bool operator==(const TfEnum& t) const {
return t._value == _value &&
TfSafeTypeCompare(*t._typeInfo, *_typeInfo);
}
/// Less than comparison. Enum values belonging to the same type are
/// ordered according to their numeric value. Enum values belonging to
/// different types are ordered in a consistent but arbitrary way which
/// may vary between program runs.
bool operator<(const TfEnum& t) const {
return _typeInfo->before(*t._typeInfo) ||
(!t._typeInfo->before(*_typeInfo) && _value < t._value);
}
/// True if \c *this has been assigned with \c value.
template <class T>
std::enable_if_t<std::is_enum<T>::value, bool>
operator==(T value) const {
return int(value) == _value && IsA<T>();
}
/// False if \c *this has been assigned with \c value.
template <class T>
std::enable_if_t<std::is_enum<T>::value, bool>
operator!=(T value) const {
return int(value) != _value || !IsA<T>();
}
/// Compare a literal enum value \a val of enum type \a T with TfEnum \a e.
template <class T>
friend std::enable_if_t<std::is_enum<T>::value, bool>
operator==(T val, TfEnum const &e) {
return e == val;
}
/// Compare a literal enum value \a val of enum type \a T with TfEnum \a e.
template <class T>
friend std::enable_if_t<std::is_enum<T>::value, bool>
operator!=(T val, TfEnum const &e) {
return e != val;
}
/// True if \c *this has been assigned any enumerated value of type \c T.
template <class T>
bool IsA() const {
return TfSafeTypeCompare(*_typeInfo, typeid(T));
}
/// True if \c *this has been assigned any enumerated value of type
/// \c T with \c typeid(T)==t.
bool IsA(const std::type_info& t) const {
return TfSafeTypeCompare(*_typeInfo, t);
}
/// Returns the type of the enum value, as an \c std::type_info.
const std::type_info& GetType() const {
return *_typeInfo;
}
/// Returns the integral value of the enum value.
const int& GetValueAsInt() const {
return _value;
}
/// Returns the enum value for the enum type \c T.
///
/// \warning This function can cause your program to abort if not used
/// properly.
///
/// If it is possible that the enum value is not of type \c T, first use
/// \c IsA() to test whether the enum value is of type \c T before calling
/// \c GetValue<T>().
///
/// Note that if \c IsA<T>() succeeds, then \c GetValue<T>() will also
/// succeed.
template <typename T>
T GetValue() const {
if (!IsA<T>())
_FatalGetValueError(typeid(T));
return T(_value);
}
/// Conversion operator for enum and integral types only.
template <typename T,
typename = typename std::enable_if<
std::is_integral<T>::value ||
std::is_enum<T>::value>::type
>
operator T() const
{
return T(_value);
}
/// \name Retrieving Corresponding Names and Enumerated Values
///
/// The methods in this group can be used to retrieve corresponding names
/// and values. The correspondences are set up with the
/// \c TF_ADD_ENUM_NAME() macro.
///
///@{
/// Returns the name associated with an enumerated value.
///
/// If there is no such name registered, an empty string is returned.
TF_API static std::string GetName(TfEnum val);
/// Returns the fully-qualified name for an enumerated value.
///
/// This returns a fully-qualified enumerated value name (e.g.,
/// \c "Season::WINTER") associated with the given value. If there is no
/// such name registered, an empty string is returned.
TF_API static std::string GetFullName(TfEnum val);
/// Returns the display name for an enumerated value.
///
/// This returns a user interface-suitable string for the given enumerated
/// value.
TF_API static std::string GetDisplayName(TfEnum val);
/// Returns a vector of all the names associated with an enum type.
///
/// This returns a vector of all the names associated with the enum that
/// contains the type \p val. The names are not fully qualified. For
/// example, \c TfEnum::GetAllNames(WINTER) would return a vector
/// containing "SPRING", "SUMMER", "AUTUMN", and "WINTER".
///
/// If there are no such names registered, an empty vector is returned.
static std::vector<std::string> GetAllNames(TfEnum val) {
return GetAllNames(val.GetType());
}
/// \overload
TF_API static std::vector<std::string> GetAllNames(const std::type_info &ti);
/// Returns a vector of all the names associated with an enum type.
///
/// This returns a vector of all the names associated with the enum
/// type \c T. The names are not fully qualified. For
/// example, \c TfEnum::GetAllNames<Season>() would return a vector
/// containing "SPRING", "SUMMER", "AUTUMN", and "WINTER".
///
/// If there are no such names registered, an empty vector is returned.
template <class T>
static std::vector<std::string> GetAllNames() {
return GetAllNames(typeid(T));
}
/// Returns the typeid for a given enum type name.
///
/// This returns a pointer to the type_info associated with the enum that
/// has the type name \c typeName. If no such enum is registered, returns
/// NULL.
TF_API
static const std::type_info *GetTypeFromName(const std::string& typeName);
/// Returns the enumerated value for a name.
///
/// If there is no such name registered, this returns -1. Since -1 can
/// sometimes be a valid value, the \p foundIt flag pointer, if not \c
/// NULL, is set to \c true if the name was found and \c false otherwise.
template <class T>
static T GetValueFromName(const std::string &name, bool *foundIt = NULL) {
TfEnum e = GetValueFromName(typeid(T), name, foundIt);
return T(e.GetValueAsInt());
}
/// Returns the enumerated value for a name.
///
/// This is a template-independent version of \c GetValueFromName().
TF_API
static TfEnum GetValueFromName(const std::type_info& ti,
const std::string &name,
bool *foundIt = NULL);
/// Returns the enumerated value for a fully-qualified name.
///
/// This takes a fully-qualified enumerated value name (e.g.,
/// \c "Season::WINTER") and returns the associated value. If there is
/// no such name, this returns -1. Since -1 can sometimes be a
/// valid value, the \p foundIt flag pointer, if not \c NULL, is
/// set to \c true if the name was found and \c false
/// otherwise. Also, since this is not a templated function, it has
/// to return a generic value type, so we use \c TfEnum.
TF_API
static TfEnum GetValueFromFullName(const std::string &fullname,
bool *foundIt = NULL);
/// Returns true if \p typeName is a known enum type.
///
/// If any enum whose demangled type name is \p typeName has been
/// added via \c TF_ADD_ENUM_NAME(), this function returns true.
TF_API
static bool IsKnownEnumType(const std::string& typeName);
///@}
/// Associates a name with an enumerated value.
///
/// \warning This method is called by the \c TF_ADD_ENUM_NAME() macro, and
/// should NOT be called directly. Instead, call AddName(), which does
/// exactly the same thing.
TF_API
static void _AddName(TfEnum val, const std::string &valName,
const std::string &displayName="");
/// Associates a name with an enumerated value.
/// \see _AddName().
static void AddName(TfEnum val, const std::string &valName,
const std::string &displayName="")
{
_AddName(val, valName, displayName);
}
template <typename T>
static TfEnum IntegralEnum(T value) {
TfEnum e;
e._typeInfo = &typeid(T);
e._value = int(value);
return e;
}
private:
// Internal constructor for int values.
explicit TfEnum(int value)
: _typeInfo(&typeid(int)), _value(value)
{
}
// Internal constructor for size_t values.
explicit TfEnum(size_t value)
: _typeInfo(&typeid(size_t)), _value(static_cast<int>(value))
{
}
TF_API
void _FatalGetValueError(std::type_info const& typeInfo) const;
const std::type_info* _typeInfo;
int _value;
};
// TfHash support. Make the enum parameter be a deduced template type but
// enable the overload only for TfEnum. This disables implicit conversion from
// ordinary enum types to TfEnum.
template <class HashState, class Enum>
std::enable_if_t<std::is_same<Enum, TfEnum>::value>
TfHashAppend(HashState &h, Enum const &e)
{
h.Append(TfHashAsCStr(e.GetType().name()));
h.Append(e.GetValueAsInt());
}
/// Output a TfEnum value.
/// \ingroup group_tf_DebuggingOutput
TF_API std::ostream& operator<<(std::ostream& out, const TfEnum & e);
/// Macro used to associate a name with an enumerated value.
///
/// \c TF_ADD_ENUM_NAME() registers a name for an enumerated value so that the
/// association can be accessed in calls to \c TfEnum::GetValueFromName(),
/// \c TfEnum::GetValueFromFullName(), \c TfEnum::GetName(), and
/// \c TfEnum::GetFullName(). It's first argument, \p VAL, is the symbolic
/// name of the enumerated value or a \c TfEnum instance constructed from it.
/// The name defined for the value is created by putting double quotes around
/// the \p VAL argument.
///
/// An optional second argument, \p DISPLAY, is a name to be used for display
/// purposes (i.e. in a user interface). The display name can contain
/// characters like spaces and punctuation, and does not need to be a unique
/// string. If this argument is not specified, the display name will be
/// derived from \p VAL.
///
/// Only the names for which \c TF_ADD_ENUM_NAME() is called will be
/// accessible with the name/value methods; you can hide values from this
/// mechanism by not adding them.
///
/// Please note that the best way to call \c TF_ADD_ENUM_NAME() is using the
/// \c TfRegistryManager macro \c TF_REGISTRY_FUNCTION().
///
/// \ingroup group_tf_RuntimeTyping
/// \hideinitializer
#define TF_ADD_ENUM_NAME(VAL, ...) \
TfEnum::_AddName(VAL, \
TF_PP_STRINGIZE(VAL) \
BOOST_PP_COMMA_IF(TF_NUM_ARGS(__VA_ARGS__)) \
__VA_ARGS__)
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ENUM_H
+193
View File
@@ -0,0 +1,193 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ENV_SETTING_H
#define PXR_BASE_TF_ENV_SETTING_H
/// \file tf/envSetting.h
/// Environment setting variable.
///
/// A \c TfEnvSetting<T> is used to access an environment variable that
/// controls program execution according to the value set in the environment.
/// Currently, the legal types for T are bool, int, and string.
///
/// The TfEnvSetting facility is used to enable new features in the code that
/// are still in "experimental" mode, and warn the user and/or QA that they
/// are pushing the edge of the envelope by setting a non-standard value for
/// these variables. Accordingly, the \c TfEnvSetting construct should be
/// used as sparingly as possible in code.
///
/// In contrast, a variable that allows the user to customize program
/// execution but is not an in-development code path should simply use
/// TfGetenv() to access the variable. An example would be supplying a
/// variable to override a default font or fontsize, for users who don't like
/// the default program choice (and when there is no other way to set the
/// preference).
///
/// Here is how to use the TfEnvSetting facility.
///
/// 1. First, define your variable in a single .cpp file:
///
/// \code
/// #include "pxr/base/tf/envSetting.h"
///
/// TF_DEFINE_ENV_SETTING(TDS_FILE_VERSION, 12,
/// "Default file format to use");
/// \endcode
///
/// The first argument is the name of your variable; it is also the name for
/// the variable you can set in your shell to set the value at runtime. The
/// second argument is the default value. To create a bool variable, pass
/// either true or false. To create a string variable, pass an explicit
/// string(), i.e.
///
/// \code
/// TF_DEFINE_ENV_SETTING(TDS_FILE_SUFFIX, string(".tid"),
/// "Default file-name suffix");
/// \endcode
///
/// 2. If you need to access this variable outside the .cpp file that defines
/// the variable, put the following in a common header file:
///
/// \code
/// extern TfEnvSetting<int> TDS_FILE_VERSION;
/// extern TfEnvSetting<string> TDS_FILE_SUFFIX;
/// \endcode
///
/// 3. At runtime, access your variable using TfGetEnvSetting(). For example:
///
/// \code
/// int version = TfGetEnvSetting(TDS_FILE_VERSION);
/// string const& suffix =TfGetEnvSetting(TDS_FILE_SUFFIX);
/// \endcode
///
/// You can also access a variable's value from Python:
///
/// \code{.py}
/// from pxr import Tf
/// suffix = Tf.GetEnvSetting("TDS_FILE_SUFFIX")
/// \endcode
///
/// \c Tf.GetEnvSetting() returns the value for the TfEnvSetting variable, or
/// None if no such variable is defined in the currently loaded C++ code.
///
/// If a user's environment has a value for a TfEnvSetting variable that
/// differs from the default, when the program starts or the module defining
/// the TfEnvSetting variable is loaded, a warning messages is printed.
///
/// Additionally, at program startup time (or when lib/tf is first loaded),
/// the environment variable PIXAR_TF_ENV_SETTING_FILE is examined. If this
/// variable indicates a file that can be read, then the file is parsed, and
/// should contain lines of the form key=value. For each line read, the
/// environment variable key is set to value. For example:
///
/// \code{.sh}
/// $ setenv PIXAR_TF_ENV_SETTING_FILE /usr/anim/<UNIT>/admin/env-settings
///
/// $ cat /usr/anim/<UNIT>/admin/env-settings
/// TDS_DEF_VERSION=30
/// TDS_BLAH=
/// TDS_LONG_STRING=i am some long string with spaces
/// \endcode
///
/// Blank lines in the file and lines where the first character is '#' are
/// ignored. If the file itself cannot be read, no error is printed; however,
/// if the file is malformed, errors are printed to stderr.
#include "pxr/pxr.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/registryManager.h"
#include <atomic>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
// POD, statically initialized.
//
// We store the atomic_value separately and refer to it via pointer because we
// cannot use aggregate-initialization on a struct holding an atomic, but we
// can value-initialize a single std::atomic.
template <class T>
struct TfEnvSetting
{
std::atomic<T*> *_value;
T _default;
char const * _name;
char const * _description;
};
// Specialize for string, default is stored as char const * (pointing to a
// literal).
template <>
struct TfEnvSetting<std::string>
{
std::atomic<std::string*> *_value;
char const * _default;
char const * _name;
char const * _description;
};
template <class T>
void Tf_InitializeEnvSetting(TfEnvSetting<T> *);
/// Returns the value of the specified env setting, registered using
/// \c TF_DEFINE_ENV_SETTING.
template <class T>
inline T const &
TfGetEnvSetting(TfEnvSetting<T>& setting) {
extern void Tf_InitEnvSettings();
Tf_InitEnvSettings();
T *val = setting._value->load();
if (ARCH_UNLIKELY(!val)) {
Tf_InitializeEnvSetting(&setting);
val = setting._value->load();
}
return *val;
}
// Ensure that we only allow bool, int, and string, and map char * and char
// array to string.
bool Tf_ChooseEnvSettingType(bool);
int Tf_ChooseEnvSettingType(int);
std::string Tf_ChooseEnvSettingType(char const *);
class Tf_EnvSettingRegistry;
/// Define an env setting named \p envVar with default value \p defValue and a
/// descriptive string \p description.
/// \hideinitializer
#define TF_DEFINE_ENV_SETTING(envVar, defValue, description) \
std::atomic< decltype(Tf_ChooseEnvSettingType(defValue))*> \
envVar##_value; \
TfEnvSetting<decltype(Tf_ChooseEnvSettingType(defValue))> envVar = { \
&envVar##_value, defValue, #envVar, description }; \
TF_REGISTRY_FUNCTION_WITH_TAG(Tf_EnvSettingRegistry, envVar) { \
(void)TfGetEnvSetting(envVar); \
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ENV_SETTING_H
+72
View File
@@ -0,0 +1,72 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ERROR_H
#define PXR_BASE_TF_ERROR_H
/// \file tf/error.h
#include "pxr/pxr.h"
#include "pxr/base/tf/diagnosticBase.h"
PXR_NAMESPACE_OPEN_SCOPE
class TfDiagnosticMgr;
/// \class TfError
/// \ingroup group_tf_Diagnostic
///
/// Represents an object that contains error information.
///
/// See \ref page_tf_Diagnostic in the C++ API reference for a detailed
/// description of the error issuing API. For a example of how to post an
/// error, see \c TF_ERROR(), also in the C++ API reference.
///
/// In the Python API, you can raise several different types of errors,
/// including coding errors (Tf.RaiseCodingError), run time errors
/// (Tf.RaiseRuntimeError), fatal errors (Tf.Fatal).
///
class TfError: public TfDiagnosticBase {
public:
/// Return the error code posted.
TfEnum GetErrorCode() const {
return GetDiagnosticCode();
}
/// Return the diagnostic code posted as a string.
const std::string& GetErrorCodeAsString() const {
return GetDiagnosticCodeAsString();
}
private:
TfError(TfEnum errorCode, char const *errCodeString,
TfCallContext const &context, const std::string& commentary,
TfDiagnosticInfo info, bool quiet);
friend class TfDiagnosticMgr;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ERROR_H
+218
View File
@@ -0,0 +1,218 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ERROR_MARK_H
#define PXR_BASE_TF_ERROR_MARK_H
/// \file tf/errorMark.h
#include "pxr/pxr.h"
#include "pxr/base/tf/diagnosticMgr.h"
#include "pxr/base/tf/errorTransport.h"
#include "pxr/base/tf/api.h"
#include <boost/noncopyable.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfErrorMark
/// \ingroup group_tf_TfError
///
/// Class used to record the end of the error-list.
///
/// See \ref page_tf_TfError for a detailed description.
///
/// A \c TfErrorMark is used as follows:
/// \code
/// TfErrorMark m;
///
/// m.SetMark(); // (A)
/// ... ;
/// ... ;
/// // (B)
/// if (!m.IsClean()) {
/// // errors occurred between (A) and (B)
/// }
/// \endcode
///
/// Another common pattern is
/// \code
/// TfErrorMark m;
/// if (TF_HAS_ERRORS(m, expr)) {
/// // handle errors;
/// }
/// \endcode
///
class TfErrorMark : boost::noncopyable
{
public:
typedef TfDiagnosticMgr::ErrorIterator Iterator;
/// Default constructor.
///
/// The default constructor automatically calls \c SetMark() at the point
/// of declaration.
TF_API TfErrorMark();
/// Destroy this ErrorMark.
///
/// If this is the last ErrorMark on this thread of execution and there
/// are pending errors, this will report them via the diagnostic delegate
/// (if one is installed) otherwise by printing to stderr.
TF_API ~TfErrorMark();
/// Record future errors.
///
/// \c SetMark() arranges to record future errors in \c *this.
inline void SetMark() {
_mark = TfDiagnosticMgr::GetInstance()._nextSerial;
}
/// Return true if no new errors were posted in this thread since the last
/// call to \c SetMark(), false otherwise.
///
/// When no threads are issuing errors the cost of this function is an
/// atomic integer read and comparison. Otherwise thread-specific data is
/// accessed to make the determination. Thus, this function is fast when
/// diagnostics are not being issued.
inline bool IsClean() const {
TfDiagnosticMgr &mgr = TfDiagnosticMgr::GetInstance();
return _mark >= mgr._nextSerial || _IsCleanImpl(mgr);
}
/// Remove all errors in this mark from the error system. Return true if
/// any errors were cleared, false if there were no errors in this mark.
///
/// Clear all errors contained in this mark from the error system.
/// Subsequently, these errors will be considered handled.
inline bool Clear() const {
TfDiagnosticMgr &mgr = TfDiagnosticMgr::GetInstance();
auto b = GetBegin(), e = mgr.GetErrorEnd();
if (b != e) {
mgr.EraseRange(b, e);
return true;
}
return false;
}
/// Remove all errors in this mark fom the error system and return them in
/// a TfErrorTransport.
///
/// This can be used to transfer errors from one thread to another. See
/// TfErrorTransport for more information. As with Clear(), all the
/// removed errors are considered handled for this thread. See also
/// TransportTo().
inline TfErrorTransport Transport() const {
TfDiagnosticMgr &mgr = TfDiagnosticMgr::GetInstance();
return TfErrorTransport(mgr._errorList.local(),
GetBegin(), mgr.GetErrorEnd());
}
/// Remove all errors in this mark fom the error system and return them in
/// a TfErrorTransport.
///
/// This is a variant of Transport(). Instead of returning a new
/// TfErrorTransport object it fills an existing one.
inline void TransportTo(TfErrorTransport &dest) const {
Transport().swap(dest);
}
/// Return an iterator to the first error added to the error list after
/// \c SetMark().
///
/// If there are no errors on the error list that were not already present
/// when \c SetMark() was called, the iterator returned is equal to the
/// iterator returned by \c TfDiagnosticMgr::GetErrorEnd(). Otherwise, the
/// iterator points to the earliest error added to the list since
/// \c SetMark() was called.
///
/// This function takes O(n) time where n is the number of errors from the
/// end of the list to the mark i.e. \c GetMark() walks the list from the
/// end until it finds the mark and then returns an iterator to that spot.
///
/// If \c nErrors is non-NULL, then \c *nErrors is set to the number of
/// errors between the returned iterator and the end of the list.
Iterator GetBegin(size_t *nErrors = 0) const {
return
TfDiagnosticMgr::GetInstance()._GetErrorMarkBegin(_mark, nErrors);
}
/// Return an iterator past the last error in the error system.
///
/// This iterator is always equivalent to the iterator returned by \c
/// TfDiagnosticMgr::GetErrorEnd().
Iterator GetEnd() const {
return TfDiagnosticMgr::GetInstance().GetErrorEnd();
}
/// Equivalent to GetBegin()
Iterator begin() const { return GetBegin(); }
/// Equivalent to GetEnd()
Iterator end() const { return GetEnd(); }
private:
friend class TfDiagnosticMgr;
// Helper to check if the _mark identifies any errors present on the
// thread-local error list.
TF_API bool _IsCleanImpl(TfDiagnosticMgr &mgr) const;
void _ReportErrors(TfDiagnosticMgr &mgr) const;
size_t _mark;
};
/// Convenience macro to check if errors occurred.
///
/// This macro is equivalent to
/// \code
/// (marker.SetMark(), (expr), !marker.IsClean())
/// \endcode
///
/// which enables it to be used as an expression:
/// \code
/// if (TF_HAS_ERRORS(m, expr))
/// // cope!
/// \endcode
///
/// \ingroup group_tf_TfError
/// \hideinitializer
#define TF_HAS_ERRORS(marker, expr) \
(marker.SetMark(), (expr), !marker.IsClean())
/// Report current TfErrorMark instances and the stack traces that created
/// them to stdout for debugging purposes.
///
/// To call this function, set _enableTfErrorMarkStackTraces in errorMark.cpp
/// and enable the TF_ERROR_MARK_TRACKING TfDebug code.
///
/// \ingroup group_tf_TfError
TF_API
void TfReportActiveErrorMarks();
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ERROR_MARK_H
+95
View File
@@ -0,0 +1,95 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ERROR_TRANSPORT_H
#define PXR_BASE_TF_ERROR_TRANSPORT_H
/// \file tf/errorTransport.h
#include "pxr/pxr.h"
#include "pxr/base/tf/diagnosticMgr.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/api.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfErrorTransport
///
/// A facility for transporting errors from thread to thread.
///
/// Typical use is to create a TfErrorMark in the thread that is the error
/// source (e.g. the child thread), then call TfErrorMark::Transport() or
/// TfErrorMark::TransportTo() to lift generated errors out into a
/// TfErrorTransport object. Later the thread that wants to sink those errors
/// (e.g. the parent thread) invokes TfErrorTransport::Post() to post all
/// contained errors to its own thread's error list.
class TfErrorTransport
{
public:
typedef TfDiagnosticMgr::ErrorList ErrorList;
/// Construct an empty TfErrorTransport.
TfErrorTransport() {}
/// Post all contained errors to the current thread's error list, leaving
/// this TfErrorTransport empty.
void Post() {
if (ARCH_UNLIKELY(!IsEmpty()))
_PostImpl();
}
/// Return true if this TfErrorTransport contains no errors, false
/// otherwise.
bool IsEmpty() const { return _errorList.empty(); }
/// Swap this TfErrorTransport's content with \p other. This provides a
/// lightweight way to move the contents of one TfErrorTransport to
/// another.
void swap(TfErrorTransport &other) {
_errorList.swap(other._errorList);
}
private:
friend class TfErrorMark;
TfErrorTransport(ErrorList &src,
ErrorList::iterator first,
ErrorList::iterator last) {
_errorList.splice(_errorList.begin(), src, first, last);
}
TF_API
void _PostImpl();
ErrorList _errorList;
};
inline void
swap(TfErrorTransport &l, TfErrorTransport &r)
{
l.swap(r);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ERROR_TRANSPORT_H
+155
View File
@@ -0,0 +1,155 @@
//
// Copyright 2021 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_EXCEPTION_H
#define PXR_BASE_TF_EXCEPTION_H
/// \file tf/exception.h
/// \ingroup group_tf_Diagnostic
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/callContext.h"
#include "pxr/base/tf/functionRef.h"
#include <cstdint>
#include <exception>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// This structure is used to indicate that some number of caller frames should
/// be skipped when capturing exception stack traces at the throw point.
struct TfSkipCallerFrames
{
explicit TfSkipCallerFrames(int n=0) : numToSkip(n) {}
int numToSkip;
};
/// The base class for exceptions supported by the Tf exceptions facilities.
/// Typical usage is to publically derive your own exception class from this
/// one, and throw using the TF_THROW() macro.
///
/// Deriving this base class and throwing via TF_THROW() will record the throw
/// point's call context (see GetThrowContext()) and will also capture a portion
/// of the throwing thread's call stack (see GetThrowStack()).
///
/// Additionally, the Tf library registers an exception translator with
/// boost.python to raise a Python exeption wrapping the thrown exception
/// object. Similarly utilties that call Python via Tf will re-throw the
/// embedded C++ exception if the Python exception unwinds back into C++.
class TfBaseException : public std::exception
{
public:
TF_API
virtual ~TfBaseException();
/// Construct with \p message, reported by this class's what()
/// implementation.
TF_API
explicit TfBaseException(std::string const &message);
/// Return the call context from the throw point associated with this
/// exception. Note that this context may be invalid if this exception was
/// not thrown with TF_THROW().
TfCallContext const &GetThrowContext() const {
return _callContext;
}
/// Return the stack frame pointers from the throw point. See
/// ArchPrintStackFrames() to turn these into human-readable strings.
std::vector<uintptr_t> const &GetThrowStack() const {
return _throwStack;
}
/// Move the stack frame pointers from the throw point to \p out. See
/// GetThrowStack() for more details.
void MoveThrowStackTo(std::vector<uintptr_t> &out) {
out = std::move(_throwStack);
_throwStack.clear();
}
/// Override std::exception::what() to return the message passed during
/// construction.
TF_API
virtual const char *what() const noexcept override;
// Friend throw support.
template <class Derived, class ... Args>
friend void
Tf_Throw(TfCallContext const &cc,
TfSkipCallerFrames skipFrames,
Args && ... args);
private:
TF_API
static void _ThrowImpl(TfCallContext const &cc,
TfBaseException &exc,
TfFunctionRef<void ()> thrower,
int skipNCallerFrames);
TfCallContext _callContext;
std::vector<uintptr_t> _throwStack;
std::string _message;
};
// TF_THROW() support function.
template <class Exception, class ... Args>
void
Tf_Throw(TfCallContext const &cc,
TfSkipCallerFrames skipFrames,
Args && ... args) {
Exception exc(std::forward<Args>(args)...);
auto thrower = [&exc]() { throw std::move(exc); };
TfBaseException::_ThrowImpl(cc, exc, thrower, skipFrames.numToSkip);
}
// TF_THROW() support function.
template <class Exception, class ... Args>
void Tf_Throw(TfCallContext const &cc, Args && ... args) {
Tf_Throw<Exception>(cc, TfSkipCallerFrames(), std::forward<Args>(args)...);
}
#ifdef doxygen
/// Construct an instance of Exception (which must derive TfBaseException) with
/// Exception-ctor-args and throw it. Also capture a portion of this thread's
/// current call stack and the throw point's source filename & line number to
/// embed in the exception. If the exception goes unhandled these will be
/// reported in the crash report that Tf's terminate handler generates, or in
/// the unhandled exception message in the python interpreter.
#define TF_THROW(Exception, Exception-ctor-args...)
#define TF_THROW(Exception, TfSkipCallerFrames, Exception-ctor-args...)
#else
#define TF_THROW(Exception, ...) \
Tf_Throw<Exception>(TF_CALL_CONTEXT, __VA_ARGS__)
#endif
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_EXCEPTION_H
+71
View File
@@ -0,0 +1,71 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_EXPIRY_NOTIFIER_H
#define PXR_BASE_TF_EXPIRY_NOTIFIER_H
/// \file tf/expiryNotifier.h
#include "pxr/pxr.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/api.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class Tf_ExpiryNotifier
///
/// Set the extra notifier function.
///
/// Objects derived from \c TfWeakBase can request that extra notification be
/// performed when they expire. Objects that do not request extra
/// notification do not suffer any performance penalty when they expire, while
/// objects that request the notification will have the extra notifier
/// function run on them, with the address returned by \c
/// TfWeakPtr::GetUniqueIdentifier() passed to the notifier function.
///
/// An object requests extra notification be performed by calling \c
/// wp.RequestExtraNotification() where \c wp is a \c TfWeakPtr pointing to
/// the object in question.
///
/// This functions sets the extra notifier function to \p func. At present,
/// this notifier is intended to be used only by the scripting system to
/// inform the system that a particular object has expired and scripting
/// resources devoted to that object can be discarded. Accordingly, if
/// \p func is non-NULL and a previous non-NULL notifier function has been
/// set, a fatal error is issued.
class Tf_ExpiryNotifier {
public:
TF_API static void Invoke(void const *p);
TF_API static void SetNotifier(void (*func)(void const *));
TF_API static void Invoke2(void const *p);
TF_API static void SetNotifier2(void (*func)(void const *));
private:
static void (*_func)(void const *);
static void (*_func2)(void const *);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+73
View File
@@ -0,0 +1,73 @@
//`
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
#ifndef PXR_BASE_TF_FAST_COMPRESSION_H
#define PXR_BASE_TF_FAST_COMPRESSION_H
/// \file tf/fastCompression.h
/// Simple fast data compression/decompression routines.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <cstddef>
PXR_NAMESPACE_OPEN_SCOPE
class TfFastCompression
{
public:
/// Return the largest input buffer size that can be compressed with these
/// functions. Guaranteed to be at least 200 GB.
TF_API static size_t
GetMaxInputSize();
/// Return the largest possible compressed size for the given \p inputSize
/// in the worst case (input is not compressible). This is larger than
/// \p inputSize. If inputSize is larger than GetMaxInputSize(), return 0.
TF_API static size_t
GetCompressedBufferSize(size_t inputSize);
/// Compress \p inputSize bytes in \p input and store the result in
/// \p compressed. The \p compressed buffer must point to at least
/// GetCompressedBufferSize(uncompressedSize) bytes. Return the number of
/// bytes written to the \p compressed buffer. Issue a runtime error and
/// return ~0 in case of an error.
TF_API static size_t
CompressToBuffer(char const *input, char *compressed, size_t inputSize);
/// Decompress \p compressedSize bytes in \p compressed and store the
/// result in \p output. No more than \p maxOutputSize bytes will be
/// written to \p output.
TF_API static size_t
DecompressFromBuffer(char const *compressed, char *output,
size_t compressedSize, size_t maxOutputSize);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_FAST_COMPRESSION_H
+236
View File
@@ -0,0 +1,236 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_FILE_UTILS_H
#define PXR_BASE_TF_FILE_UTILS_H
/// \file tf/fileUtils.h
/// \ingroup group_tf_File
/// Definitions of basic file utilities in tf.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <string>
#include <vector>
#include <functional>
PXR_NAMESPACE_OPEN_SCOPE
/// Returns true if the path exists.
///
/// If \p resolveSymlinks is false (default), the path is checked using
/// lstat(). if \p resolveSymlinks is true, the path is checked using stat(),
/// which resolves all symbolic links in the path.
TF_API
bool TfPathExists(std::string const& path, bool resolveSymlinks = false);
/// Returns true if the path exists and is a directory.
///
/// If \p resolveSymlinks is false (default), the path is checked using
/// lstat(). if \p resolveSymlinks is true, the path is checked using stat(),
/// which resolves all symbolic links in the path.
TF_API
bool TfIsDir(std::string const& path, bool resolveSymlinks = false);
/// Returns true if the path exists and is a file.
///
/// If \p resolveSymlinks is false (default), the path is checked using
/// lstat(). if \p resolveSymlinks is true, the path is checked using stat(),
/// which resolves all symbolic links in the path.
TF_API
bool TfIsFile(std::string const& path, bool resolveSymlinks = false);
/// Returns true if the path exists and is a symbolic link.
TF_API
bool TfIsLink(std::string const& path);
/// Returns true if the file or directory at \p path is writable.
///
/// For this function to return true, the file must exist and be writable by
/// the effective user, effective group, or all users. This function
/// dereferences symbolic links, returning whether or not the resolved file or
/// directory path is writable. If the file or directory does not exist, this
/// function returns false.
TF_API
bool TfIsWritable(std::string const& path);
/// Returns true if the path is an empty directory.
TF_API
bool TfIsDirEmpty(std::string const& path);
/// Creates a symbolic link from \p src to \p dst.
TF_API
bool TfSymlink(std::string const& src, std::string const& dst);
/// Deletes a file at path.
TF_API
bool TfDeleteFile(std::string const& path);
/// Creates a directory.
///
/// If the directory cannot be created, this function returns false. If no
/// mode is specified, the default mode is 0777. If the specified path already
/// exists, or an error occurs while creating the directory, this method
/// returns false.
TF_API
bool TfMakeDir(std::string const& path, int mode=-1);
/// Creates a directory hierarchy.
///
/// If any element of the path cannot be created, this function will return
/// false. The specified mode will be used to create all new directories. If
/// no mode is specified, the default mode of \c TfMakeDir is used. If the
/// target directory exists, this function returns false if \p existOk is
/// false.
TF_API
bool TfMakeDirs(std::string const& path, int mode=-1, bool existOk=false);
/// Function type for TfWalkDirs.
///
/// This function is called once for each directory visited by TfWalkDirs.
/// The first parameter is the directory path; if the topmost directory passed
/// to TfWalkDirs is relative, this path will also be relative. The second
/// parameter is a vector of subdirectory names, relative to the directory
/// path. This parameter is a pointer, allowing the subdirectory list to be
/// modified, thus controlling which directories are visited. Note that
/// modifying the subdirectory vector has no effect when TfWalkDirs is called
/// with \c topDown set to \c false. The final parameter is a vector of file
/// names found in the directory path. The returned value determines whether
/// the walk should be terminated (\c false), or continue (\c true).
typedef std::function<bool (std::string const&,
std::vector<std::string> *,
std::vector<std::string> const&)> TfWalkFunction;
/// TfRmTree error handler function.
///
/// The first parameter is the path which caused the error (file or directory),
/// and the second parameter is an error message indicating why the error
/// occurred.
typedef std::function<void (std::string const&,
std::string const&)> TfWalkErrorHandler;
/// error handler to use when you want to ignore errors
///
/// When calling TfWalkDirs/ChmodTree/RmTree and you want to ignore errors,
/// you can pass in this public error handler which will ignore all the
/// errors.
TF_API
void TfWalkIgnoreErrorHandler(std::string const& path, std::string const& msg);
/// Directory tree walker.
///
/// This function attempts to be as compatible as possible with Python's
/// os.walk() function.
///
/// For each directory in the tree rooted at \p top (including \p top itself,
/// but excluding '.' and '..'), the std::function \p fn is called with
/// three arguments: \c dirpath, \c dirnames, and \c filenames.
///
/// \c dirpath is a string, the path to the directory. \c dirnames is a list
/// of the names of the subdirectories in \c dirpath (excluding '.' and '..').
/// \c filenames is a list of the names of the non-directory files in
/// \c dirpath. Note that the names in the sets are just names, with no path
/// components. To get a full path (which begins with \p top) to a file or
/// directory in \c dirpath, use \c TfStringCatPaths(dirpath, name).
///
/// If optional argument \p topDown is true, or not specified, \p fn is called
/// for a directory before any subdirectories. If topdown is false, \p fn is
/// called for a directory after all subdirectories. Additionally, when
/// \p topDown is true, the walk function can modify the \c dirnames set in
/// place. This can be used to prune the search, or to impose a specific
/// visitation order. Modifying \c dirnames when \p topDown is false has no
/// effect, since the directories in \c dirnames have already been visited
/// by the time they are passed to \p fn.
///
/// The value returned by the error handler function \p onError determines what
/// further action will be taken if an error is encountered. If \c true is
/// returned, the walk will continue; if \c false, the walk will not continue.
///
/// If \p followLinks is false, symbolic links to directories encountered
/// during the walk are passed to the walk function in the \c filenames vector.
/// If \p followLinks is true, symbolic links to directories are passed to the
/// walk function in the \p dirnames vector, and the walk will recurse into
/// these directories.
///
/// If \p top is a symbolic link to a directory, it is followed regardless of
/// the value of \p followLinks. Calling TfWalkDirs with a file argument
/// returns immediately without calling \p fn.
TF_API
void TfWalkDirs(std::string const& top,
TfWalkFunction fn,
bool topDown=true,
TfWalkErrorHandler onError = 0,
bool followLinks = false);
/// Recursively delete a directory tree rooted at \p path.
///
/// Tf runtime errors are raised if any errors are encountered while deleting
/// the specified \p path. Pass in TfWalkIgnoreErrorHandler() to ignore errors.
/// Alternately, sending in a custom TfWalkErrorHandler will
/// call this handler when errors occur. This handler receives the path which
/// caused the error, and a message indicating why the error occurred.
TF_API
void TfRmTree(std::string const& path,
TfWalkErrorHandler onError = 0);
/// Return a list containing files and directories in \p path.
///
/// A trailing path separator character is appended to directories returned
/// in the listing. If \p recursive is true, the directory listing will
/// include all subdirectory structure of \p path.
TF_API
std::vector<std::string> TfListDir(std::string const& path,
bool recursive = false);
/// Read the contents of \p dirPath and append the names of the contained
/// directories, files, and symlinks to \p dirnames, \p filenames, and
/// \p symlinknames, respectively.
///
/// Return true if \p dirPath 's contents were read successfully. Otherwise
/// return false and set \p errMsg with a description of the error if \p errMsg
/// is not NULL.
///
/// It is safe to pass NULL for any of \p dirnames, \p filenames, and
/// \p symlinknames. In that case those elements are not reported
TF_API
bool
TfReadDir(std::string const &dirPath,
std::vector<std::string> *dirnames,
std::vector<std::string> *filenames,
std::vector<std::string> *symlinknames,
std::string *errMsg = NULL);
/// Touch \p fileName, updating access and modification time to 'now'.
///
/// A simple touch-like functionality. Simple in a sense that it does not
/// offer as many options as the same-name unix touch command, but otherwise
/// is identical to the default touch behavior. If \p create is true, an empty
/// file gets created, otherwise the touch call fails if the file does not
/// already exist.
TF_API
bool TfTouchFile(std::string const &fileName, bool create=true);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_FILE_UTILS_H
+159
View File
@@ -0,0 +1,159 @@
//
// Copyright 2020 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_FUNCTION_REF_H
#define PXR_BASE_TF_FUNCTION_REF_H
#include "pxr/pxr.h"
#include <memory>
#include <type_traits>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
template <class Sig>
class TfFunctionRef;
/// \class TfFunctionRef
///
/// This class provides a non-owning reference to a type-erased callable object
/// with a specified signature. This is useful in cases where you want to write
/// a function that takes a user-provided callback, and that callback is used
/// only in the duration of the function call, and you want to keep your
/// function's implementation out-of-line.
///
/// For technical reasons, TfFunctionRef does not support function pointers;
/// only function objects. Internally TfFunctionRef stores a void pointer to
/// the function object it's referencing, but C++ does not allow function
/// pointers to be cast to void pointers. Supporting this case would increase
/// this class's size and add complexity to its implementation. Instead,
/// callers may wrap function pointers in lambdas to sidestep the issue.
///
/// The advantage over std::function is that TfFunctionRef is lighter-weight.
/// Since it is non-owning, it guarantees no heap allocation; a possibility with
/// std::function. The cost to call a TfFunctionRef is an indirect function
/// call.
///
/// For example:
///
/// \code
///
/// // widgetUtil.h ////////////////////////////////
///
/// class WidgetUtil
/// {
/// template <class WidgetPredicate>
/// bool AnyWidgetsMatch(WidgetPredicate const &predicate) {
/// TfFunctionRef<bool (Widget const &)> predRef(predicate);
/// return _AnyWidgetsMatchImpl(predRef);
/// }
/// private:
/// bool _AnyWidgetsMatchImpl(
/// TfFunctionRef<bool (Widget const &)> const &pred);
/// };
///
/// // widgetUtil.cpp //////////////////////////////
///
/// #include "widgetUtil.h"
///
/// bool WidgetUtil::_AnyWidgetsMatchImpl(
/// TfFunctionRef<bool (Widget const &)> const &pred)
/// {
/// for (Widget const &widget: GetAllTheWidgets()) {
/// if (pred(widget)) {
/// return true;
/// }
/// }
/// return false;
/// }
///
/// \endcode
///
/// Here the implementation of _AnyWidgetsMatchImpl is kept out-of-line, callers
/// can pass their own function objects for the predicate, there is no heap
/// allocation, and the cost to invoke the predicate in the implementation is
/// just the cost of calling a function pointer.
///
template <class Ret, class... Args>
class TfFunctionRef<Ret (Args...)>
{
public:
/// Construct with an lvalue callable \p fn.
template <class Fn>
constexpr TfFunctionRef(Fn &fn) noexcept
: _fn(static_cast<void const *>(std::addressof(fn)))
, _invoke(_InvokeFn<Fn>) {}
/// Copy construct from another TfFunctionRef. The constructed
/// TfFunctionRef refers to the same callable as \p rhs.
TfFunctionRef(TfFunctionRef const &rhs) noexcept = default;
/// Assign from another TfFunctionRef. After assignment this object refers
/// to the same callable as \p rhs.
TfFunctionRef &
operator=(TfFunctionRef const &rhs) noexcept = default;
/// Assign from an lvalue callable \p fn.
template <class Fn>
TfFunctionRef &
operator=(Fn &fn) noexcept {
*this = TfFunctionRef(fn);
return *this;
}
/// Swap this and \p other. After the swap, this refers to \p other's
/// previous callable, and \p other refers to this's previous callable.
void swap(TfFunctionRef &other) noexcept {
std::swap(_fn, other._fn);
std::swap(_invoke, other._invoke);
}
/// Invoke the callable that this object refers to with \p args.
inline Ret operator()(Args... args) const {
return _invoke(_fn, std::forward<Args>(args)...);
}
private:
template <class Fn>
static Ret _InvokeFn(void const *fn, Args...args) {
using FnPtr = typename std::add_pointer<
typename std::add_const<Fn>::type>::type;
return (*static_cast<FnPtr>(fn))(std::forward<Args>(args)...);
}
void const *_fn;
Ret (*_invoke)(void const *, Args...);
};
/// Swap \p lhs and \p rhs. Equivalent to lhs.swap(rhs).
template <class Sig>
inline void
swap(TfFunctionRef<Sig> &lhs, TfFunctionRef<Sig> &rhs)
{
lhs.swap(rhs);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_FUNCTION_REF_H
+85
View File
@@ -0,0 +1,85 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_GETENV_H
#define PXR_BASE_TF_GETENV_H
/// \file tf/getenv.h
/// \ingroup group_tf_SystemsExt
/// Functions for accessing environment variables.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \addtogroup group_tf_SystemsExt
///@{
/// Return an environment variable as a string.
///
/// Return the value of the environment variable \c envName
/// as a string. If the variable is unset, or is the empty string,
/// then \c defaultValue is returned.
TF_API
std::string TfGetenv(const std::string& envName,
const std::string& defaultValue = "");
/// Return an environment variable as an integer.
///
/// Return the value of the environment variable \c envName as an integer. If
/// the variable is unset, or is the empty string, then \c defaultValue is
/// returned. Otherwise, the function uses atoi() to convert the string to an
/// integer: the implication being that if the string is not a valid integer,
/// you get back whatever value atoi() comes up with.
TF_API
int TfGetenvInt(const std::string& envName, int defaultValue);
/// Return an environment variable as a boolean.
///
/// Return the value of the environment variable \c envName as a boolean. If
/// the variable is unset, or is the empty string, then \c defaultValue is
/// returned. A value of \c true is returned if the environment variable is
/// any of "true", "yes", "on" or "1"; the match is not case sensitive. All
/// other values yield a return value of \c false.
TF_API
bool TfGetenvBool(const std::string&, bool defaultValue);
/// Return an environment variable as a double.
///
/// Return the value of the environment variable \c envName as a double. If
/// the variable is unset, or is the empty string, then \c defaultValue is
/// returned. Otherwise, the function uses TfStringToDouble() to convert the
/// string to a double: the implication being that if the string is not a
/// valid double, you get back whatever value TfStringToDouble() comes up
/// with.
TF_API
double TfGetenvDouble(const std::string& envName, double defaultValue);
///@}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+498
View File
@@ -0,0 +1,498 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_HASH_H
#define PXR_BASE_TF_HASH_H
/// \file tf/hash.h
/// \ingroup group_tf_String
#include "pxr/pxr.h"
#include "pxr/base/tf/tf.h"
#include "pxr/base/tf/api.h"
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
// Support integers.
template <class HashState, class T>
std::enable_if_t<std::is_integral<T>::value>
TfHashAppend(HashState &h, T integral)
{
h.Append(integral);
}
// Simple metafunction that returns an unsigned integral type given a size in
// bytes.
template <size_t Size> struct Tf_SizedUnsignedInt;
template <> struct Tf_SizedUnsignedInt<1> { using type = uint8_t; };
template <> struct Tf_SizedUnsignedInt<2> { using type = uint16_t; };
template <> struct Tf_SizedUnsignedInt<4> { using type = uint32_t; };
template <> struct Tf_SizedUnsignedInt<8> { using type = uint64_t; };
// Support enums.
template <class HashState, class Enum>
std::enable_if_t<std::is_enum<Enum>::value>
TfHashAppend(HashState &h, Enum e)
{
h.Append(static_cast<std::underlying_type_t<Enum>>(e));
}
// Support floating point.
template <class HashState, class T>
std::enable_if_t<std::is_floating_point<T>::value>
TfHashAppend(HashState &h, T fp)
{
// We want both positive and negative zero to hash the same, so we have to
// check against zero here.
typename Tf_SizedUnsignedInt<sizeof(T)>::type intbuf = 0;
if (fp != static_cast<T>(0)) {
memcpy(&intbuf, &fp, sizeof(T));
}
h.Append(intbuf);
}
// Support std::pair.
template <class HashState, class T, class U>
inline void
TfHashAppend(HashState &h, std::pair<T, U> const &p)
{
h.Append(p.first);
h.Append(p.second);
}
// Support std::vector.
template <class HashState, class T>
inline void
TfHashAppend(HashState &h, std::vector<T> const &vec)
{
h.AppendContiguous(vec.data(), vec.size());
}
// Support for hashing std::string.
template <class HashState>
inline void
TfHashAppend(HashState &h, const std::string& s)
{
return h.AppendContiguous(s.c_str(), s.length());
}
// Support for hashing pointers, but we explicitly delete the version for
// [const] char pointers. See more below.
template <class HashState, class T>
inline void
TfHashAppend(HashState &h, const T* ptr) {
return h.Append(reinterpret_cast<uintptr_t>(ptr));
}
// We refuse to hash [const] char *. You're almost certainly trying to hash the
// pointed-to string and this will not do that (it will hash the pointer
// itself). To hash a c-style null terminated string, you can use
// TfHashAsCStr() to indicate the intent, or use TfHashCString. If you
// really want to hash the pointer then use static_cast<const void*>(ptr) or
// TfHashCharPtr.
template <class HashState>
inline void TfHashAppend(HashState &h, char const *ptr) = delete;
template <class HashState>
inline void TfHashAppend(HashState &h, char *ptr) = delete;
/// A structure that wraps a char pointer, indicating intent that it should be
/// hashed as a c-style null terminated string. See TfhashAsCStr().
struct TfCStrHashWrapper
{
explicit TfCStrHashWrapper(char const *cstr) : cstr(cstr) {}
char const *cstr;
};
/// Indicate that a char pointer is intended to be hashed as a C-style null
/// terminated string. Use this to wrap a char pointer in a HashState::Append()
/// call when implementing a TfHashAppend overload.
///
/// This structure provides a lightweight view on the char pointer passed to its
/// constructor. It does not copy the data or participate in its lifetime. The
/// passed char pointer must remain valid as long as this struct is used.
inline TfCStrHashWrapper
TfHashAsCStr(char const *cstr)
{
return TfCStrHashWrapper(cstr);
}
template <class HashState>
inline void TfHashAppend(HashState &h, TfCStrHashWrapper hcstr)
{
return h.AppendContiguous(hcstr.cstr, std::strlen(hcstr.cstr));
}
// Implementation detail: dispatch based on hash capability: Try TfHashAppend
// first, otherwise try hash_value. We'd like to otherwise try std::hash<T>,
// but std::hash<> is not SFINAE-friendly until c++17 and this code needs to
// support c++14 currently. We rely on a combination of expression SFINAE and
// establishing preferred order by passing a 0 constant and having the overloads
// take int (highest priority), long (next priority) and '...' (lowest
// priority).
// std::hash version, attempted last. Consider adding when we move to
// C++17 or newer.
/*
template <class HashState, class T>
inline auto Tf_HashImpl(HashState &h, T &&obj, ...)
-> decltype(std::hash<typename std::decay<T>::type>()(
std::forward<T>(obj)), void())
{
TfHashAppend(
h, std::hash<typename std::decay<T>::type>()(std::forward<T>(obj)));
}
*/
// hash_value, attempted second.
template <class HashState, class T>
inline auto Tf_HashImpl(HashState &h, T &&obj, long)
-> decltype(hash_value(std::forward<T>(obj)), void())
{
TfHashAppend(h, hash_value(std::forward<T>(obj)));
}
// TfHashAppend, attempted first.
template <class HashState, class T>
inline auto Tf_HashImpl(HashState &h, T &&obj, int)
-> decltype(TfHashAppend(h, std::forward<T>(obj)), void())
{
TfHashAppend(h, std::forward<T>(obj));
}
// Implementation detail, CRTP base that provides the public interface for hash
// state implementations.
template <class Derived>
class Tf_HashStateAPI
{
public:
// Append several objects to the hash state.
template <class... Args>
void Append(Args &&... args) {
_AppendImpl(args...);
}
// Append contiguous objects to the hash state.
template <class T>
void AppendContiguous(T const *elems, size_t numElems) {
this->_AsDerived()._AppendContiguous(elems, numElems);
}
// Append a range of objects to the hash state.
template <class Iter>
void AppendRange(Iter f, Iter l) {
this->_AsDerived()._AppendRange(f, l);
}
// Return the hash code for the current state.
size_t GetCode() const {
return this->_AsDerived()._GetCode();
}
private:
template <class T, class... Args>
void _AppendImpl(T &&obj, Args &&... rest) {
this->_AsDerived()._Append(std::forward<T>(obj));
_AppendImpl(rest...);
}
void _AppendImpl() const {
// base case intentionally empty.
}
Derived &_AsDerived() {
return *static_cast<Derived *>(this);
}
Derived const &_AsDerived() const {
return *static_cast<Derived const *>(this);
}
};
// Implementation detail, accumulates hashes.
class Tf_HashState : public Tf_HashStateAPI<Tf_HashState>
{
private:
friend class Tf_HashStateAPI<Tf_HashState>;
// Go thru Tf_HashImpl for non-integers.
template <class T>
std::enable_if_t<!std::is_integral<std::decay_t<T>>::value>
_Append(T &&obj) {
Tf_HashImpl(*this, std::forward<T>(obj), 0);
}
// Integers bottom out here.
template <class T>
std::enable_if_t<std::is_integral<T>::value>
_Append(T i) {
if (!_didOne) {
_state = i;
_didOne = true;
}
else {
_state = _Combine(_state, i);
}
}
// Append contiguous objects.
template <class T>
std::enable_if_t<std::is_integral<T>::value>
_AppendContiguous(T const *elems, size_t numElems) {
_AppendBytes(reinterpret_cast<char const *>(elems),
numElems * sizeof(T));
}
// Append contiguous objects.
template <class T>
std::enable_if_t<!std::is_integral<T>::value>
_AppendContiguous(T const *elems, size_t numElems) {
while (numElems--) {
Append(*elems++);
}
}
// Append a range.
template <class Iter>
void _AppendRange(Iter f, Iter l) {
while (f != l) {
_Append(*f++);
}
}
/// Append a number of bytes to the hash state.
TF_API void _AppendBytes(char const *bytes, size_t numBytes);
// Return the hash code for the accumulated hash state.
size_t _GetCode() const {
// This is based on Knuth's multiplicative hash for integers. The
// constant is the closest prime to the binary expansion of the inverse
// golden ratio. The best way to produce a hash table bucket index from
// the result is to shift the result right, since the higher order bits
// have the most entropy. But since we can't know the number of buckets
// in a table that's using this, we just reverse the byte order instead,
// to get the highest entropy bits into the low-order bytes.
return _SwapByteOrder(_state * 11400714819323198549ULL);
}
// This turns into a single bswap/pshufb type instruction on most compilers.
inline uint64_t
_SwapByteOrder(uint64_t val) const {
val =
((val & 0xFF00000000000000u) >> 56u) |
((val & 0x00FF000000000000u) >> 40u) |
((val & 0x0000FF0000000000u) >> 24u) |
((val & 0x000000FF00000000u) >> 8u) |
((val & 0x00000000FF000000u) << 8u) |
((val & 0x0000000000FF0000u) << 24u) |
((val & 0x000000000000FF00u) << 40u) |
((val & 0x00000000000000FFu) << 56u);
return val;
}
size_t _Combine(size_t x, size_t y) const {
// This is our hash combiner. The task is, given two hash codes x and
// y, compute a single hash code. One way to do this is to exclusive-or
// the two codes together, but this can produce bad results if they
// differ by some fixed amount, For example if the input codes are
// multiples of 32, and the two codes we're given are N and N + 32 (this
// happens commonly when the hashed values are memory addresses) then
// the resulting hash codes for successive pairs of these produces many
// repeating values (32, 96, 32, XXX, 32, 96, 32, YYY...). That's a lot
// of collisions.
//
// Instead we combine hash values by assigning numbers to the lattice
// points in the plane, and then treating the inputs x and y as
// coordinates identifying a lattice point. Then the combined hash
// value is just the number assigned to the lattice point. This way
// each unique input pair (x, y) gets a unique output hash code.
//
// We number lattice points by triangular numbers like this:
//
// X 0 1 2 3 4 5
// Y
// 0 0 2 5 9 14 20
// 1 1 4 8 13 19 26
// 2 3 7 12 18 25 33
// 3 6 11 17 24 32 41
// 4 10 16 23 31 40 50
// 5 15 22 30 39 49 60
//
// This takes a couple of additions and a multiplication, which is a bit
// more expensive than something like an exclusive or, but the quality
// improvement outweighs the added expense.
x += y;
return y + x * (x + 1) / 2;
}
size_t _state = 0;
bool _didOne = false;
};
/// \class TfHash
/// \ingroup group_tf_String
///
/// A user-extensible hashing mechanism for use with runtime hash tables.
///
/// The hash functions here are appropriate for storing objects in runtime hash
/// tables. They are not appropriate for document signatures / fingerprinting
/// or for storage and offline use. No specific guarantee is made about hash
/// function quality, and the resulting hash codes are only 64-bits wide.
/// Callers must assume that collisions will occur and be prepared to deal with
/// them.
///
/// Additionally, no guarantee is made about repeatability from run-to-run.
/// That is, within a process lifetime an object's hash code will not change
/// (provided its internal state does not change). But an object with
/// equivalent state in a future run of the same process may hash differently.
///
/// At the time of this writing we observe good performance combined with the
/// "avalanche" quality (~50% output bit flip probability for a single input bit
/// flip) in the low-order 40 output bits. Higher order bits do not achieve
/// avalanche, and the highest order 8 bits are particularly poor. But for our
/// purposes we deem this performance/quality tradeoff acceptable.
///
/// This mechanism has builtin support for integral and floating point types,
/// some STL types and types in Tf. TfHash uses three methods to attempt to
/// hash a passed object. First, TfHash tries to call TfHashAppend() on its
/// argument. This is the primary customization point for TfHash. If that is
/// not viable, TfHash makes an unqualified call to hash_value(). We would like
/// TfHash to try to use std::hash<T> next, but std::hash<T> is not
/// SFINAE-friendly until c++17, and this code needs to support c++14.
///
/// The best way to add TfHash support for user-defined types is to provide a
/// function overload like the following.
///
/// \code
/// template <class HashState>
/// void TfHashAppend(HashState &h, MyType const &myObj)
/// h.Append(myObject._member1,
/// myObject._member2,
/// myObject._member3);
/// h.AppendContiguous(myObject._memberArray, myObject._numArrayElems);
/// }
/// \endcode
///
/// The HashState object is left deliberately unspecified, so that different
/// hash state objects may be used in different circumstances without modifying
/// this support code, and without excess abstraction penalty. The methods
/// available for use in TfHashAppend overloads are:
///
/// \code
/// // Append several objects to the hash state. This invokes the TfHash
/// // mechanism so it works for any types supported by TfHash.
/// template <class... Args>
/// void HashState::Append(Args &&... args);
///
/// // Append contiguous objects to the hash state. Note that this is
/// // explicitly *not* guaranteed to produce the same result as calling
/// // Append() with each object in order.
/// template <class T>
/// void HashState::AppendContiguous(T const *objects, size_t numObjects);
///
/// // Append a general range of objects to the hash state. Note that this is
/// // explicitly *not* guaranteed to produce the same result as calling
/// // Append() with each object in order.
/// template <class Iter>
/// void AppendRange(Iter f, Iter l);
/// \endcode
///
/// The \c TfHash class function object supports:
/// \li integral types (including bool)
/// \li floating point types
/// \li std::string
/// \li TfRefPtr
/// \li TfWeakPtr
/// \li TfEnum
/// \li const void*
/// \li types that provide overloads for TfHashAppend
/// \li types that provide overloads for hash_value
///
/// The \c TfHash class can be used to instantiate a \c TfHashMap with \c string
/// keys as follows:
/// \code
/// TfHashMap<string, int, TfHash> m;
/// m["abc"] = 1;
/// \endcode
///
/// \c TfHash()(const char*) is disallowed to avoid confusion of whether
/// the pointer or the string is being hashed. If you want to hash a
/// C-string use \c TfHashCString and if you want to hash a \c char* use
/// \c TfHashCharPtr.
///
class TfHash {
public:
/// Produce a hash code for \p obj. See the class documentation for
/// details.
template <class T>
auto operator()(T &&obj) const ->
decltype(Tf_HashImpl(std::declval<Tf_HashState &>(),
std::forward<T>(obj), 0), size_t()) {
Tf_HashState h;
Tf_HashImpl(h, std::forward<T>(obj), 0);
return h.GetCode();
}
/// Produce a hash code by combining the hash codes of several objects.
template <class... Args>
static size_t Combine(Args &&... args) {
Tf_HashState h;
_CombineImpl(h, args...);
return h.GetCode();
}
private:
template <class HashState, class T, class... Args>
static void _CombineImpl(HashState &h, T &&obj, Args &&... rest) {
Tf_HashImpl(h, std::forward<T>(obj), 0);
_CombineImpl(h, rest...);
}
template <class HashState>
static void _CombineImpl(HashState &h) {
// base case does nothing
}
};
/// A hash function object that hashes the address of a char pointer.
struct TfHashCharPtr {
size_t operator()(const char* ptr) const;
};
/// A hash function object that hashes null-terminated c-string content.
struct TfHashCString {
size_t operator()(const char* ptr) const;
};
/// A function object that compares two c-strings for equality.
struct TfEqualCString {
bool operator()(const char* lhs, const char* rhs) const;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+504
View File
@@ -0,0 +1,504 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
// Wrap one of various unordered map implementations. The exposed API
// is similar to std::unordered_map but is missing some methods and
// erase(const_iterator) returns nothing.
//
// Wrapping provides a convenient way to switch between implementations.
// The GNU extension (currently) has the best overall performance but
// isn't standard. Otherwise we use the C++11 standard implementation.
#ifndef PXR_BASE_TF_HASHMAP_H
#define PXR_BASE_TF_HASHMAP_H
#include "pxr/pxr.h"
#include "pxr/base/arch/defines.h"
#if defined(ARCH_HAS_GNU_STL_EXTENSIONS)
#include <ext/hash_map>
#else
#include <unordered_map>
#endif // ARCH_HAS_GNU_STL_EXTENSIONS
PXR_NAMESPACE_OPEN_SCOPE
#if defined(ARCH_HAS_GNU_STL_EXTENSIONS)
template<class Key, class Mapped, class HashFn = __gnu_cxx::hash<Key>,
class EqualKey = __gnu_cxx::equal_to<Key>,
class Alloc = __gnu_cxx::allocator<Mapped> >
class TfHashMap :
private __gnu_cxx::hash_map<Key, Mapped, HashFn, EqualKey, Alloc> {
typedef __gnu_cxx::hash_map<Key, Mapped, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::mapped_type mapped_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashMap() : _Base() { }
explicit
TfHashMap(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashMap(const allocator_type& alloc) :
_Base(0, hasher(), key_equal(), alloc) { }
template<class InputIterator>
TfHashMap(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashMap(const TfHashMap& other) : _Base(other) { }
TfHashMap& operator=(const TfHashMap& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return const_iterator(_Base::begin()); }
// size_type bucket(const key_type& key) const;
using _Base::bucket_count;
size_type bucket_size(size_type n) const { return _Base::elems_in_bucket(n); }
const_iterator cbegin() const { return const_iterator(_Base::begin()); }
const_iterator cend() const { return const_iterator(_Base::end()); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return const_iterator(_Base::end()); }
std::pair<iterator,iterator> equal_range(const key_type& key) {
return _Base::equal_range(key);
}
std::pair<const_iterator,const_iterator> equal_range(const key_type& key) const {
return _Base::equal_range(key);
}
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) {
_Base::erase(_MakeIterator(position));
}
void erase(const_iterator first, const_iterator last) {
_Base::erase(_MakeIterator(first), _MakeIterator(last));
}
iterator find(const key_type& key) { return _Base::find(key); }
const_iterator find(const key_type& key) const {
return const_iterator(_Base::find(key));
}
using _Base::get_allocator;
hasher hash_function() const { return _Base::hash_funct(); }
using _Base::insert;
iterator insert(const_iterator, const value_type& v) {
return insert(v).first;
}
using _Base::key_eq;
float load_factor() const {
return static_cast<float>(static_cast<double>(size()) / bucket_count());
}
using _Base::max_bucket_count;
float max_load_factor() const { return 1.0; }
// void max_load_factor(float) { }
using _Base::max_size;
void rehash(size_type n) { _Base::resize(__gnu_cxx::__stl_next_prime(n)); }
void reserve(size_type n) { _Base::resize(n); }
using _Base::size;
void swap(TfHashMap& other) { _Base::swap(other); }
mapped_type& operator[](const key_type& k) { return _Base::operator[](k); }
template<class Key2, class Mapped2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&,
const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&);
private:
// _Base::erase() takes an iterator, not a const_iterator. We happen
// to know const_iterator and iterator have the same layout.
static const iterator& _MakeIterator(const const_iterator& i) {
return reinterpret_cast<const iterator&>(i);
}
};
template<class Key, class Mapped, class HashFn = __gnu_cxx::hash<Key>,
class EqualKey = __gnu_cxx::equal_to<Key>,
class Alloc = __gnu_cxx::allocator<Mapped> >
class TfHashMultiMap :
private __gnu_cxx::hash_multimap<Key, Mapped, HashFn, EqualKey, Alloc> {
typedef __gnu_cxx::hash_multimap<Key, Mapped, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::mapped_type mapped_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashMultiMap() : _Base() { }
explicit
TfHashMultiMap(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashMultiMap(const allocator_type& alloc) :
_Base(0, hasher(), key_equal(), alloc) { }
template<class InputIterator>
TfHashMultiMap(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashMultiMap(const TfHashMultiMap& other) : _Base(other) { }
TfHashMultiMap& operator=(const TfHashMultiMap& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return const_iterator(_Base::begin()); }
// size_type bucket(const key_type& key) const;
using _Base::bucket_count;
size_type bucket_size(size_type n) const { return _Base::elems_in_bucket(n); }
const_iterator cbegin() const { return const_iterator(_Base::begin()); }
const_iterator cend() const { return const_iterator(_Base::end()); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return const_iterator(_Base::end()); }
std::pair<iterator,iterator> equal_range(const key_type& key) {
return _Base::equal_range(key);
}
std::pair<const_iterator,const_iterator> equal_range(const key_type& key) const {
return _Base::equal_range(key);
}
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) {
_Base::erase(_MakeIterator(position));
}
void erase(const_iterator first, const_iterator last) {
_Base::erase(_MakeIterator(first), _MakeIterator(last));
}
iterator find(const key_type& key) { return _Base::find(key); }
const_iterator find(const key_type& key) const {
return const_iterator(_Base::find(key));
}
using _Base::get_allocator;
hasher hash_function() const { return _Base::hash_funct(); }
using _Base::insert;
iterator insert(const_iterator, const value_type& v) {
return insert(v).first;
}
using _Base::key_eq;
float load_factor() const {
return static_cast<float>(static_cast<double>(size()) / bucket_count());
}
using _Base::max_bucket_count;
float max_load_factor() const { return 1.0; }
// void max_load_factor(float) { }
using _Base::max_size;
void rehash(size_type n) { _Base::resize(__gnu_cxx::__stl_next_prime(n)); }
void reserve(size_type n) { _Base::resize(n); }
using _Base::size;
void swap(TfHashMultiMap& other) { _Base::swap(other); }
mapped_type& operator[](const key_type& k) { return _Base::operator[](k); }
template<class Key2, class Mapped2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&,
const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&);
private:
// _Base::erase() takes an iterator, not a const_iterator. We happen
// to know const_iterator and iterator have the same layout.
static const iterator& _MakeIterator(const const_iterator& i) {
return reinterpret_cast<const iterator&>(i);
}
};
#else
template<class Key, class Mapped, class HashFn = std::hash<Key>,
class EqualKey = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, Mapped> > >
class TfHashMap :
private std::unordered_map<Key, Mapped, HashFn, EqualKey, Alloc> {
typedef std::unordered_map<Key, Mapped, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::mapped_type mapped_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashMap() : _Base() { }
explicit
TfHashMap(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashMap(const allocator_type& alloc) : _Base(alloc) { }
template<class InputIterator>
TfHashMap(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashMap(const TfHashMap& other) : _Base(other) { }
TfHashMap& operator=(const TfHashMap& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return _Base::begin(); }
// using _Base::bucket;
using _Base::bucket_count;
using _Base::bucket_size;
const_iterator cbegin() const { return _Base::cbegin(); }
const_iterator cend() const { return _Base::cend(); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return _Base::end(); }
using _Base::equal_range;
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) { _Base::erase(position); }
void erase(const_iterator first, const_iterator last) {
_Base::erase(first, last);
}
using _Base::find;
using _Base::get_allocator;
using _Base::hash_function;
std::pair<iterator, bool> insert(const value_type& v) {
return _Base::insert(v);
}
iterator insert(const_iterator hint, const value_type& v) {
return _Base::insert(hint, v);
}
template<class InputIterator>
void insert(InputIterator first, InputIterator last) {
_Base::insert(first, last);
}
using _Base::key_eq;
using _Base::load_factor;
using _Base::max_bucket_count;
using _Base::max_load_factor;
// using _Base::max_load_factor;
using _Base::max_size;
using _Base::rehash;
using _Base::reserve;
using _Base::size;
void swap(TfHashMap& other) { _Base::swap(other); }
mapped_type& operator[](const key_type& k) { return _Base::operator[](k); }
template<class Key2, class Mapped2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&,
const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&);
};
template<class Key, class Mapped, class HashFn = std::hash<Key>,
class EqualKey = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, Mapped> > >
class TfHashMultiMap :
private std::unordered_multimap<Key, Mapped, HashFn, EqualKey, Alloc> {
typedef std::unordered_multimap<Key, Mapped, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::mapped_type mapped_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashMultiMap() : _Base() { }
explicit
TfHashMultiMap(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashMultiMap(const allocator_type& alloc) : _Base(alloc) { }
template<class InputIterator>
TfHashMultiMap(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashMultiMap(const TfHashMultiMap& other) : _Base(other) { }
TfHashMultiMap& operator=(const TfHashMultiMap& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return _Base::begin(); }
// using _Base::bucket;
using _Base::bucket_count;
using _Base::bucket_size;
const_iterator cbegin() const { return _Base::cbegin(); }
const_iterator cend() const { return _Base::cend(); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return _Base::end(); }
using _Base::equal_range;
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) { _Base::erase(position); }
void erase(const_iterator first, const_iterator last) {
_Base::erase(first, last);
}
using _Base::find;
using _Base::get_allocator;
using _Base::hash_function;
iterator insert(const value_type& v) {
return _Base::insert(v);
}
iterator insert(const_iterator hint, const value_type& v) {
return _Base::insert(hint, v);
}
template<class InputIterator>
void insert(InputIterator first, InputIterator last) {
_Base::insert(first, last);
}
using _Base::key_eq;
using _Base::load_factor;
using _Base::max_bucket_count;
using _Base::max_load_factor;
// using _Base::max_load_factor;
using _Base::max_size;
using _Base::rehash;
using _Base::reserve;
using _Base::size;
void swap(TfHashMultiMap& other) { _Base::swap(other); }
mapped_type& operator[](const key_type& k) { return _Base::operator[](k); }
template<class Key2, class Mapped2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&,
const TfHashMap<Key2, Mapped2, HashFn2, EqualKey2, Alloc2>&);
};
#endif // ARCH_HAS_GNU_STL_EXTENSIONS
template<class Key, class Mapped, class HashFn, class EqualKey, class Alloc>
inline void
swap(TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>& lhs,
TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>& rhs)
{
lhs.swap(rhs);
}
template<class Key, class Mapped, class HashFn, class EqualKey, class Alloc>
inline bool
operator==(const TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>& lhs,
const TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>& rhs)
{
typedef typename TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>::_Base _Base;
return static_cast<const _Base&>(lhs) == static_cast<const _Base&>(rhs);
}
template<class Key, class Mapped, class HashFn, class EqualKey, class Alloc>
inline bool
operator!=(const TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>& lhs,
const TfHashMap<Key, Mapped, HashFn, EqualKey, Alloc>& rhs)
{
return !(lhs == rhs);
}
template<class Key, class Mapped, class HashFn, class EqualKey, class Alloc>
inline void
swap(TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>& lhs,
TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>& rhs)
{
lhs.swap(rhs);
}
template<class Key, class Mapped, class HashFn, class EqualKey, class Alloc>
inline bool
operator==(const TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>& lhs,
const TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>& rhs)
{
typedef typename TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>::_Base _Base;
return static_cast<const _Base&>(lhs) == static_cast<const _Base&>(rhs);
}
template<class Key, class Mapped, class HashFn, class EqualKey, class Alloc>
inline bool
operator!=(const TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>& lhs,
const TfHashMultiMap<Key, Mapped, HashFn, EqualKey, Alloc>& rhs)
{
return !(lhs == rhs);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_HASHMAP_H
+496
View File
@@ -0,0 +1,496 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
// Wrap one of various unordered set implementations. The exposed API
// is similar to std::unordered_set but is missing some methods and
// erase(const_iterator) returns nothing.
//
// Wrapping provides a convenient way to switch between implementations.
// The GNU extension (currently) has the best overall performance but
// isn't standard. Otherwise we use the C++11 standard implementation.
#ifndef PXR_BASE_TF_HASHSET_H
#define PXR_BASE_TF_HASHSET_H
#include "pxr/pxr.h"
#include "pxr/base/arch/defines.h"
#if defined(ARCH_HAS_GNU_STL_EXTENSIONS)
#include <ext/hash_set>
#else
#include <unordered_set>
#endif // ARCH_HAS_GNU_STL_EXTENSIONS
PXR_NAMESPACE_OPEN_SCOPE
#if defined(ARCH_HAS_GNU_STL_EXTENSIONS)
template<class Key, class HashFn = __gnu_cxx::hash<Key>,
class EqualKey = __gnu_cxx::equal_to<Key>,
class Alloc = __gnu_cxx::allocator<Key> >
class TfHashSet :
private __gnu_cxx::hash_set<Key, HashFn, EqualKey, Alloc> {
typedef __gnu_cxx::hash_set<Key, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashSet() : _Base() { }
explicit
TfHashSet(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashSet(const allocator_type& alloc) :
_Base(0, hasher(), key_equal(), alloc) { }
template<class InputIterator>
TfHashSet(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashSet(const TfHashSet& other) : _Base(other) { }
TfHashSet& operator=(const TfHashSet& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return const_iterator(_Base::begin()); }
// size_type bucket(const key_type& key) const;
using _Base::bucket_count;
size_type bucket_size(size_type n) const { return _Base::elems_in_bucket(n); }
const_iterator cbegin() const { return const_iterator(_Base::begin()); }
const_iterator cend() const { return const_iterator(_Base::end()); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return const_iterator(_Base::end()); }
std::pair<iterator,iterator> equal_range(const key_type& key) {
return _Base::equal_range(key);
}
std::pair<const_iterator,const_iterator> equal_range(const key_type& key) const {
return _Base::equal_range(key);
}
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) {
_Base::erase(_MakeIterator(position));
}
void erase(const_iterator first, const_iterator last) {
_Base::erase(_MakeIterator(first), _MakeIterator(last));
}
iterator find(const key_type& key) { return _Base::find(key); }
const_iterator find(const key_type& key) const {
return const_iterator(_Base::find(key));
}
using _Base::get_allocator;
hasher hash_function() const { return _Base::hash_funct(); }
using _Base::insert;
iterator insert(const_iterator, const value_type& v) {
return insert(v).first;
}
using _Base::key_eq;
float load_factor() const {
return static_cast<float>(static_cast<double>(size()) / bucket_count());
}
using _Base::max_bucket_count;
float max_load_factor() const { return 1.0; }
// void max_load_factor(float) { }
using _Base::max_size;
void rehash(size_type n) { _Base::resize(__gnu_cxx::__stl_next_prime(n)); }
void reserve(size_type n) { _Base::resize(n); }
using _Base::size;
void swap(TfHashSet& other) { _Base::swap(other); }
template<class Key2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashSet<Key2, HashFn2, EqualKey2, Alloc2>&,
const TfHashSet<Key2, HashFn2, EqualKey2, Alloc2>&);
private:
// _Base::erase() takes an iterator, not a const_iterator. We happen
// to know const_iterator and iterator have the same layout.
static const iterator& _MakeIterator(const const_iterator& i) {
return reinterpret_cast<const iterator&>(i);
}
};
template<class Key, class HashFn = __gnu_cxx::hash<Key>,
class EqualKey = __gnu_cxx::equal_to<Key>,
class Alloc = __gnu_cxx::allocator<Key> >
class TfHashMultiSet :
private __gnu_cxx::hash_multiset<Key, HashFn, EqualKey, Alloc> {
typedef __gnu_cxx::hash_multiset<Key, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashMultiSet() : _Base() { }
explicit
TfHashMultiSet(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashMultiSet(const allocator_type& alloc) :
_Base(0, hasher(), key_equal(), alloc) { }
template<class InputIterator>
TfHashMultiSet(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashMultiSet(const TfHashMultiSet& other) : _Base(other) { }
TfHashMultiSet& operator=(const TfHashMultiSet& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return const_iterator(_Base::begin()); }
// size_type bucket(const key_type& key) const;
using _Base::bucket_count;
size_type bucket_size(size_type n) const { return _Base::elems_in_bucket(n); }
const_iterator cbegin() const { return const_iterator(_Base::begin()); }
const_iterator cend() const { return const_iterator(_Base::end()); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return const_iterator(_Base::end()); }
std::pair<iterator,iterator> equal_range(const key_type& key) {
return _Base::equal_range(key);
}
std::pair<const_iterator,const_iterator> equal_range(const key_type& key) const {
return _Base::equal_range(key);
}
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) {
_Base::erase(_MakeIterator(position));
}
void erase(const_iterator first, const_iterator last) {
_Base::erase(_MakeIterator(first), _MakeIterator(last));
}
iterator find(const key_type& key) { return _Base::find(key); }
const_iterator find(const key_type& key) const {
return const_iterator(_Base::find(key));
}
using _Base::get_allocator;
hasher hash_function() const { return _Base::hash_funct(); }
using _Base::insert;
iterator insert(const_iterator, const value_type& v) {
return insert(v).first;
}
using _Base::key_eq;
float load_factor() const {
return static_cast<float>(static_cast<double>(size()) / bucket_count());
}
using _Base::max_bucket_count;
float max_load_factor() const { return 1.0; }
// void max_load_factor(float) { }
using _Base::max_size;
void rehash(size_type n) { _Base::resize(__gnu_cxx::__stl_next_prime(n)); }
void reserve(size_type n) { _Base::resize(n); }
using _Base::size;
void swap(TfHashMultiSet& other) { _Base::swap(other); }
template<class Key2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashMultiSet<Key2, HashFn2, EqualKey2, Alloc2>&,
const TfHashMultiSet<Key2, HashFn2, EqualKey2, Alloc2>&);
private:
// _Base::erase() takes an iterator, not a const_iterator. We happen
// to know const_iterator and iterator have the same layout.
static const iterator& _MakeIterator(const const_iterator& i) {
return reinterpret_cast<const iterator&>(i);
}
};
#else
template<class Key, class HashFn = std::hash<Key>,
class EqualKey = std::equal_to<Key>,
class Alloc = std::allocator<Key> >
class TfHashSet :
private std::unordered_set<Key, HashFn, EqualKey, Alloc> {
typedef std::unordered_set<Key, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashSet() : _Base() { }
explicit
TfHashSet(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashSet(const allocator_type& alloc) : _Base(alloc) { }
template<class InputIterator>
TfHashSet(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashSet(const TfHashSet& other) : _Base(other) { }
TfHashSet& operator=(const TfHashSet& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return _Base::begin(); }
// using _Base::bucket;
using _Base::bucket_count;
using _Base::bucket_size;
const_iterator cbegin() const { return _Base::cbegin(); }
const_iterator cend() const { return _Base::cend(); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return _Base::end(); }
using _Base::equal_range;
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) { _Base::erase(position); }
void erase(const_iterator first, const_iterator last) {
_Base::erase(first, last);
}
using _Base::find;
using _Base::get_allocator;
using _Base::hash_function;
std::pair<iterator, bool> insert(const value_type& v) {
return _Base::insert(v);
}
iterator insert(const_iterator hint, const value_type& v) {
return _Base::insert(hint, v);
}
template<class InputIterator>
void insert(InputIterator first, InputIterator last) {
_Base::insert(first, last);
}
using _Base::key_eq;
using _Base::load_factor;
using _Base::max_bucket_count;
using _Base::max_load_factor;
// using _Base::max_load_factor;
using _Base::max_size;
using _Base::rehash;
using _Base::reserve;
using _Base::size;
void swap(TfHashSet& other) { _Base::swap(other); }
template<class Key2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashSet<Key2, HashFn2, EqualKey2, Alloc2>&,
const TfHashSet<Key2, HashFn2, EqualKey2, Alloc2>&);
};
template<class Key, class HashFn = std::hash<Key>,
class EqualKey = std::equal_to<Key>,
class Alloc = std::allocator<Key> >
class TfHashMultiSet :
private std::unordered_multiset<Key, HashFn, EqualKey, Alloc> {
typedef std::unordered_multiset<Key, HashFn, EqualKey, Alloc> _Base;
public:
typedef typename _Base::key_type key_type;
typedef typename _Base::value_type value_type;
typedef typename _Base::hasher hasher;
typedef typename _Base::key_equal key_equal;
typedef typename _Base::size_type size_type;
typedef typename _Base::difference_type difference_type;
typedef typename _Base::pointer pointer;
typedef typename _Base::const_pointer const_pointer;
typedef typename _Base::reference reference;
typedef typename _Base::const_reference const_reference;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::allocator_type allocator_type;
// No local_iterator nor any methods using them.
TfHashMultiSet() : _Base() { }
explicit
TfHashMultiSet(size_type n, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(n, hf, eql, alloc) { }
explicit
TfHashMultiSet(const allocator_type& alloc) : _Base(alloc) { }
template<class InputIterator>
TfHashMultiSet(InputIterator first, InputIterator last,
size_type n = 0, const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type()) :
_Base(first, last, n, hf, eql, alloc) { }
TfHashMultiSet(const TfHashMultiSet& other) : _Base(other) { }
TfHashMultiSet& operator=(const TfHashMultiSet& rhs) {
_Base::operator=(rhs);
return *this;
}
iterator begin() { return _Base::begin(); }
const_iterator begin() const { return _Base::begin(); }
// using _Base::bucket;
using _Base::bucket_count;
using _Base::bucket_size;
const_iterator cbegin() const { return _Base::cbegin(); }
const_iterator cend() const { return _Base::cend(); }
using _Base::clear;
using _Base::count;
using _Base::empty;
iterator end() { return _Base::end(); }
const_iterator end() const { return _Base::end(); }
using _Base::equal_range;
size_type erase(const key_type& key) { return _Base::erase(key); }
void erase(const_iterator position) { _Base::erase(position); }
void erase(const_iterator first, const_iterator last) {
_Base::erase(first, last);
}
using _Base::find;
using _Base::get_allocator;
using _Base::hash_function;
iterator insert(const value_type& v) {
return _Base::insert(v);
}
iterator insert(const_iterator hint, const value_type& v) {
return _Base::insert(hint, v);
}
template<class InputIterator>
void insert(InputIterator first, InputIterator last) {
_Base::insert(first, last);
}
using _Base::key_eq;
using _Base::load_factor;
using _Base::max_bucket_count;
using _Base::max_load_factor;
// using _Base::max_load_factor;
using _Base::max_size;
using _Base::rehash;
using _Base::reserve;
using _Base::size;
void swap(TfHashMultiSet& other) { _Base::swap(other); }
template<class Key2, class HashFn2, class EqualKey2, class Alloc2>
friend bool
operator==(const TfHashMultiSet<Key2, HashFn2, EqualKey2, Alloc2>&,
const TfHashMultiSet<Key2, HashFn2, EqualKey2, Alloc2>&);
};
#endif // ARCH_HAS_GNU_STL_EXTENSIONS
template<class Key, class HashFn, class EqualKey, class Alloc>
inline void
swap(TfHashSet<Key, HashFn, EqualKey, Alloc>& lhs,
TfHashSet<Key, HashFn, EqualKey, Alloc>& rhs)
{
lhs.swap(rhs);
}
template<class Key, class HashFn, class EqualKey, class Alloc>
inline bool
operator==(const TfHashSet<Key, HashFn, EqualKey, Alloc>& lhs,
const TfHashSet<Key, HashFn, EqualKey, Alloc>& rhs)
{
typedef typename TfHashSet<Key, HashFn, EqualKey, Alloc>::_Base _Base;
return static_cast<const _Base&>(lhs) == static_cast<const _Base&>(rhs);
}
template<class Key, class HashFn, class EqualKey, class Alloc>
inline bool
operator!=(const TfHashSet<Key, HashFn, EqualKey, Alloc>& lhs,
const TfHashSet<Key, HashFn, EqualKey, Alloc>& rhs)
{
return !(lhs == rhs);
}
template<class Key, class HashFn, class EqualKey, class Alloc>
inline void
swap(TfHashMultiSet<Key, HashFn, EqualKey, Alloc>& lhs,
TfHashMultiSet<Key, HashFn, EqualKey, Alloc>& rhs)
{
lhs.swap(rhs);
}
template<class Key, class HashFn, class EqualKey, class Alloc>
inline bool
operator==(const TfHashMultiSet<Key, HashFn, EqualKey, Alloc>& lhs,
const TfHashMultiSet<Key, HashFn, EqualKey, Alloc>& rhs)
{
typedef typename TfHashMultiSet<Key, HashFn, EqualKey, Alloc>::_Base _Base;
return static_cast<const _Base&>(lhs) == static_cast<const _Base&>(rhs);
}
template<class Key, class HashFn, class EqualKey, class Alloc>
inline bool
operator!=(const TfHashMultiSet<Key, HashFn, EqualKey, Alloc>& lhs,
const TfHashMultiSet<Key, HashFn, EqualKey, Alloc>& rhs)
{
return !(lhs == rhs);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_HASHSET_H
+104
View File
@@ -0,0 +1,104 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/*
* This header is not meant to be included in a .h file.
* Complain if we see this header twice through.
*/
#ifdef PXR_BASE_TF_INSTANTIATE_SINGLETON_H
#error This file should only be included once in any given source (.cpp) file.
#endif
#define PXR_BASE_TF_INSTANTIATE_SINGLETON_H
/// \file tf/instantiateSingleton.h
/// \ingroup group_tf_ObjectCreation
/// Manage a single instance of an object.
#include "pxr/pxr.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/mallocTag.h"
#include "pxr/base/arch/demangle.h"
PXR_NAMESPACE_OPEN_SCOPE
template <class T> std::mutex* TfSingleton<T>::_mutex = 0;
template <class T> T* TfSingleton<T>::_instance = 0;
template <typename T>
T&
TfSingleton<T>::_CreateInstance()
{
// Why is TfSingleton<T>::_mutex a pointer requiring allocation and
// construction and not simply an object? Because the default
// std::mutex c'tor on MSVC 2015 isn't constexpr . That means the
// mutex is dynamically initialized. That can be too late for
// singletons, which are often accessed via ARCH_CONSTRUCTOR()
// functions.
static std::once_flag once;
std::call_once(once, [](){
TfSingleton<T>::_mutex = new std::mutex;
});
TfAutoMallocTag2 tag2("Tf", "TfSingleton::_CreateInstance");
TfAutoMallocTag tag("Create Singleton " + ArchGetDemangled<T>());
std::lock_guard<std::mutex> lock(*TfSingleton<T>::_mutex);
if (!TfSingleton<T>::_instance) {
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_MAY_NOT_BE_ALIGNED
T *inst = new T;
ARCH_PRAGMA_POP
// T's constructor could cause this to be created and set
// already, so guard against that.
if (!TfSingleton<T>::_instance) {
TfSingleton<T>::_instance = inst;
}
}
return *TfSingleton<T>::_instance;
}
template <typename T>
void
TfSingleton<T>::_DestroyInstance()
{
std::lock_guard<std::mutex> lock(*TfSingleton<T>::_mutex);
delete TfSingleton<T>::_instance;
TfSingleton<T>::_instance = 0;
}
/// Source file definition that a type is being used as a singleton.
///
/// To use a type \c T in conjunction with \c TfSingleton, add
/// TF_INSTANTIATE_SINGLETON(T) in one source file (typically the .cpp) file
/// for class \c T.
///
/// \hideinitializer
#define TF_INSTANTIATE_SINGLETON(T) \
template class PXR_NS_GLOBAL::TfSingleton<T>
PXR_NAMESPACE_CLOSE_SCOPE
+44
View File
@@ -0,0 +1,44 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifdef PXR_BASE_TF_INSTANTIATE_STACKED_H
#error This file may be included only once in a translation unit (.cpp file).
#endif
#define PXR_BASE_TF_INSTANTIATE_STACKED_H
#include "pxr/pxr.h"
#include "pxr/base/tf/stacked.h"
PXR_NAMESPACE_OPEN_SCOPE
#define TF_INSTANTIATE_STACKED(Derived) \
template <> \
std::atomic<typename Derived::Storage::Type*> \
Derived::Storage::value(nullptr)
#define TF_INSTANTIATE_DEFINED_STACKED(Derived) \
std::atomic<typename Derived::Storage::Type*> \
Derived::Storage::value(nullptr)
PXR_NAMESPACE_CLOSE_SCOPE
+87
View File
@@ -0,0 +1,87 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/*
* This header is not meant to be included in a .h file.
* Complain if we see this header twice through.
*/
#ifdef PXR_BASE_TF_INSTANTIATE_TYPE_H
#error This file should only be included once in any given source (.cpp) file.
#endif
#define PXR_BASE_TF_INSTANTIATE_TYPE_H
#include "pxr/pxr.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/refPtr.h"
PXR_NAMESPACE_OPEN_SCOPE
template <typename T, bool AS_REF_PTR>
struct Tf_TypeFactoryType {
struct FactoryType : public TfType::FactoryBase {
TfRefPtr<T> New() { return T::New(); }
};
};
template <class T>
struct TfTest_RefPtrFactory {
};
template <typename T>
struct Tf_TypeFactoryType<T, false> {
struct FactoryType : public TfType::FactoryBase {
T* New() { return new T; }
};
};
// Make the type actually manufacturable.
template <typename T, bool MANUFACTURABLE>
struct Tf_MakeTypeManufacturable {
static void Doit(TfType t) {
typedef typename Tf_TypeFactoryType<T, TF_SUPPORTS_REFPTR(T)>::FactoryType FT;
t.SetFactory<FT>();
}
};
// Don't make it manufacturable.
template <typename T>
struct Tf_MakeTypeManufacturable<T, false> {
static void Doit(TfType) {
}
};
#define _TF_REMOVE_PARENS_HELPER(...) __VA_ARGS__
#define _TF_REMOVE_PARENS(parens) _TF_REMOVE_PARENS_HELPER parens
#define TF_NO_PARENT() (TfType::Bases<>)
#define TF_1_PARENT(p1) (TfType::Bases<p1 >)
#define TF_2_PARENT(p1,p2) (TfType::Bases<p1, p2 >)
#define TF_INSTANTIATE_TYPE(Type, flags, Bases) \
TF_REGISTRY_DEFINE_WITH_TYPE(TfType, Type) { \
TfType t1 = TfType::Define<Type, _TF_REMOVE_PARENS(Bases) >(); \
Tf_MakeTypeManufacturable<Type, (flags&TfType::MANUFACTURABLE)!=0 >::Doit(t1); \
}
PXR_NAMESPACE_CLOSE_SCOPE
+414
View File
@@ -0,0 +1,414 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_ITERATOR_H
#define PXR_BASE_TF_ITERATOR_H
/// \file tf/iterator.h
/// \ingroup group_tf_Containers
/// A simple iterator adapter for \c STL containers.
#include "pxr/pxr.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/diagnosticLite.h"
#include <iterator>
#include <type_traits>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
// May be specialized by container proxies and container "views" to indicate
// they should be copied for TfIterator iteration.
template <class T>
struct Tf_ShouldIterateOverCopy : std::false_type {};
// IteratorInterface abstracts the differences between forward/backward and
// const/non-const iteration so that TfIterator doesn't have to think about
// them. It simply provides the IteratorType (which is either iterator,
// const_iterator, reverse_iterator, or reverse_const_iterator) and Begin and
// End which call the correct functions in the container (begin, rbegin, end,
// rend).
template <class T, bool Reverse>
struct Tf_IteratorInterface {
typedef typename T::iterator IteratorType;
static IteratorType Begin(T &c) { return c.begin(); }
static IteratorType End(T &c) { return c.end(); }
};
template <class T, bool Reverse>
struct Tf_IteratorInterface<const T, Reverse> {
typedef typename T::const_iterator IteratorType;
static IteratorType Begin(T const &c) { return c.begin(); }
static IteratorType End(T const &c) { return c.end(); }
};
template <class T>
struct Tf_IteratorInterface<T, true> {
typedef typename T::reverse_iterator IteratorType;
static IteratorType Begin(T &c) { return c.rbegin(); }
static IteratorType End(T &c) { return c.rend(); }
};
template <class T>
struct Tf_IteratorInterface<const T, true> {
typedef typename T::const_reverse_iterator IteratorType;
static IteratorType Begin(T const &c) { return c.rbegin(); }
static IteratorType End(T const &c) { return c.rend(); }
};
/// \class TfIterator
/// \ingroup group_tf_Containers group_tf_Stl
///
/// A simple iterator adapter for \c STL containers.
///
/// \c TfIterator iterates over the elements in an \c STL container, according
/// to the semantics of the \ref iterator_pattern "simple iterator pattern".
/// The following examples compare the \c TfIterator to \c STL, highlighting
/// the brevity of the \c TfIterator interface.
/// \code
/// std::vector<int> vector;
/// std::set<int> set;
///
/// // TfIterator 'while' loop
/// TfIterator< std::vector<int> > i(vector);
/// while (i) {
/// int x = *i++;
/// }
///
/// // STL 'while' loop
/// std::vector<int>::iterator i = vector.begin();
/// while (i != vector.end()) {
/// int x = *i++;
/// }
///
/// // TfIterator 'for' loop
/// std::set<int> set;
/// for (TfIterator< const std::set<int> > j = set; j; ++j) {
/// int x = *j;
/// }
///
/// // STL 'for' loop
/// std::set<int> set;
/// for (std::set<int>::iterator j = set.begin(); j != set.end(); ++j) {
/// int x = *j;
/// }
/// \endcode
///
/// Note that using the \c TF_FOR_ALL() macro, even more brevity is possible.
/// For example, to print out all items of a \c set<int> \c s, we could write
/// \code
/// TF_FOR_ALL(i, s)
/// printf("%d\n", *i);
/// \endcode
///
/// Typically, a \c TfIterator is used to traverse all of the elements in an
/// \c STL container. For ordered sets, other uses include iterating over a
/// subset of the elements in the container, and using a \c TfIterator as a
/// sentinel.
/// \code
/// // Iterate over subset
/// TfIterator< std::vector<int> > start, finish;
/// TfIterator< std::vector<int> > iterator(start, finish);
///
/// // TfIterator sentinel
/// TfIterator< std::vector<int> > sentinel(finish, finish);
/// while (iterator != sentinel) {
/// int x = *iterator++;
/// }
/// \endcode
///
/// \anchor iterator_pattern
/// <b>The Simple Iterator Pattern</b>
///
/// The \e simple \e iterator pattern generalizes pointer semantics to
/// traverse a set of elements, much like \c STL iterators. However, the
/// simple iterator pattern subscribes to a simpler subset of pointer
/// operations: pointer assignment (\c operator=), auto-increment (\c
/// operator++), dereferencing (\c operator*), redirection (\c operator->),
/// and null pointer comparison (\c operator! and \c operator \c bool). The
/// simpler interface improves code legibility for the typical set traversals
/// for which iterators are most commonly used. It is particularly useful for
/// specifying iterators over sets of elements that are maintained by a user
/// object, since the interface calls for only one \c GetIterator() entry
/// point rather than dual \c begin() and \c end() calls. This is especially
/// desirable when the object owns many different sets.
/// \code
/// // The simple iterator pattern.
/// class Iterator {
/// Iterator(); // default c'tor
/// Iterator(const Iterator&); // copy c'tor
/// Iterator& operator=(const Iterator &); // assignment
/// Iterator& operator++(); // pre-increment
/// Iterator operator++(int); // post-increment
/// reference operator *(); // dereference
/// pointer operator->(); // redirection
/// bool operator==(const Iterator &) const; // equality
/// bool operator!=(const Iterator &) const; // inequality
/// bool operator!() const // is exhausted
/// operator bool() const; // is not exhausted
/// };
/// \endcode
///
/// \param T container type
///
template <class T, bool Reverse=false>
class TfIterator {
// Forward declare implementation structs.
struct _IteratorPairAndCopy;
struct _IteratorPair;
// Select the correct data storage depending on whether we should iterate
// over a copy of the container.
typedef typename std::conditional<
Tf_ShouldIterateOverCopy<T>::value,
_IteratorPairAndCopy, _IteratorPair
>::type _Data;
public:
// Choose either iterator or const_iterator for Iterator depending on
// whether T is const.
typedef Tf_IteratorInterface<T, Reverse> IterInterface;
typedef typename IterInterface::IteratorType Iterator;
typedef typename std::iterator_traits<Iterator>::reference Reference;
/// Default constructor. This iterator is uninitialized.
TfIterator() { }
/// Constructs an iterator to traverse each element of the specified
/// \c STL container object.
/// \param container container object
TfIterator(T &container) : _data(container) {}
/// Allow rvalues only if the container type T should be copied by TfIterator.
TfIterator(T &&container)
: _data(container)
{
static_assert(
Tf_ShouldIterateOverCopy<typename std::decay<T>::type>::value,
"TfIterator only allows rvalues that it has been told to copy "
"via Tf_ShouldIterateOverCopy");
}
/// Constructs an iterator to traverse a subset of the elements in a
/// container. This iterator is exhausted when it reaches the end
/// iterator.
/// \param begin iterator at the beginning of the sequence
/// \param end iterator at the end of the sequence
TfIterator(Iterator const &begin, Iterator const &end)
: _data(begin, end)
{
}
/// Returns true if this iterator is exhausted.
/// \return true if this iterator is exhausted
bool operator!() const {
return _data.current == _data.end;
}
/// Returns true if this Iterator.has the same position in the sequence as
/// the specified iterator. The end of the sequence need not be the same.
/// \param iterator iterator to compare
/// \return true if this Iterator.has the same position as \e iterator
bool operator==(const TfIterator& iterator) const {
return _data.current == iterator._data.current;
}
/// Returns false if (*this == \a iterator) returns true, returns true
/// otherwise.
bool operator!=(const TfIterator& iterator) const {
return !(*this == iterator);
}
/// Pre-increment operator. Advances this iterator to the next element in
/// the sequence.
/// \return this iterator
TfIterator& operator++() {
if (!*this) {
TF_CODING_ERROR("iterator exhausted");
return *this;
}
++_data.current;
return *this;
}
/// Post-increment operator. Advances this iterator to the next element in
/// the sequence, and returns a copy of this iterator prior to the increment.
/// \return copy of this iterator prior to increment
TfIterator operator++(int) {
TfIterator iterator = *this;
++(*this);
return iterator;
}
/// Returns the element referenced by this iterator.
/// \return element
Reference operator*() {
if (ARCH_UNLIKELY(!*this))
TF_FATAL_ERROR("iterator exhausted");
return *_data.current;
}
/// Returns the element referenced by this iterator.
/// \return element
Reference operator*() const {
if (ARCH_UNLIKELY(!*this))
TF_FATAL_ERROR("iterator exhausted");
return *_data.current;
}
/// Returns a pointer to the element referenced by this iterator.
/// \return pointer to element
Iterator& operator->() {
if (ARCH_UNLIKELY(!*this))
TF_FATAL_ERROR("iterator exhausted");
return _data.current;
}
/// Explicit bool conversion operator.
/// The Iterator object converts to true if it has not been exhausted.
explicit operator bool() const {
return !(_data.current == _data.end);
}
/// Returns an \c STL iterator that has the same position as this
/// iterator.
/// \return \c STL iterator at the same position as this iterator
operator Iterator() const {
return _data.current;
}
/// Returns an \c STL iterator that has the same position as this
/// iterator.
/// \return \c STL iterator at the same position as this iterator
const Iterator& base() const {
return _data.current;
}
/// Returns an iterator that is positioned at the next element in the
/// sequence.
/// \return iterator at next element in the sequence
TfIterator GetNext() const {
TfIterator next = *this;
++next;
return next;
}
private: // state
// Normal iteration just holds onto the begin/end pair of iterators.
struct _IteratorPair {
_IteratorPair() {}
explicit _IteratorPair(T &c) {
// Use assignment rather than initializer-list here to work around
// a GCC 4.1.2 bug when using TfIterator with TfHashMap.
current = IterInterface::Begin(c);
end = IterInterface::End(c);
}
_IteratorPair(Iterator const &b, Iterator const &e) :
current(b), end(e) {}
Iterator current;
Iterator end;
};
// Iterating over copies which is appropriate for proxies retains a copy of
// 'container' and iterators into the copy.
struct _IteratorPairAndCopy : public _IteratorPair {
_IteratorPairAndCopy() {}
explicit _IteratorPairAndCopy(T const &c) : _IteratorPair(), _copy(c) {
current = IterInterface::Begin(_copy);
end = IterInterface::End(_copy);
}
using _IteratorPair::current;
using _IteratorPair::end;
private:
T _copy;
};
_Data _data;
};
/// Helper functions for creating TfIterator objects.
/// \ingroup group_tf_Containers
template <class T>
TfIterator<typename std::remove_reference<T>::type>
TfMakeIterator(T&& container)
{
return TfIterator<typename std::remove_reference<T>::type>(
std::forward<T>(container));
}
template <class T>
TfIterator<typename std::remove_reference<T>::type, /* Reverse = */ true>
TfMakeReverseIterator(T&& container)
{
return TfIterator<typename std::remove_reference<T>::type, true>(
std::forward<T>(container));
}
/// Macro for iterating over a container.
///
/// For any container \c c of type \c T, the following loop
/// \code
/// for (TfIterator<T> i = c.begin(); i; ++i) {
/// ...
/// }
/// \endcode
/// is equivalent to
/// \code
/// TF_FOR_ALL(i, c) {
/// ...
/// }
/// \endcode
///
/// \ingroup group_tf_Containers
/// \hideinitializer
#define TF_FOR_ALL(iter, c) \
for (auto iter = TfMakeIterator(c); iter; ++iter)
/// Macro for iterating over a container in reverse.
///
/// Operates like \a TF_FOR_ALL, but iterates the container in reverse order.
///
/// \ingroup group_tf_Containers
/// \hideinitializer
#define TF_REVERSE_FOR_ALL(iter, c) \
for (auto iter = TfMakeReverseIterator(c); iter; ++iter)
/// Returns the number of elements in a statically sized array.
///
/// This function is an implementation of the array version of C++17's
/// std::size()
template <class T, size_t N>
constexpr size_t TfArraySize(const T (&array)[N]) noexcept
{
return N;
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_ITERATOR_H
+639
View File
@@ -0,0 +1,639 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#if !BOOST_PP_IS_ITERATING
#ifndef PXR_BASE_TF_MAKE_PY_CONSTRUCTOR_H
#define PXR_BASE_TF_MAKE_PY_CONSTRUCTOR_H
/// \file tf/makePyConstructor.h
/// An injected constructor mechanism that works with polymorphic wrapped
/// classes.
#ifndef TF_MAX_ARITY
# define TF_MAX_ARITY 7
#endif // TF_MAX_ARITY
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/pyError.h"
#include "pxr/base/tf/pyIdentity.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/arch/demangle.h"
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/python/def_visitor.hpp>
#include <boost/python/dict.hpp>
#include <boost/python/errors.hpp>
#include <boost/python/list.hpp>
#include <boost/python/object/iterator.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/type_id.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
// Helper for wrapping objects that are held by weak pointers, but may also be
// constructed from script. This lets one construct an object from script and
// stores a ref pointer to the C++ object inside the python object. This way,
// objects created from script are owned by script, but objects obtained from
// the C++ API cannot be owned by script. When the owning python object is
// collected, its ref pointer will go away and the C++ object will be
// deallocated.
//
// Example usage:
//
// class_<MyClass, MyClassPtr>("MyClass", no_init)
// .def(TfPyRefAndWeakPtr())
// .def(TfMakePyConstructor(MyClass::New))
// .def(...)
// ...
//
// TfMakePyConstructorWithVarArgs may be used to wrap an object so that it
// may be constructed with a variable number of positional and keyword
// arguments. The last two arguments of the function being wrapped must
// be a boost::python::tuple and dict. These will contain the remaining
// positional and keyword args after required arguments are parsed.
//
// Example usage:
//
// static MyObjectRefPtr MyObjectFactory(
// int formalArg1, const std::string& formalArg2,
// const boost::python::tuple& args, const boost::python::dict& kwargs);
//
// class_<MyClass, MyClassPtr>("MyClass", no_init)
// .def(TfPyRefAndWeakPtr())
// .def(TfMakePyConstructorWithVarArgs(MyObjectFactory))
// .def(...)
//
// NOTE: The current implementation does not handle boost::python::arg for
// specifying keywords for required arguments.
namespace Tf_MakePyConstructor {
namespace bp = boost::python;
template <typename CTOR>
struct InitVisitor : bp::def_visitor<InitVisitor<CTOR> > {
friend class bp::def_visitor_access;
const std::string _doc;
InitVisitor(const std::string &doc = std::string()) : _doc(doc) {}
template <typename CLS>
void visit(CLS &c) const {
c.def("__init__", CTOR::template init_callable<CLS>(), _doc.c_str());
}
template <class CLS, class Options>
void visit(CLS &c, char const* name, Options& options) const {
// Note: we ignore options.doc() in favor of _doc
c.def(name, CTOR::template init_callable<CLS>(options), _doc.c_str());
}
};
TF_API
bp::object _DummyInit(bp::tuple const & /* args */,
bp::dict const & /* kw */);
template <typename CTOR>
struct NewVisitor : bp::def_visitor<NewVisitor<CTOR> > {
friend class bp::def_visitor_access;
const std::string _doc;
NewVisitor(const std::string &doc = std::string()) : _doc(doc) {}
template <typename CLS>
void visit(CLS &c) const {
// If there's already a __new__ method, look through the staticmethod to
// get the underlying function, replace __new__ with that, then add the
// overload, and recreate the staticmethod. This is required because
// boost python needs to have all overloads exported before you say
// .staticmethod.
// Note that it looks like this should do nothing, but it actually does
// something! Here's what it does: looking up __new__ on c doesn't
// actually produce the staticmethod object -- it does a "descriptor
// __get__" which produces the underlying function. Replacing __new__
// with that underlying thing has the effect of unwrapping the
// staticmethod, which is exactly what we want.
if (PyObject_HasAttrString(c.ptr(), "__new__"))
c.attr("__new__") = c.attr("__new__");
c.def("__new__", CTOR::template __new__<CLS>, _doc.c_str());
c.staticmethod("__new__");
//c.def("__init__", CTOR::template __init__<CLS>, _doc.c_str());
c.def("__init__", bp::raw_function(_DummyInit));
}
template <class CLS, class Options>
void visit(CLS &c, char const* name, Options& options) const {
// If there's already a __new__ method, look through the staticmethod to
// get the underlying function, replace __new__ with that, then add the
// overload, and recreate the staticmethod. This is required because
// boost python needs to have all overloads exported before you say
// .staticmethod.
// Note that it looks like this should do nothing, but it actually does
// something! Here's what it does: looking up __new__ on c doesn't
// actually produce the staticmethod object -- it does a "descriptor
// __get__" which produces the underlying function. Replacing __new__
// with that underlying thing has the effect of unwrapping the
// staticmethod, which is exactly what we want.
if (PyObject_HasAttrString(c.ptr(), "__new__"))
c.attr("__new__") = c.attr("__new__");
c.def("__new__", CTOR::template __new__<CLS>,
// Note: we ignore options.doc() in favor of _doc
_doc.c_str(),
options.keywords(),
options.policies()
);
c.staticmethod("__new__");
//c.def("__init__", CTOR::template __init__<CLS>, _doc.c_str());
c.def("__init__", bp::raw_function(_DummyInit));
}
};
typedef bp::object object;
template <typename T>
struct InstallPolicy {
static void PostInstall(object const &self, T const &t,
const void *) {}
};
// Specialize install policy for refptrs.
template <typename T>
struct InstallPolicy<TfRefPtr<T> > {
static_assert(Tf_SupportsUniqueChanged<T>::Value,
"Type T must support refcount unique changed notification.");
static void PostInstall(object const &self, TfRefPtr<T> const &ptr,
const void *uniqueId) {
// Stash a self-reference ref ptr into the python object that will
// keep the object alive. Need to get a ref ptr to the held type,
// since that's what's wrapped.
Tf_PyAddPythonOwnership(ptr, uniqueId, self.ptr());
}
};
template <typename CLS, typename T>
void Install(object const &self, T const &t, TfErrorMark const &m) {
// Stick the weakptr into the python object self to complete
// construction.
typedef typename CLS::metadata::holder Holder;
typedef typename bp::objects::instance<Holder> instance_t;
typedef InstallPolicy<T> Policy;
typedef typename CLS::metadata::held_type HeldType;
// CODE_COVERAGE_OFF
void *memory = Holder::
// CODE_COVERAGE_ON
allocate(self.ptr(), offsetof(instance_t, storage), sizeof(Holder));
try {
HeldType held(t);
Holder *holder = (new (memory) Holder(held));
// If there was a TfError, raise that back to python.
if (TfPyConvertTfErrorsToPythonException(m))
bp::throw_error_already_set();
// If no TfError, but object construction failed, raise a generic error
// back to python.
if (!held)
TfPyThrowRuntimeError("could not construct " +
ArchGetDemangled(typeid(HeldType)));
bp::detail::initialize_wrapper(self.ptr(), &(*(held.operator->())));
holder->install(self.ptr());
// Set object identity
Tf_PySetPythonIdentity(held, self.ptr());
Policy::PostInstall(self, t, held.GetUniqueIdentifier());
} catch(...) {
Holder::deallocate(self.ptr(), memory); throw;
}
}
template <typename WeakPtr, typename P>
struct _RefPtrFactoryConverter {
typedef typename boost::remove_reference<P>::type Ptr;
bool convertible() const {
// FIXME should actually check here... It's not really horrible because
// if the conversion will fail, we'll just get a runtime error down
// below when we try to create the resulting object. That's basically
// what we want anyway.
return true;
}
PyObject *operator()(Ptr const &p) const {
typedef InstallPolicy<Ptr> Policy;
WeakPtr ptr(static_cast<typename WeakPtr::DataType *>
(get_pointer(p)));
// If resulting pointer is null, return None.
if (!ptr)
return bp::incref(Py_None);
// The to-python converter will set identity here.
object result(ptr);
Policy::PostInstall(result, p, ptr.GetUniqueIdentifier());
return bp::incref(result.ptr());
}
// Required for boost.python signature generator, in play when
// BOOST_PYTHON_NO_PY_SIGNATURES is undefined.
PyTypeObject const *get_pytype() const {
return boost::python::objects::registered_class_object(
boost::python::type_id<typename WeakPtr::DataType>()).get();
}
};
template <typename WeakPtr = void>
struct RefPtrFactory {
template <typename FactoryResultPtr>
struct apply {
typedef typename boost::mpl::if_<boost::is_same<WeakPtr, void>,
TfWeakPtr<typename FactoryResultPtr::DataType>,
WeakPtr>::type WeakPtrType;
typedef _RefPtrFactoryConverter<WeakPtrType, FactoryResultPtr> type;
};
};
template <typename SIG>
struct CtorBase {
typedef SIG Sig;
static Sig *_func;
static void SetFunc(Sig *func) {
if (!_func)
_func = func;
else {
// CODE_COVERAGE_OFF
TF_CODING_ERROR("Ctor with signature '%s' is already registered. "
"Duplicate will be ignored.",
ArchGetDemangled(typeid(Sig)).c_str());
// CODE_COVERAGE_ON
}
}
};
template <typename SIG> SIG *CtorBase<SIG>::_func = 0;
// The following preprocessor code repeatedly includes this file to generate
// specializations of Ctor taking 0 through TF_MAX_ARITY parameters.
template <typename SIG> struct InitCtor;
template <typename SIG> struct InitCtorWithBackReference;
template <typename SIG> struct InitCtorWithVarArgs;
template <typename SIG> struct NewCtor;
template <typename SIG> struct NewCtorWithClassReference;
#define BOOST_PP_ITERATION_LIMITS (0, TF_MAX_ARITY)
#define BOOST_PP_FILENAME_1 "pxr/base/tf/makePyConstructor.h"
#include BOOST_PP_ITERATE()
/* comment needed for scons dependency scanner
#include "pxr/base/tf/makePyConstructor.h"
*/
}
template <typename T>
Tf_MakePyConstructor::InitVisitor
<typename Tf_MakePyConstructor::InitCtor<T> >
TfMakePyConstructor(T *func, const std::string &doc = std::string()) {
// Instantiate to set static constructor pointer, then return the visitor.
Tf_MakePyConstructor::InitCtor<T> Ctor(func);
return Tf_MakePyConstructor::InitVisitor
<Tf_MakePyConstructor::InitCtor<T> >(doc);
}
template <typename T>
Tf_MakePyConstructor::InitVisitor
<typename Tf_MakePyConstructor::InitCtorWithBackReference<T> >
TfMakePyConstructorWithBackReference(T *func, const std::string &doc = std::string()) {
// Instantiate to set static constructor pointer, then return the visitor.
Tf_MakePyConstructor::InitCtorWithBackReference<T> Ctor(func);
return Tf_MakePyConstructor::InitVisitor
<Tf_MakePyConstructor::InitCtorWithBackReference<T> >(doc);
}
template <typename T>
Tf_MakePyConstructor::InitVisitor
<typename Tf_MakePyConstructor::InitCtorWithVarArgs<T> >
TfMakePyConstructorWithVarArgs(T *func, const std::string &doc = std::string()) {
// Instantiate to set static constructor pointer, then return the visitor.
Tf_MakePyConstructor::InitCtorWithVarArgs<T> Ctor(func);
return Tf_MakePyConstructor::InitVisitor
<Tf_MakePyConstructor::InitCtorWithVarArgs<T> >(doc);
}
template <typename T>
Tf_MakePyConstructor::NewVisitor
<typename Tf_MakePyConstructor::NewCtor<T> >
TfMakePyNew(T *func, const std::string &doc = std::string()) {
// Instantiate to set static constructor pointer, then return the visitor.
Tf_MakePyConstructor::NewCtor<T> Ctor(func);
return Tf_MakePyConstructor::NewVisitor
<Tf_MakePyConstructor::NewCtor<T> >(doc);
}
template <typename T>
Tf_MakePyConstructor::NewVisitor
<typename Tf_MakePyConstructor::NewCtorWithClassReference<T> >
TfMakePyNewWithClassReference(T *func, const std::string &doc = std::string()) {
// Instantiate to set static constructor pointer, then return the visitor.
Tf_MakePyConstructor::NewCtorWithClassReference<T> Ctor(func);
return Tf_MakePyConstructor::NewVisitor
<Tf_MakePyConstructor::NewCtorWithClassReference<T> >(doc);
}
template <typename T = void>
struct TfPyRefPtrFactory : public Tf_MakePyConstructor::RefPtrFactory<T> {};
template <typename T> struct Tf_PySequenceToListConverterRefPtrFactory;
/// A \c boost::python result converter generator which converts standard
/// library sequences to lists of python owned objects.
struct TfPySequenceToListRefPtrFactory {
template <typename T>
struct apply {
typedef Tf_PySequenceToListConverterRefPtrFactory<T> type;
};
};
// XXX: would be nicer to be able to compose converters with factory
template <typename T>
struct Tf_PySequenceToListConverterRefPtrFactory {
typedef typename boost::remove_reference<T>::type SeqType;
bool convertible() const {
return true;
}
PyObject *operator()(T seq) const {
using namespace boost::python;
typedef typename Tf_MakePyConstructor::RefPtrFactory<>::
apply<typename SeqType::value_type>::type RefPtrFactory;
boost::python::list l;
for (typename SeqType::const_iterator i = seq.begin();
i != seq.end(); ++i) {
l.append(object(handle<>(RefPtrFactory()(*i))));
}
return boost::python::incref(l.ptr());
}
// Required for boost.python signature generator, in play when
// BOOST_PYTHON_NO_PY_SIGNATURES is undefined.
PyTypeObject const *get_pytype() const {
return &PyList_Type;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_MAKE_PY_CONSTRUCTOR_H
#else // BOOST_PP_IS_ITERATING
#define N BOOST_PP_ITERATION()
#define SIGNATURE R (BOOST_PP_ENUM_PARAMS(N, A))
#define PARAMLIST BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, A, a)
#define ARGLIST BOOST_PP_ENUM_PARAMS(N, a)
// This generates multi-argument specializations for Tf_MakePyConstructor::Ctor.
// One nice thing about this style of PP repetition is that the debugger will
// actually step you over these lines for any instantiation of Ctor.
template <typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct InitCtor<SIGNATURE> : CtorBase<SIGNATURE> {
typedef CtorBase<SIGNATURE> Base;
typedef typename Base::Sig Sig;
InitCtor(Sig *func) { Base::SetFunc(func); }
template <typename CLS>
static bp::object init_callable() {
return bp::make_function(__init__<CLS>);
}
template <typename CLS, typename Options>
static bp::object init_callable(Options& o) {
return bp::make_function(__init__<CLS>, o.policies(), o.keywords()) ;
}
template <typename CLS>
static void __init__(object &self PARAMLIST) {
TfErrorMark m;
Install<CLS>(self, Base::_func(ARGLIST), m);
}
};
template <typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct NewCtor<SIGNATURE> : CtorBase<SIGNATURE> {
typedef CtorBase<SIGNATURE> Base;
typedef typename Base::Sig Sig;
NewCtor(Sig *func) { Base::SetFunc(func); }
template <class CLS>
static bp::object __new__(object &cls PARAMLIST) {
typedef typename CLS::metadata::held_type HeldType;
TfErrorMark m;
R r((Base::_func(ARGLIST)));
HeldType h((r));
if (TfPyConvertTfErrorsToPythonException(m))
bp::throw_error_already_set();
bp::object ret = TfPyObject(h);
if (TfPyIsNone(ret))
TfPyThrowRuntimeError("could not construct " +
ArchGetDemangled(typeid(HeldType)));
bp::detail::initialize_wrapper(ret.ptr(), get_pointer(h));
// make the object have the right class.
bp::setattr(ret, "__class__", cls);
InstallPolicy<R>::PostInstall(ret, r, h.GetUniqueIdentifier());
return ret;
}
};
#define VAR_SIGNATURE \
R (BOOST_PP_ENUM_PARAMS(N, A) BOOST_PP_COMMA_IF(N) \
const bp::tuple&, const bp::dict&)
#define FORMAT_STR(z, n, data) "%s, "
#define ARG_TYPE_STR_A(z, n, data) bp::type_id<A##n>().name()
#define EXTRACT_REQ_ARG_A(z, n, data) \
/* The n'th required arg is stored at n + 1 in the positional args */ \
/* tuple as the 0'th element is always the self object */ \
bp::extract<typename boost::remove_reference<A##n>::type>(data[n + 1])
template <typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct InitCtorWithVarArgs<VAR_SIGNATURE> : CtorBase<VAR_SIGNATURE> {
typedef CtorBase<VAR_SIGNATURE> Base;
typedef typename Base::Sig Sig;
InitCtorWithVarArgs(Sig *func) { Base::SetFunc(func); }
template <typename CLS>
static bp::object init_callable() {
// Specify min_args as 1 to account for just the 'self' argument.
// min_args really should be N + 1. However, we want to do this check
// ourselves later so we can emit a better error message.
return bp::raw_function(__init__<CLS>, /* min_args = */ 1);
}
template <typename CLS, typename Options>
static bp::object init_callable(Options& options) {
// XXX: Note ignoring options.keywords(), current implementation can't
// handle that correctly.
return bp::raw_function(
bp::make_function(__init__<CLS>, options.policies()),
/* min_args = */ 1);
}
template <typename CLS>
static bp::object __init__(const bp::tuple& args, const bp::dict& kwargs) {
TfErrorMark m;
const unsigned int numArgs = bp::len(args);
if (numArgs - 1 < N) {
// User didn't provide enough positional arguments for the factory
// function. Complain.
TfPyThrowTypeError(
TfStringPrintf(
"Arguments to __init__ did not match C++ signature:\n"
"\t__init__(" BOOST_PP_REPEAT(N, FORMAT_STR, 0) "...)"
BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM(N, ARG_TYPE_STR_A, 0)
)
);
return bp::object();
}
Install<CLS>(
// self object for new instance is the first arg to __init__
args[0],
// Slice the first N arguments from positional arguments as
// those are the required arguments for the factory function.
Base::_func(
BOOST_PP_ENUM(N, EXTRACT_REQ_ARG_A, args) BOOST_PP_COMMA_IF(N)
bp::tuple(args.slice(N + 1, numArgs)), kwargs),
m);
return bp::object();
}
};
#if N > 0
#undef PARAMLIST
#define PARAMLIST BOOST_PP_ENUM_BINARY_PARAMS(N, A, a)
// This is a variant of Ctor which includes a back reference to self
// (the Python object being initialized) in the args passed to the
// constructor. This is used to expose the factory methods for classes
// which we expect to subclass in Python. When the constructor is called,
// it can examine self and initialize itself appropriately.
template <typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct InitCtorWithBackReference<SIGNATURE> : CtorBase<SIGNATURE> {
typedef CtorBase<SIGNATURE> Base;
typedef typename Base::Sig Sig;
InitCtorWithBackReference(Sig *func) { Base::SetFunc(func); }
template <typename CLS>
static bp::object init_callable() {
return bp::make_function(__init__<CLS>);
}
template <typename CLS, typename Options>
static bp::object init_callable(Options& o) {
return bp::make_function(__init__<CLS>, o.policies(), o.keywords());
}
template <typename CLS>
static void __init__(PARAMLIST) {
TfErrorMark m;
Install<CLS>(a0, Base::_func(ARGLIST), m);
}
};
template <typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct NewCtorWithClassReference<SIGNATURE> : CtorBase<SIGNATURE> {
typedef CtorBase<SIGNATURE> Base;
typedef typename Base::Sig Sig;
NewCtorWithClassReference(Sig *func) { Base::SetFunc(func); }
template <class CLS>
static bp::object __new__(PARAMLIST) {
typedef typename CLS::metadata::held_type HeldType;
TfErrorMark m;
R r(Base::_func(ARGLIST));
HeldType h(r);
if (TfPyConvertTfErrorsToPythonException(m))
bp::throw_error_already_set();
bp::object ret = TfPyObject(h);
if (TfPyIsNone(ret))
TfPyThrowRuntimeError("could not construct " +
ArchGetDemangled(typeid(HeldType)));
bp::detail::initialize_wrapper(ret.ptr(), get_pointer(h));
// make the object have the right class.
bp::setattr(ret, "__class__", a0);
InstallPolicy<R>::PostInstall(ret, r, h.GetUniqueIdentifier());
return ret;
}
};
#endif
#undef N
#undef SIGNATURE
#undef PARAMLIST
#undef ARGLIST
#undef VAR_SIGNATURE
#undef FORMAT_STR
#undef ARG_TYPE_STR_A
#undef EXTRACT_REQ_ARG_A
#endif // BOOST_PP_IS_ITERATING
+580
View File
@@ -0,0 +1,580 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_MALLOC_TAG_H
#define PXR_BASE_TF_MALLOC_TAG_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <cstdlib>
#include <iosfwd>
#include <stdint.h>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \file tf/mallocTag.h
/// \ingroup group_tf_MallocTag
struct Tf_MallocPathNode;
/// \class TfMallocTag
/// \ingroup group_tf_MallocTag
///
/// Top-down memory tagging system.
///
/// See \ref page_tf_MallocTag for a detailed description.
class TfMallocTag {
public:
struct CallStackInfo;
/// \struct CallTree
/// Summary data structure for \c malloc statistics.
///
/// The \c CallTree structure is used to deliver a snapshot of the current
/// malloc usage. It is accessible as publicly modifiable data because it
/// is simply a returned snapshot of the current memory state.
struct CallTree {
/// \struct PathNode
/// Node in the call tree structure.
///
/// A \c PathNode captures the hierarchy of active \c TfAutoMallocTag
/// objects that are pushed and popped during program execution. Each
/// \c PathNode thus describes a sequence of call-sites (i.e. a path
/// down the call tree). Repeated call sites (in the case of
/// co-recursive function calls) can be skipped, e.g. pushing tags
/// "A", "B", "C", "B", "C" leads to only three path-nodes,
/// representing the paths "A", "AB", and "ABC". Allocations done at
/// the bottom (i.e. when tags "A", "B", "C", "B", "C" are all active)
/// are billed to the longest path node in the sequence, which
/// corresponds to the path "ABC").
///
/// Path nodes track both the memory they incur directly (\c
/// nBytesDirect) but more importantly, the total memory allocated by
/// themselves and any of their children (\c nBytes). The name of a
/// node (\c siteName) corresponds to the tag name of the final tag in
/// the path.
struct PathNode {
size_t nBytes, ///< Allocated bytes by this or descendant nodes.
nBytesDirect; ///< Allocated bytes (only for this node).
size_t nAllocations; ///< The number of allocations for this node.
std::string siteName; ///< Tag name.
std::vector<PathNode>
children; ///< Children nodes.
};
/// \struct CallSite
/// Record of the bytes allocated under each different tag.
///
/// Each construction of a \c TfAutoMallocTag object with a different
/// argument produces a distinct \c CallSite record. The total bytes
/// outstanding for all memory allocations made under a given
/// call-site are recorded in \c nBytes, while the name of the call
/// site is available as \c name.
struct CallSite {
std::string name; ///< Tag name.
size_t nBytes; ///< Allocated bytes.
};
// Note: enum below must be kept in sync with tfmodule/mallocCallTree.h
/// Specify which parts of the report to print.
enum PrintSetting {
TREE = 0, ///< Print the full call tree
CALLSITES, ///< Print just the call sites > 0.1%
BOTH ///< Print both tree and call sites
};
/// Return the malloc report string.
///
/// Get a malloc report of the tree and/or callsites.
///
/// The columns in the report are abbreviated. Here are the definitions.
///
/// \b TAGNAME : The name of the tag being tracked. This matches the
/// string argument to TfAutoMallocTag constructor.
///
/// \b BytesIncl : Bytes Inclusive. This includes all bytes allocated by
/// this tag and any bytes of its children.
///
/// \b BytesExcl : Bytes Exclusive. Only bytes allocated exclusively by
/// this tag, not including any bytes of its children.
///
/// \b %%Prnt : (%% Parent). me.BytesIncl / parent.BytesIncl * 100
///
/// \b %%Exc : BytesExcl / BytesIncl * 100
///
/// \b %%Totl : (%% Total). BytesExcl / TotalBytes * 100
TF_API
std::string GetPrettyPrintString(PrintSetting setting = BOTH,
size_t maxPrintedNodes = 100000) const;
/// Generates a report to the ostream \p out.
///
/// This report is printed in a way that is intended to be used by
/// xxtracediff. If \p rootName is non-empty it will replace the name
/// of the tree root in the report.
TF_API
void Report(
std::ostream &out,
const std::string &rootName) const;
/// \overload
TF_API
void Report(
std::ostream &out) const;
/// All call sites.
std::vector<CallSite> callSites;
/// Root node of the call-site hierarchy.
PathNode root;
/// The captured malloc stacks.
std::vector<CallStackInfo> capturedCallStacks;
};
/// \struct CallStackInfo
/// This struct is used to represent a call stack taken for an allocation
/// that was billed under a specific malloc tag.
struct CallStackInfo
{
/// The stack frame pointers.
std::vector<uintptr_t> stack;
/// The amount of allocated memory (accumulated over all allocations
/// sharing this call stack).
size_t size;
/// The number of allocations (always one unless stack frames have
/// been combined to create unique stacks).
size_t numAllocations;
};
/// Initialize the memory tagging system.
///
/// This function returns \c true if the memory tagging system can be
/// successfully initialized or it has already been initialized. Otherwise,
/// \p *errMsg is set with an explanation for the failure.
///
/// Until the system is initialized, the various memory reporting calls
/// will indicate that no memory has been allocated. Note also that
/// memory allocated prior to calling \c Initialize() is not tracked i.e.
/// all data refers to allocations that happen subsequent to calling \c
/// Initialize().
TF_API static bool Initialize(std::string* errMsg);
/// Return true if the tagging system is active.
///
/// If \c Initialize() has been successfully called, this function returns
/// \c true.
static bool IsInitialized() {
return TfMallocTag::_doTagging;
}
/// Return total number of allocated bytes.
///
/// The current total memory that has been allocated and not freed is
/// returned. Memory allocated before calling \c Initialize() is not
/// accounted for.
TF_API static size_t GetTotalBytes();
/// Return the maximum total number of bytes that have ever been allocated
/// at one time.
///
/// This is simply the maximum value of GetTotalBytes() since Initialize()
/// was called.
TF_API static size_t GetMaxTotalBytes();
/// Return a snapshot of memory usage.
///
/// Returns a snapshot by writing into \c *tree. See the \c C *tree
/// structure for documentation. If \c Initialize() has not been called,
/// \ *tree is set to a rather blank structure (empty vectors, empty
/// strings, zero in all integral fields) and \c false is returned;
/// otherwise, \p *tree is set with the contents of the current memory
/// snapshot and \c true is returned. It is fine to call this function on
/// the same \p *tree instance; each call simply overwrites the data from
/// the last call. If /p skipRepeated is \c true, then any repeated
/// callsite is skipped. See the \c CallTree documentation for more
/// details.
TF_API static bool GetCallTree(CallTree* tree, bool skipRepeated = true);
private:
// Enum describing whether allocations are being tagged in an associated
// thread.
enum _Tagging {
_TaggingEnabled, // Allocations are being tagged
_TaggingDisabled, // Allocations are not being tagged
_TaggingDormant // Tagging has not been initialized in this
// thread as no malloc tags have been pushed onto
// the stack.
};
struct _ThreadData;
public:
/// \class Auto
/// \ingroup group_tf_MallocTag
///
/// Scoped (i.e. local) object for creating/destroying memory tags.
///
/// Note: \c TfAutoMallocTag is a typedef to \c TfMallocTag::Auto; the
/// convention is to use \c TfAutoMallocTag to make it clear that the
/// local object exists only because its constructor and destructor modify
/// program state.
///
/// A \c TfAutoMallocTag object is used to push a memory tag onto the
/// current call stack; destruction of the object pops the call stack.
/// Note that each thread has its own call-stack.
///
/// There is no (measurable) cost to creating or destroying memory tags if
/// \c TfMallocTag::Initialize() has not been called; if it has, then
/// there is a small (but measurable) cost associated with pushing and
/// popping memory tags on the local call stack. Most of the cost is
/// simply locking a mutex; typically, pushing or popping the call stack
/// does not actually cause any memory allocation unless this is the first
/// time that the given named tag has been encountered.
class Auto {
public:
Auto(const Auto &) = delete;
Auto& operator=(const Auto &) = delete;
Auto(Auto &&) = delete;
Auto& operator=(Auto &&) = delete;
/// Push a memory tag onto the local-call stack with name \p name.
///
/// If \c TfMallocTag::Initialize() has not been called, this
/// constructor does essentially no (measurable) work, assuming \p
/// name is a string literal or just a pointer to an existing string.
///
/// Objects of this class should only be created as local variables;
/// never as member variables, global variables, or via \c new. If
/// you can't create your object as a local variable, you can make
/// manual calls to \c TfMallocTag::Push() and \c TfMallocTag::Pop(),
/// though you should do this only as a last resort.
Auto(const char* name) : _threadData(0) {
if (TfMallocTag::_doTagging)
_Begin(name);
}
/// Push a memory tag onto the local-call stack with name \p name.
///
/// If \c TfMallocTag::Initialize() has not been called, this
/// constructor does essentially no (measurable) work. However, any
/// work done in constructing the \c std::string object \p name will
/// be incurred even if tagging is not active. If this is an issue,
/// you can query \c TfMallocTag::IsInitialized() to avoid unneeded
/// work when tagging is inactive. Note that the case when \p name is
/// a string literal does not apply here: instead, the constructor that
/// takes a \c const \c char* (above) will be called.
///
/// Objects of this class should only be created as local variables;
/// never as member variables, global variables, or via \c new. If
/// you can't create your object as a local variable, you can make
/// manual calls to \c TfMallocTag::Push() and \c TfMallocTag::Pop(),
/// though you should do this only as a last resort.
Auto(const std::string& name) : _threadData(0) {
if (TfMallocTag::_doTagging)
_Begin(name);
}
/// Pop the tag from the stack before it is destructed.
///
/// Normally you should not use this. The normal destructor is
/// preferable because it insures proper release order. If you call
/// \c Release(), make sure all tags are released in the opposite
/// order they were declared in. It is better to use sub-scopes to
/// control the life span of tags, but if that won't work, \c
/// Release() is still preferable to \c TfMallocTag::Push() and \c
/// TfMallocTag::Pop() because it isn't vulnerable to early returns or
/// exceptions.
inline void Release() {
if (_threadData) {
_End();
_threadData = NULL;
}
}
/// Pop a memory tag from the local-call stack.
///
/// If \c TfMallocTag::Initialize() was not called when this tag was
/// pushed onto the stack, popping the tag from the stack does
/// essentially no (measurable) work.
inline ~Auto() {
Release();
}
private:
TF_API void _Begin(const char* name);
TF_API void _Begin(const std::string& name);
TF_API void _End();
_ThreadData* _threadData;
friend class TfMallocTag;
};
/// \class Auto2
/// \ingroup group_tf_MallocTag
///
/// Scoped (i.e. local) object for creating/destroying memory tags.
///
/// Auto2 is just like Auto, except it pushes two tags onto the stack.
class Auto2 {
public:
/// Push two memory tags onto the local-call stack.
///
/// \see TfMallocTag::Auto(const char* name).
Auto2(const char* name1, const char* name2) :
_tag1(name1),
_tag2(name2)
{
}
/// Push two memory tags onto the local-call stack.
///
/// \see TfMallocTag::Auto(const std::string& name).
Auto2(const std::string& name1, const std::string& name2) :
_tag1(name1),
_tag2(name2)
{
}
/// Pop two memory tags from the local-call stack.
///
/// \see TfMallocTag::Auto(const char* name).
void Release() {
_tag2.Release();
_tag1.Release();
}
private:
Auto _tag1;
Auto _tag2;
};
/// Manually push a tag onto the stack.
///
/// This call has the same effect as the constructor for \c
/// TfMallocTag::Auto (aka \c TfAutoMallocTag), however a matching call to
/// \c Pop() is required.
///
/// Note that initializing the tagging system between matching calls to \c
/// Push() and \c Pop() is ill-advised, which is yet another reason to
/// prefer using \c TfAutoMallocTag whenever possible.
static void Push(const std::string& name) {
TfMallocTag::Auto noname(name);
noname._threadData = NULL; // disable destructor
}
/// \overload
static void Push(const char* name) {
TfMallocTag::Auto noname(name);
noname._threadData = NULL; // disable destructor
}
/// Manually pop a tag from the stack.
///
/// This call has the same effect as the destructor for \c
/// TfMallocTag::Auto; it must properly nest with a matching call to \c
/// Push(), of course.
///
/// If \c name is supplied and does not match the tag at the top of the
/// stack, a warning message is issued.
TF_API static void Pop(const char* name = NULL);
/// \overload
static void Pop(const std::string& name) {
Pop(name.c_str());
}
/// Sets the tags to trap in the debugger.
///
/// When memory is allocated or freed for any tag that matches \p
/// matchList the debugger trap is invoked. If a debugger is attached the
/// program will stop in the debugger, otherwise the program will continue
/// to run. See \c ArchDebuggerTrap() and \c ArchDebuggerWait().
///
/// \p matchList is a comma, tab or newline separated list of malloc tag
/// names. The names can have internal spaces but leading and trailing
/// spaces are stripped. If a name ends in '*' then the suffix is
/// wildcarded. A name can have a leading '-' or '+' to prevent or allow a
/// match. Each name is considered in order and later matches override
/// earlier matches. For example, 'Csd*, -CsdScene::_Populate*,
/// +CsdScene::_PopulatePrimCacheLocal' matches any malloc tag starting
/// with 'Csd' but nothing starting with 'CsdScene::_Populate' except
/// 'CsdScene::_PopulatePrimCacheLocal'. Use the empty string to disable
/// debugging traps.
TF_API static void SetDebugMatchList(const std::string& matchList);
/// Sets the tags to trace.
///
/// When memory is allocated for any tag that matches \p matchList a stack
/// trace is recorded. When that memory is released the stack trace is
/// discarded. Clients can call \c GetCapturedMallocStacks() to get a
/// list of all recorded stack traces. This is useful for finding leaks.
///
/// Traces recorded for any tag that will no longer be matched are
/// discarded by this call. Traces recorded for tags that continue to be
/// matched are retained.
///
/// \p matchList is a comma, tab or newline separated list of malloc tag
/// names. The names can have internal spaces but leading and trailing
/// spaces are stripped. If a name ends in '*' then the suffix is
/// wildcarded. A name can have a leading '-' or '+' to prevent or allow
/// a match. Each name is considered in order and later matches override
/// earlier matches. For example, 'Csd*, -CsdScene::_Populate*,
/// +CsdScene::_PopulatePrimCacheLocal' matches any malloc tag starting
/// with 'Csd' but nothing starting with 'CsdScene::_Populate' except
/// 'CsdScene::_PopulatePrimCacheLocal'. Use the empty string to disable
/// stack capturing.
TF_API static void SetCapturedMallocStacksMatchList(const std::string& matchList);
/// Returns the captured malloc stack traces for allocations billed to the
/// malloc tags passed to SetCapturedMallocStacksMatchList().
///
/// \note This method also clears the internally held set of captured
/// stacks.
TF_API static std::vector<std::vector<uintptr_t> > GetCapturedMallocStacks();
private:
friend struct Tf_MallocGlobalData;
class _TemporaryTaggingState {
public:
explicit _TemporaryTaggingState(_Tagging state);
~_TemporaryTaggingState();
_TemporaryTaggingState(const _TemporaryTaggingState &);
_TemporaryTaggingState& operator=(const _TemporaryTaggingState &);
_TemporaryTaggingState(_TemporaryTaggingState &&);
_TemporaryTaggingState& operator=(_TemporaryTaggingState &&);
private:
_Tagging _oldState;
};
static void _SetTagging(_Tagging state);
static _Tagging _GetTagging();
static bool _Initialize(std::string* errMsg);
static inline bool _ShouldNotTag(_ThreadData**, _Tagging* t = NULL);
static inline Tf_MallocPathNode* _GetCurrentPathNodeNoLock(
const _ThreadData* threadData);
static void* _MallocWrapper_ptmalloc(size_t, const void*);
static void* _ReallocWrapper_ptmalloc(void*, size_t, const void*);
static void* _MemalignWrapper_ptmalloc(size_t, size_t, const void*);
static void _FreeWrapper_ptmalloc(void*, const void*);
static void* _MallocWrapper(size_t, const void*);
static void* _ReallocWrapper(void*, size_t, const void*);
static void* _MemalignWrapper(size_t, size_t, const void*);
static void _FreeWrapper(void*, const void*);
friend class TfMallocTag::Auto;
class Tls;
friend class TfMallocTag::Tls;
TF_API static bool _doTagging;
};
/// Top-down memory tagging system.
typedef TfMallocTag::Auto TfAutoMallocTag;
/// Top-down memory tagging system.
typedef TfMallocTag::Auto2 TfAutoMallocTag2;
/// Enable lib/tf memory management.
///
/// Invoking this macro inside a class body causes the class operator \c new to push
/// two \c TfAutoMallocTag objects onto the stack before actually allocating memory for the
/// class. The names passed into the tag are used for the two tags; pass NULL if you
/// don't need the second tag. For example,
/// \code
/// class MyBigMeshVertex {
/// public:
/// TF_MALLOC_TAG_NEW("MyBigMesh", "Vertex");
/// ...
/// }
/// \endcode
/// will cause dynamic allocations of \c MyBigMeshVertex to be grouped under
/// the tag \c Vertex which is in turn grouped under \c MyBigMesh. However,
/// \code
/// class MyBigMesh {
/// public:
/// TF_MALLOC_TAG_NEW("MyBigMesh", NULL);
/// ...
/// }
/// \endcode
/// specifies \c NULL for the second tag because the first tag is sufficient.
///
/// Normally, this macro should be placed in the public section of a class.
/// Note that you cannot specify both this and \c TF_FIXED_SIZE_ALLOCATOR()
/// for the same class.
///
/// Also, note that allocations of a class inside an STL datastructure will
/// not be grouped under the indicated tags.
/// \remark Placed in .h files.
///
/// \hideinitializer
//
PXR_NAMESPACE_CLOSE_SCOPE
#define TF_MALLOC_TAG_NEW(name1, name2) \
/* this is for STL purposes */ \
inline void* operator new(::std::size_t, void* ptr) { \
return ptr; \
} \
\
inline void* operator new(::std::size_t s) { \
PXR_NS::TfAutoMallocTag tag1(name1); \
PXR_NS::TfAutoMallocTag tag2(name2); \
return malloc(s); \
} \
\
inline void* operator new[](::std::size_t s) { \
PXR_NS::TfAutoMallocTag tag1(name1); \
PXR_NS::TfAutoMallocTag tag2(name2); \
return malloc(s); \
} \
\
/* Required due to the placement-new override above. */ \
inline void operator delete(void* ptr, void* place) {} \
\
inline void operator delete(void* ptr, size_t) { \
free(ptr); \
} \
\
inline void operator delete[] (void* ptr, size_t) { \
free(ptr); \
} \
#endif
+792
View File
@@ -0,0 +1,792 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_NOTICE_H
#define PXR_BASE_TF_NOTICE_H
/// \file tf/notice.h
/// \ingroup group_tf_Notification
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/anyWeakPtr.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/arch/hints.h"
#include <list>
#include <typeinfo>
PXR_NAMESPACE_OPEN_SCOPE
class Tf_NoticeRegistry;
/// \class TfNotice
/// \ingroup group_tf_Notification
///
/// The base class for objects used to notify interested parties (listeners)
/// when events have occurred. The TfNotice class also serves as a container
/// for various dispatching routines such as Register() and Send().
///
/// See \ref page_tf_Notification in the C++ API reference for a detailed
/// description of the notification system.
///
/// \section pycode_TfNotice Python Example: Registering For and Sending
/// Notices The following code provides examples of how to set up a Notice
/// listener connection (represented in Python by the Listener class),
/// including creating and sending notices, registering to receive notices,
/// and breaking a listener connection.
/// \code{.py}
/// # To create a new notice type:
/// class APythonClass(Tf.Notice):
/// '''TfNotice sent when APythonClass does something of interest.'''
/// pass
/// Tf.Type.Define(APythonClass)
///
/// # An interested listener can register to receive notices from all
/// # senders, or from a particular type of sender.
///
/// # To send a notice to all registered listeners:;
/// APythonClass().SendGlobally()
///
/// # To send a notice to listeners who register with a specific sender:
/// APythonClass().Send(self)
///
/// # To register for the notice from any sender:
/// my_listener = Tf.Notice.RegisterGlobally(APythonClass, self._HandleNotice)
///
/// # To register for the notice from a specific sender
/// my_listener = Tf.Notice.Register(APythonClass, self._HandleNotice, sender)
///
/// def _HandleNotice(self, notice, sender):
/// '''callback function for handling a notice'''
/// # do something when the notice arrives
///
/// # To revoke interest in a notice
/// my_listener.Revoke()
/// \endcode
///
/// For more on using notices in Python, see the Editor With Notices tutorial.
///
class TfNotice {
private:
class _DelivererBase;
typedef TfWeakPtr<_DelivererBase> _DelivererWeakPtr;
typedef std::list<_DelivererBase*> _DelivererList;
////////////////////////////////////////////////////////////////////////
// Per-sender delivery, listener gets sender.
template <class LPtr, class L,
class Notice, class SPtr, class DeliveredSPtr>
static _DelivererBase *
_MakeDeliverer(LPtr const &listener,
void (L::*method)
(const Notice &, DeliveredSPtr const &),
SPtr const &sender) {
DeliveredSPtr weakSender(sender);
return new _DelivererWithSender<
LPtr, DeliveredSPtr,
void (L::*)(const Notice &, DeliveredSPtr const &),
Notice
>(listener, method, weakSender);
}
template <class LPtr, class L,
class Notice, class SPtr, class DeliveredSPtr>
static _DelivererBase *
_MakeDeliverer(LPtr const &listener,
void (L::*method)
(const Notice &, DeliveredSPtr const &) const,
SPtr const &sender) {
DeliveredSPtr weakSender(sender);
return new _DelivererWithSender<
LPtr, DeliveredSPtr,
void (L::*)(const Notice &, DeliveredSPtr const &) const,
Notice
>(listener, method, weakSender);
}
////////////////////////////////////////////////////////////////////////
// Per-sender delivery, listener does not get sender.
template <class LPtr, class L, class SPtr, class Notice>
static _DelivererBase *
_MakeDeliverer(LPtr const &listener,
void (L::*method)(const Notice &),
SPtr const &sender) {
return new _Deliverer<
LPtr, SPtr, void (L::*)(const Notice &), Notice
>(listener, method, sender);
}
template <class LPtr, class L, class SPtr, class Notice>
static _DelivererBase *
_MakeDeliverer(LPtr const &listener,
void (L::*method)(const Notice &) const,
SPtr const &sender) {
return new _Deliverer<
LPtr, SPtr, void (L::*)(const Notice &) const, Notice
>(listener, method, sender);
}
////////////////////////////////////////////////////////////////////////
// Global delivery.
template <class LPtr, class L, class Notice>
static _DelivererBase *
_MakeDeliverer(LPtr const &listener,
void (L::*method)(const Notice &)) {
return new _Deliverer<
LPtr, TfAnyWeakPtr, void (L::*)(const Notice &), Notice
>(listener, method);
}
template <class LPtr, class L, class Notice>
static _DelivererBase *
_MakeDeliverer(LPtr const &listener,
void (L::*method)(const Notice &) const) {
return new _Deliverer<
LPtr, TfAnyWeakPtr, void (L::*)(const Notice &) const, Notice
>(listener, method);
}
////////////////////////////////////////////////////////////////////////
// Generic (raw) delivery.
template <class LPtr, class L>
static _DelivererBase *
_MakeDeliverer(TfType const &noticeType,
LPtr const &listener,
void (L::*method)(const TfNotice &,
const TfType &,
TfWeakBase*, const void *,
const std::type_info&),
TfAnyWeakPtr const &sender) {
return new _RawDeliverer<LPtr,
void (L::*)(const TfNotice &, const TfType &,
TfWeakBase *, const void *,
const std::type_info &)>
(listener, method, sender, noticeType);
}
template <class LPtr, class L>
static _DelivererBase *
_MakeDeliverer(TfType const &noticeType,
LPtr const &listener,
void (L::*method)(const TfNotice &,
const TfType &,
TfWeakBase*, const void *,
const std::type_info&) const,
TfAnyWeakPtr const &sender)
{
return new _RawDeliverer<LPtr,
void (L::*)(const TfNotice &, const TfType &,
TfWeakBase *, const void *,
const std::type_info &) const>
(listener, method, sender, noticeType);
}
public:
class Probe;
typedef TfWeakPtr<Probe> WeakProbePtr;
/// Probe interface class which may be implemented and then registered via
/// \c InsertProbe to introspect about notices as they are sent and
/// delivered.
class Probe : public TfWeakBase {
public:
TF_API
virtual ~Probe() = 0;
/// This method is called just before \p notice is sent to any
/// listeners. \p sender is NULL if \p notice is sent globally. In
/// this case, \p senderType will be typeid(void).
virtual void BeginSend(const TfNotice &notice,
const TfWeakBase *sender,
const std::type_info &senderType) = 0;
/// This method is called after the notice in the corresponding \c
/// BeginSend call has been delivered to all listeners.
virtual void EndSend() = 0;
/// This method is called just before \p notice is
/// delivered to a listener. \p sender is NULL if \p notice is
/// sent globally or the listener is global. In this case, \p
/// senderType will be typeid(void).
virtual void BeginDelivery(const TfNotice &notice,
const TfWeakBase *sender,
const std::type_info &senderType,
const TfWeakBase *listener,
const std::type_info &listenerType) = 0;
/// This method is called after the notice in the
/// corresponding \c BeginDelivery call has finished being
/// processed by its listener.
virtual void EndDelivery() = 0;
};
/// Handle-object returned by \c TfNotice::Register().
///
/// When a listener is registered by \c TfNotice::Register(), an object of
/// type \c TfNotice::Key is returned; this key object can be given to \c
/// Revoke() to subsequently unregister the listener with respect to that
/// particular notice type and callback method.
class Key {
public:
Key() {}
/// Does this key refer to a valid notification?
///
/// \c IsValid will return true if this key refers to a currently
/// active notification. Revoking the key will make it invalid again.
bool IsValid() const {
return _deliverer && _deliverer->_IsActive();
}
/// Does this key refer to a valid notification?
///
/// The boolean operator is identical to \c IsValid() above.
operator bool() const {
return IsValid();
}
private:
Key(const _DelivererWeakPtr & d) : _deliverer(d) {}
_DelivererWeakPtr _deliverer;
friend class Tf_NoticeRegistry;
friend class TfNotice;
};
/// A \c TfNotice::Key container.
///
/// Many listeners listen for several notices and must revoke interest for
/// those several notices at once. These listeners can put all of the
/// keys into a \c TfNotice::Keys then call \c Revoke() on it.
typedef std::vector<Key> Keys;
/// Register a probe that will be invoked when notices are sent and
/// delivered.
/// \see TfNotice::Probe
static void InsertProbe(const WeakProbePtr &probe);
/// Remove a probe that was previously registered with \c InsertProbe.
/// \see TfNotice::Probe
static void RemoveProbe(const WeakProbePtr &probe);
/// Register a listener as being interested in a \c TfNotice.
///
/// Registration of interest in a notice class \c N automatically
/// registers interest in all classes derived from \c N. When a notice of
/// appropriate type is received, the listening object's member-function
/// \p method is called with the notice.
///
/// Supports several forms of registration.
///
/// - Listening for a notice from a particular sender.
///
/// \code
/// // Listener does not receive sender.
/// void Listener::_HandleNotice(SomeNotice const &notice) [const];
/// Register(listenerPtr, &Listener::_HandleNotice, senderPtr);
///
/// // Listener receives sender.
/// void Listener::_HandleNoticeSender(SomeNotice const &notice,
/// SenderPtr const &sender) [const];
/// Register(listenerPtr, &Listener::_HandleNoticeSender, senderPtr);
/// \endcode
///
/// - Listening for a notice globally. Prefer listening to a notice from a
/// particular sender whenever possible (as above).
///
/// \code
/// void Listener::_HandleGlobalNotice(SomeNotice const &notice) [const];
/// Register(listenerPtr, &Listener::_HandleGlobalNotice);
/// \endcode
///
/// - Listening for a notice dynamically, with a type that is unknown at
/// compile-time. This facility is used for some internal mechanisms,
/// such as bridging notice delivery into Python, and is not meant for
/// public consumption.
///
/// \code
/// void Listener::_HandleGenericNotice(TfNotice const &notice,
/// TfType const &noticeType,
/// TfWeakBase *sender,
/// void const *senderUniqueId,
/// std::type_info const &senderType)
/// [const];
/// Register(listenerPtr,
/// &Listener::_HandleGenericNotice, noticeType, senderPtr);
/// \endcode
///
/// The listener being registered must be pointed to by a \c
/// TfWeakPtrFacade, like a TfWeakPtr or another TfWeakPtrFacade-based
/// Handle. The sender being registered for (if any) must also be pointed
/// to by a \c TfWeakPtrFacade.
///
/// Note that the notification center only holds onto the listening object
/// via a \c TfWeakPtr. That is, it does not influence the lifetime of
/// that object.
///
/// To reverse the registration, call \c Key::Revoke() on the \c Key
/// object returned by this call.
template <class LPtr, class MethodPtr>
static TfNotice::Key
Register(LPtr const &listener, MethodPtr method) {
return _Register(_MakeDeliverer(listener, method));
}
template <class LPtr, class MethodPtr, class SenderPtr>
static TfNotice::Key
Register(LPtr const &listener, MethodPtr method, SenderPtr const &sender) {
return _Register(_MakeDeliverer(listener, method, sender));
}
template <class LPtr, class MethodPtr>
static TfNotice::Key
Register(LPtr const &listener, MethodPtr method,
const TfType &noticeType, const TfAnyWeakPtr &sender) {
return _Register(_MakeDeliverer(noticeType, listener, method, sender));
}
/// Revoke interest by a listener.
///
/// This revokes interest by the listener for the particular notice type
/// and call-back method for which this key was created.
///
/// \c Revoke will return a bool value indicating whether or not the key
/// was successfully revoked. Subsequent calls to \c Revoke with the same
/// key will return false.
TF_API
static bool Revoke(TfNotice::Key& key);
/// Revoke interest by listeners.
///
/// This revokes interest by the listeners for the particular
/// notice types and call-back methods for which the keys were
/// created. It then clears the keys container.
TF_API
static void Revoke(TfNotice::Keys* keys);
/// Deliver the notice to interested listeners, returning the number
/// of interested listeners.
///
/// For most clients it is recommended to use the Send(sender) version of
/// Send() rather than this one. Clients that use this form of Send
/// will prevent listeners from being able to register to receive notices
/// based on the sender of the notice.
///
/// ONLY listeners that registered globally will get the notice.
///
/// Listeners are invoked synchronously and in arbitrary order. The value
/// returned is the total number of times the notice was sent to listeners.
/// Note that a listener is called in the thread in which \c Send() is called
/// and \e not necessarily in the thread that \c Register() was called in.
TF_API
size_t Send() const;
/// Deliver the notice to interested listeners, returning the number of
/// interested listeners.
///
/// This is the recommended form of Send. It takes the sender as an
/// argument.
///
/// Listeners that registered for the given sender AND listeners that
/// registered globally will get the notice.
///
/// Listeners are invoked synchronously and in arbitrary order. The value
/// returned is the total number of times the notice was sent to
/// listeners. Note that a listener is called in the thread in which \c
/// Send() is called and \e not necessarily in the thread that \c
/// Register() was called in.
template <typename SenderPtr>
size_t Send(SenderPtr const &s) const;
/// Variant of Send() that takes a specific sender in the form of a
/// TfWeakBase pointer and a typeid.
///
/// This version is used by senders who don't have static knowledge of
/// sender's type, but have access to its weak base pointer and its
/// typeid.
TF_API
size_t SendWithWeakBase(const TfWeakBase *senderWeakBase,
const void *senderUniqueId,
const std::type_info &type) const;
TF_API
virtual ~TfNotice();
/// Blocks sending of all notices in current thread.
///
/// \note This is intended to be temporary and should NOT be used.
///
/// While one or more \c TfNotice::Block is instantiated, any call to \c
/// TfNotice::Send in the current thread will be silently ignored. This
/// will continue until all \c TfNotice::Block objects are destroyed.
/// Notices that are sent when blocking is active will *not* be resent.
class Block {
public:
TF_API Block();
TF_API ~Block();
};
private:
// Abstract base class for calling listeners.
// A typed-version derives (via templating) off this class.
class _DelivererBase : public TfWeakBase {
public:
_DelivererBase()
: _list(0), _active(true), _markedForRemoval(false)
{
}
TF_API
virtual ~_DelivererBase();
TF_API
void _BeginDelivery(const TfNotice &notice,
const TfWeakBase *sender,
const std::type_info &senderType,
const TfWeakBase *listener,
const std::type_info &listenerType,
const std::vector<TfNotice::WeakProbePtr> &probes);
TF_API
void _EndDelivery(const std::vector<TfNotice::WeakProbePtr> &probes);
// The derived class converts n to the proper type and delivers it by
// calling the listener's method. The function returns \c true,
// unless the listener has expired or been marked in active (i.e. by
// TfNotice::Revoke()), in which case the method call is skipped and
// \c false is returned.
virtual bool
_SendToListener(const TfNotice &n,
const TfType &type,
const TfWeakBase *s,
const void *senderUniqueId,
const std::type_info &senderType,
const std::vector<TfNotice::WeakProbePtr> &probes) = 0;
void _Deactivate() {
_active = false;
}
bool _IsActive() const {
return _active;
}
void _MarkForRemoval() {
_markedForRemoval = true;
}
// True if the entry has been added to the _deadEntries list for
// removal. Used to avoid adding it more than once to the list.
bool _IsMarkedForRemoval() const {
return _markedForRemoval;
}
virtual TfType GetNoticeType() const = 0;
virtual bool Delivers(TfType const &noticeType,
const TfWeakBase *sender) const = 0;
virtual TfWeakBase const *GetSenderWeakBase() const = 0;
virtual _DelivererBase *Clone() const = 0;
protected:
template <class ToNoticeType, class FromNoticeType>
static inline ToNoticeType const *
_CastNotice(FromNoticeType const *from) {
// Dynamic casting in deliverers is significant overhead, so only
// do error checking in debug builds.
if (TF_DEV_BUILD) {
if (!dynamic_cast<ToNoticeType const *>(from)) {
ToNoticeType const *castNotice =
TfSafeDynamic_cast<ToNoticeType const *>(from);
// this will abort with a clear error message if
// castNotice is NULL
TfNotice::_VerifyFailedCast(typeid(ToNoticeType),
*from, castNotice);
}
}
return static_cast<ToNoticeType const *>(from);
}
private:
// Linkage to the containing _DelivererList in the Tf_NoticeRegistry
_DelivererList *_list;
_DelivererList::iterator _listIter;
bool _active;
bool _markedForRemoval;
friend class Tf_NoticeRegistry;
};
template <class Derived>
class _StandardDeliverer : public _DelivererBase {
public:
virtual ~_StandardDeliverer() {}
virtual TfType GetNoticeType() const {
typedef typename Derived::NoticeType NoticeType;
TfType ret = TfType::Find<NoticeType>();
if (ret.IsUnknown())
TF_FATAL_ERROR("notice type " + ArchGetDemangled<NoticeType>() +
" undefined in the TfType system");
return ret;
}
virtual bool Delivers(TfType const &noticeType,
TfWeakBase const *sender) const {
Derived const *derived = this->AsDerived();
return noticeType.IsA(GetNoticeType()) &&
!derived->_sender.IsInvalid() &&
sender && derived->_sender.GetWeakBase() == sender;
}
virtual TfWeakBase const *GetSenderWeakBase() const {
Derived const *derived = this->AsDerived();
return derived->_sender ? derived->_sender.GetWeakBase() : 0;
}
virtual _DelivererBase *Clone() const {
Derived const *derived = this->AsDerived();
return new Derived(derived->_listener,
derived->_method,
derived->_sender,
GetNoticeType());
}
virtual bool
_SendToListener(const TfNotice &notice,
const TfType &noticeType,
const TfWeakBase *sender,
const void *senderUniqueId,
const std::type_info &senderType,
const std::vector<TfNotice::WeakProbePtr> &probes)
{
Derived *derived = this->AsDerived();
typedef typename Derived::ListenerType ListenerType;
typedef typename Derived::NoticeType NoticeType;
ListenerType *listener = get_pointer(derived->_listener);
if (listener && !derived->_sender.IsInvalid()) {
if (ARCH_UNLIKELY(!probes.empty())) {
TfWeakBase const *senderWeakBase = GetSenderWeakBase(),
*listenerWeakBase = derived->_listener.GetWeakBase();
_BeginDelivery(notice, senderWeakBase,
senderWeakBase ?
senderType : typeid(void),
listenerWeakBase,
typeid(ListenerType), probes);
}
derived->
_InvokeListenerMethod(listener,
*_CastNotice<NoticeType>(&notice),
noticeType, sender,
senderUniqueId, senderType);
if (ARCH_UNLIKELY(!probes.empty()))
_EndDelivery(probes);
return true;
}
return false;
}
private:
Derived *AsDerived() {
return static_cast<Derived *>(this);
}
Derived const *AsDerived() const {
return static_cast<Derived const *>(this);
}
};
template <typename LPtr, typename SPtr, typename Method, typename Notice>
class _Deliverer :
public _StandardDeliverer<_Deliverer<LPtr, SPtr, Method, Notice> >
{
public:
typedef Notice NoticeType;
typedef typename LPtr::DataType ListenerType;
typedef Method MethodPtr;
_Deliverer(LPtr const &listener,
MethodPtr const &methodPtr,
SPtr const &sender = SPtr(),
TfType const &noticeType = TfType())
: _listener(listener)
, _sender(sender)
, _method(methodPtr)
{
}
void _InvokeListenerMethod(ListenerType *listener,
const NoticeType &notice,
const TfType &noticeType,
const TfWeakBase *,
const void *,
const std::type_info &)
{
(listener->*_method)(notice);
}
LPtr _listener;
SPtr _sender;
MethodPtr _method;
};
template <class LPtr, class Method>
class _RawDeliverer :
public _StandardDeliverer<_RawDeliverer<LPtr, Method> >
{
public:
typedef TfNotice NoticeType;
typedef typename LPtr::DataType ListenerType;
typedef Method MethodPtr;
_RawDeliverer(LPtr const &listener,
MethodPtr const &methodPtr,
TfAnyWeakPtr const &sender,
TfType const &noticeType)
: _noticeType(noticeType),
_listener(listener),
_method(methodPtr),
_sender(sender)
{
}
virtual TfType GetNoticeType() const {
return _noticeType;
}
void _InvokeListenerMethod(ListenerType *listener,
const NoticeType &notice,
const TfType &noticeType,
const TfWeakBase *sender,
const void *senderUniqueId,
const std::type_info &senderType)
{
(listener->*_method)(notice, noticeType,
const_cast<TfWeakBase *>(sender),
senderUniqueId, senderType);
}
TfType _noticeType;
LPtr _listener;
MethodPtr _method;
TfAnyWeakPtr _sender;
};
template <class LPtr, class SPtr, class Method, class Notice>
class _DelivererWithSender :
public _StandardDeliverer<
_DelivererWithSender<LPtr, SPtr, Method, Notice>
>
{
public:
typedef Notice NoticeType;
typedef Method MethodPtr;
typedef typename LPtr::DataType ListenerType;
typedef typename SPtr::DataType SenderType;
_DelivererWithSender(LPtr const &listener,
MethodPtr const &methodPtr,
SPtr const &sender,
TfType const &noticeType = TfType())
: _listener(listener),
_sender(sender),
_method(methodPtr)
{
}
void _InvokeListenerMethod(ListenerType *listener,
const NoticeType &notice,
const TfType &noticeType,
const TfWeakBase *sender,
const void *,
const std::type_info &)
{
SenderType *deliveredSender =
static_cast<SenderType *>(const_cast<TfWeakBase *>(sender));
SPtr deliveredSPtr(deliveredSender);
(listener->*_method)(notice, deliveredSPtr);
}
LPtr _listener;
SPtr _sender;
MethodPtr _method;
};
private:
// Internal non-templated function to install listeners.
TF_API
static Key _Register(_DelivererBase*);
TF_API
static void _VerifyFailedCast(const std::type_info& toType,
const TfNotice& notice,
const TfNotice* castNotice);
TF_API
size_t _Send(const TfWeakBase* sender,
const void *senderUniqueId,
const std::type_info & senderType) const;
TF_API
size_t _SendWithType(const TfType & noticeType,
const TfWeakBase* sender,
const void *senderUniqueId,
const std::type_info & senderType) const;
friend class Tf_NoticeRegistry;
// Befriend the wrapping so it can access _SendWithType() directly
// in order to provide dynamic downcasting of Python notice types.
friend class Tf_PyNotice;
};
template <typename SenderPtr>
size_t
TfNotice::Send(SenderPtr const &s) const
{
const TfWeakBase *senderWeakBase = s ? s.GetWeakBase() : NULL;
return _Send(senderWeakBase, senderWeakBase ? s.GetUniqueIdentifier() : 0,
senderWeakBase ?
typeid(typename SenderPtr::DataType) : typeid(void));
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_NOTICE_H
+43
View File
@@ -0,0 +1,43 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_NULL_PTR_H
#define PXR_BASE_TF_NULL_PTR_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
PXR_NAMESPACE_OPEN_SCOPE
// A type used to create the \a TfNullPtr token.
struct TfNullPtrType
{
};
// A token to represent null for smart pointers like \a TfWeakPtr and \a
// TfRefPtr.
TF_API extern const TfNullPtrType TfNullPtr;
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_NULL_PTR_H
+154
View File
@@ -0,0 +1,154 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_OSTREAM_METHODS_H
#define PXR_BASE_TF_OSTREAM_METHODS_H
/// \file tf/ostreamMethods.h
/// \ingroup group_tf_DebuggingOutput
///
/// Handy ostream output for various lib/tf and STL containers.
///
/// These functions are useful when you need to quickly output various STL
/// containers. The stream operators are only available if the contained
/// types have stream operators.
///
/// This facility should \e not be used to output data for later input: this
/// is essentially a "write-only" facility meant for diagnostics or
/// human-readable display; the formats described herein are subject to change
/// without notice.
#include "pxr/pxr.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/smallVector.h"
#include <ostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <type_traits>
#include <boost/type_traits/has_left_shift.hpp>
PXR_NAMESPACE_OPEN_SCOPE
template <class T>
constexpr bool Tf_IsOstreamable() {
return boost::has_left_shift<
std::ostream &, /* << */ T, /* -> */ std::ostream &>::value;
}
/// Output a TfSmallVector using [ ] as delimiters.
/// \ingroup group_tf_DebuggingOutput
template <class T, uint32_t N>
typename std::enable_if<PXR_NS::Tf_IsOstreamable<T>(), std::ostream &>::type
operator<<(std::ostream &out, const TfSmallVector<T, N> &v)
{
out << "[ ";
for (auto const &obj: v)
out << obj << " ";
out << "]";
return out;
}
PXR_NAMESPACE_CLOSE_SCOPE
// These operator<< overloads need to go in the std namespace for
// Koenig lookup to work.
namespace std {
/// Output an STL vector using [ ] as delimiters.
/// \ingroup group_tf_DebuggingOutput
template <class T>
typename std::enable_if<PXR_NS::Tf_IsOstreamable<T>(), std::ostream &>::type
operator<<(std::ostream &out, const std::vector<T> &v)
{
out << "[ ";
for (auto const &obj: v)
out << obj << " ";
out << "]";
return out;
}
/// Output an STL set using ( ) as delimiters.
/// \ingroup group_tf_DebuggingOutput
template <class T>
typename std::enable_if<PXR_NS::Tf_IsOstreamable<T>(), std::ostream &>::type
operator<<(std::ostream &out, const std::set<T> &v)
{
out << "( ";
for (auto const &obj: v)
out << obj << " ";
out << ")";
return out;
}
/// Output an STL list using { } as delimiters.
/// \ingroup group_tf_DebuggingOutput
template <class T>
typename std::enable_if<PXR_NS::Tf_IsOstreamable<T>(), std::ostream &>::type
operator<<(std::ostream &out, const std::list<T> &l)
{
out << "{ ";
for (auto const &obj: l)
out << obj << " ";
out << "}";
return out;
}
/// Output an TfHashMap using < > as delimiters.
/// \ingroup group_tf_DebuggingOutput
template <class K, class M, class H, class C, class A>
typename std::enable_if<
PXR_NS::Tf_IsOstreamable<K>() && PXR_NS::Tf_IsOstreamable<M>(), std::ostream &>::type
operator<<(std::ostream &out, const PXR_NS::TfHashMap<K, M, H, C, A> &h)
{
out << "< ";
for (auto const &p: h)
out << "<" << p.first << ": " << p.second << "> ";
out << ">";
return out;
}
/// Output an STL map using < > as delimiters.
/// \ingroup group_tf_DebuggingOutput
template <class K, class M>
typename std::enable_if<
PXR_NS::Tf_IsOstreamable<K>() && PXR_NS::Tf_IsOstreamable<M>(), std::ostream &>::type
operator<<(std::ostream &out, const std::map<K, M> &h)
{
out << "< ";
for (auto const &p: h)
out << "<" << p.first << ": " << p.second << "> ";
out << ">";
return out;
}
} // namespace std
#endif // PXR_BASE_TF_OSTREAM_METHODS_H
+156
View File
@@ -0,0 +1,156 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PATH_UTILS_H
#define PXR_BASE_TF_PATH_UTILS_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/fileSystem.h"
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \file tf/pathUtils.h
/// \ingroup group_tf_Path
/// Definitions of basic path utilities in tf.
///
/// These are utilities that operate on paths (represented by strings as
/// something like: "/chars/Buzz/Torso".
/// Returns the canonical path of the specified filename, eliminating any
/// symbolic links encountered in the path.
///
/// This is a wrapper to realpath(3), which caters for situations where the
/// real realpath() would return a NULL string, such as the case where the
/// path is really just a program name. The memory allocated by realpath is
/// managed internally.
///
/// If \a allowInaccessibleSuffix is true, then this function will only invoke
/// realpath on the longest accessible prefix of \a path, and then append the
/// inaccessible suffix.
///
/// If \a error is provided, it is set to the error reason should an error
/// occur while computing the real path. If no error occurs, the string is
/// cleared.
TF_API
std::string TfRealPath(std::string const& path,
bool allowInaccessibleSuffix = false,
std::string* error = 0);
/// Normalizes the specified path, eliminating double slashes, etc.
///
/// This canonicalizes paths, removing any double slashes, and eliminiating
/// '.', and '..' components of the path. This emulates the behavior of
/// os.path.normpath in Python.
///
/// On Windows, all backslashes are converted to forward slashes and drive
/// specifiers (e.g., "C:") are lower-cased. If \p stripDriveSpecifier
/// is \c true, these drive specifiers are removed from the path.
TF_API
std::string TfNormPath(std::string const& path,
bool stripDriveSpecifier = false);
/// Return the index delimiting the longest accessible prefix of \a path.
///
/// The returned value is safe to use to split the string via it's generalized
/// copy constructor. If the entire path is accessible, return the length of
/// the input string. If none of the path is accessible, return 0. Otherwise
/// the index points to the path separator that delimits the existing prefix
/// from the non-existing suffix.
///
/// Examples: suppose the paths /, /usr, and /usr/anim exist, but no other
/// paths exist.
///
/// TfFindLongestAccessiblePrefix('/usr/anim') -> 9
/// TfFindLongestAccessiblePrefix('/usr/anim/foo') -> 9
/// TfFindLongestAccessiblePrefix('/foo/bar') -> 0
///
/// If an error occurs, and the \a error string is not null, it is set to the
/// reason for the error. If the error string is set, the returned index is
/// the path separator before the element at which the error occurred.
TF_API
std::string::size_type
TfFindLongestAccessiblePrefix(std::string const &path, std::string* error = 0);
/// Returns the canonical absolute path of the specified filename.
///
/// This makes the specified path absolute, by prepending the current working
/// directory. If the path is already absolute, it is returned unmodified.
/// This function differs from TfRealPath in that the path may point to a
/// symlink, or not exist at all, and still result in an absolute path, rather
/// than an empty string.
TF_API
std::string TfAbsPath(std::string const& path);
/// Returns the extension for a file path
///
/// If \p path is a directory path, an empty path, or a dotfile path, return
/// the empty string. Otherwise return \p path 's dot-separated extension as
/// a string(dot not included).
///
/// Examples:
///
/// TfGetExtension('/foo/bar') -> ''
/// TfGetExtension('/foo/bar/foo.baz') -> 'baz'
/// TfGetExtension('/foo.bar/foo.baz') -> 'baz'
/// TfGetExtension('/foo/bar/foo.101.baz') -> 'baz'
/// TfGetExtension('/foo/bar/.foo.baz') -> 'baz'
/// TfGetExtension('/foo/bar/.foo') -> ''
TF_API
std::string TfGetExtension(std::string const& path);
/// Returns the value of a symbolic link. Returns the empty string on
/// error or if path is not a symbolic link.
TF_API
std::string TfReadLink(std::string const& path);
/// Return true if and only if a path is relative (not absolute).
TF_API
bool TfIsRelativePath(std::string const& path);
/// Expands one or more shell glob patterns.
///
/// This is a wrapper to glob(3), which manages the C structures necessary to
/// glob a pattern, returning a std::vector of results. If no flags are
/// specified, the GLOB_MARK and GLOB_NOCHECK flags are set by default.
/// GLOB_MARK marks directories which match the glob pattern with a trailing
/// slash. GLOB_NOCHECK returns any unexpanded patterns in the result.
TF_API
std::vector<std::string> TfGlob(std::vector<std::string> const& paths,
unsigned int flags=ARCH_GLOB_DEFAULT);
/// Expands a shell glob pattern.
///
/// This form of Glob calls TfGlob. For efficiency reasons, if expanding more
/// than one pattern, use the vector form. As with the vector form of TfGlob,
/// if flags is not set, the default glob flags are GLOB_MARK and
/// GLOB_NOCHECK.
TF_API
std::vector<std::string> TfGlob(std::string const& path,
unsigned int flags=ARCH_GLOB_DEFAULT);
PXR_NAMESPACE_CLOSE_SCOPE
#endif /* PXR_BASE_TF_PATH_UTILS_H */
+134
View File
@@ -0,0 +1,134 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PATTERN_MATCHER_H
#define PXR_BASE_TF_PATTERN_MATCHER_H
/// \file tf/patternMatcher.h
/// \ingroup group_tf_String
/// A simple glob and regex matching utility.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/regex.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPatternMatcher
/// \ingroup group_tf_String
///
/// Class for matching regular expressions.
///
/// A matcher is good to use when you have many strings to match against one
/// pattern. This is because the matcher will only compile the regular
/// expression once.
///
class TfPatternMatcher
{
public:
/// Construct an empty (invalid) TfPatternMatcher.
TF_API TfPatternMatcher();
TF_API TfPatternMatcher(TfPatternMatcher &&) noexcept = default;
TF_API TfPatternMatcher& operator=(TfPatternMatcher &&) = default;
/// Construct a TfPatternMatcher with a default configuration. Note that
/// pattern compilation will not occur until the first call to \a Match()
/// or \a IsValid().
TF_API
TfPatternMatcher( const std::string &pattern,
bool caseSensitive = false,
bool isGlob = false );
/// Destructor.
TF_API ~TfPatternMatcher();
/// If \a IsValid() returns true, this will return the reason why (if any).
TF_API std::string GetInvalidReason() const;
/// Returns true if the matcher has been set to be case sensitive, false
/// otherwise.
bool IsCaseSensitive() const {
return _caseSensitive;
}
/// Returns true if the matcher has been set to treat patterns as glob
/// patterns, false otherwise.
bool IsGlobPattern() const {
return _isGlob;
}
/// Returns the matcher's pattern string.
TF_API const std::string& GetPattern() const {
return _pattern;
}
/// Returns true if the matcher has a valid pattern. Note that empty
/// patterns are considered invalid. This will cause a compile of
TF_API bool IsValid() const;
/// Returns true if \a query matches the matcher's pattern.
///
/// If there is an error in matching and errorMsg is not NULL, it will be
/// set with the error message. If the matcher is not valid, this will
/// return false. Note that this will cause a compile of the matcher's
/// pattern if it was not already compiled.
///
/// \warning Unlike 'match' functions in other regular expression
/// libraries, this method does not implicitly anchor the pattern. If a
/// partial match is not acceptable, it is necessary to anchor the pattern
/// passed to the constructor, e.g. "^mypattern$".
///
TF_API bool Match( const std::string &query,
std::string *errorMsg = NULL ) const;
/// Set this matcher to match case-sensitively or not.
TF_API void SetIsCaseSensitive( bool sensitive );
/// Set this matcher to treat its pattern as a glob pattern. Currently,
/// this means that the pattern will be transformed by replacing all
/// instances of '.' with '\.', '*' with '.*', and '?' with '.', in that
/// order before being compiled as a normal regular expression.
TF_API void SetIsGlobPattern( bool isGlob );
/// Set the pattern that this matcher will use to match against.
TF_API void SetPattern( const std::string &pattern );
private:
void _Compile() const;
bool _caseSensitive;
bool _isGlob;
std::string _pattern;
mutable bool _recompile;
mutable ArchRegex _regex;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PATTERN_MATCHER_H
+211
View File
@@ -0,0 +1,211 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_POINTER_AND_BITS_H
#define PXR_BASE_TF_POINTER_AND_BITS_H
#include "pxr/pxr.h"
#include "pxr/base/arch/pragmas.h"
#include <cstdint>
#include <type_traits>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
// Return true if \p val is a power of two.
constexpr bool Tf_IsPow2(uintptr_t val) {
return val && !(val & (val - 1));
}
/// \class TfPointerAndBits
///
/// This class stores a T * and a small integer in the space of a T *. The
/// number of bits possible to store depends on the alignment of T. The
/// number of distinct values representable by the bits and the maximal value
/// are exposed via the compile time constants \a NumBitsValues and \a
/// MaxValue, respectively.
///
/// The bits may be set and retrieved as any integral type. The pointer value
/// and the bits value may be set and retrieved independently.
///
template <class T>
class TfPointerAndBits
{
// Microsoft Visual Studio doesn't like alignof(<abstract-type>).
// We'll assume that such an object has a pointer in it (the vtbl
// pointer) and use void* for alignment in that case.
template <typename U, bool = false>
struct _AlignOf {
static constexpr uintptr_t value = alignof(U);
};
template <typename U>
struct _AlignOf<U, true> {
static constexpr uintptr_t value = alignof(void*);
};
// Microsoft Visual Studio doesn't like alignof(<abstract-type>).
// We'll assume that such an object has a pointer in it (the vtbl
// pointer) and use void* for alignment in that case.
static constexpr uintptr_t _GetAlign() noexcept {
return _AlignOf<T, std::is_abstract<T>::value>::value;
}
static constexpr bool _SupportsAtLeastOneBit() noexcept {
return _GetAlign() > 1 && Tf_IsPow2(_GetAlign());
}
public:
/// Constructor. Pointer is initialized to null, bits are initialized to
/// zero.
constexpr TfPointerAndBits() noexcept : _ptrAndBits(0) {
static_assert(_SupportsAtLeastOneBit(),
"T's alignment does not support any bits");
}
/// Constructor. Set the pointer to \a p, and the bits to \a bits.
constexpr explicit TfPointerAndBits(T *p, uintptr_t bits = 0) noexcept
: _ptrAndBits(_Combine(p, bits))
{
static_assert(_SupportsAtLeastOneBit(),
"T's alignment does not support any bits");
}
constexpr uintptr_t GetMaxValue() const {
return _GetAlign() - 1;
}
constexpr uintptr_t GetNumBitsValues() const {
return _GetAlign();
}
/// Assignment. Leaves bits unmodified.
TfPointerAndBits &operator=(T *ptr) noexcept {
_SetPtr(ptr);
return *this;
}
/// Indirection.
constexpr T *operator->() const noexcept {
return _GetPtr();
}
/// Dereference.
constexpr T &operator *() const noexcept {
return *_GetPtr();
}
/// Retrieve the stored bits as the integral type \a Integral.
template <class Integral>
constexpr Integral BitsAs() const noexcept {
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_FORCING_TO_BOOL
return static_cast<Integral>(_GetBits());
ARCH_PRAGMA_POP
}
/// Set the stored bits. No static range checking is performed.
template <class Integral>
void SetBits(Integral val) noexcept {
_SetBits(static_cast<uintptr_t>(val));
}
/// Set the pointer value to \a ptr.
void Set(T *ptr) noexcept {
_SetPtr(ptr);
}
/// Set the pointer value to \a ptr and the bits to \a val.
template <class Integral>
void Set(T *ptr, Integral val) noexcept {
_ptrAndBits = _Combine(ptr, val);
}
/// Retrieve the pointer.
constexpr T *Get() const noexcept {
return _GetPtr();
}
/// Retrieve the raw underlying value. This can be useful for doing literal
/// equality checks between two instances. The only guarantees are that
/// this has the same bit pattern as the pointer value if the bits are 0,
/// and will compare equal to another instance when both have identical
/// pointer and bits values.
constexpr uintptr_t GetLiteral() const noexcept {
return _AsInt(_ptrAndBits);
}
/// Swap this PointerAndBits with \a other.
void Swap(TfPointerAndBits &other) noexcept {
::std::swap(_ptrAndBits, other._ptrAndBits);
}
private:
constexpr uintptr_t _GetBitMask() const noexcept {
return GetMaxValue();
}
// Combine \a p and \a bits into a single pointer value.
constexpr T *_Combine(T *p, uintptr_t bits) const noexcept {
return _AsPtr(_AsInt(p) | (bits & _GetBitMask()));
}
// Cast the pointer \a p to an integral type. This function and _AsPtr are
// the only ones that do the dubious compiler-specific casting.
constexpr uintptr_t _AsInt(T *p) const noexcept {
return (uintptr_t)p;
}
// Cast the integral \a i to the pointer type. This function and _AsInt are
// the only ones that do the dubious compiler-specific casting.
constexpr T *_AsPtr(uintptr_t i) const noexcept {
return (T *)i;
}
// Retrieve the held pointer value.
constexpr T *_GetPtr() const noexcept {
return _AsPtr(_AsInt(_ptrAndBits) & ~_GetBitMask());
}
// Set the held pointer value.
void _SetPtr(T *p) noexcept {
_ptrAndBits = _Combine(p, _GetBits());
}
// Retrieve the held bits value.
constexpr uintptr_t _GetBits() const noexcept {
return _AsInt(_ptrAndBits) & _GetBitMask();
}
// Set the held bits value.
void _SetBits(uintptr_t bits) noexcept {
_ptrAndBits = _Combine(_GetPtr(), bits);
}
// Single pointer member stores pointer value and bits.
T *_ptrAndBits;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_POINTER_AND_BITS_H
+324
View File
@@ -0,0 +1,324 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PREPROCESSOR_UTILS_H
#define PXR_BASE_TF_PREPROCESSOR_UTILS_H
/// \file tf/preprocessorUtils.h
/// \ingroup group_tf_Preprocessor
#ifndef TF_MAX_ARITY
# define TF_MAX_ARITY 7
#endif // TF_MAX_ARITY
#include "pxr/base/arch/defines.h"
#include "pxr/base/arch/pragmas.h"
#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/control/expr_iif.hpp>
#include <boost/preprocessor/comparison/equal.hpp>
#include <boost/preprocessor/facilities/expand.hpp>
#include <boost/preprocessor/punctuation/comma.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/tuple/eat.hpp>
#include <boost/preprocessor/tuple/to_list.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>
#if defined(ARCH_COMPILER_MSVC)
#include <boost/preprocessor/variadic/size.hpp>
#include <boost/vmd/is_empty.hpp>
#include <boost/vmd/is_tuple.hpp>
ARCH_PRAGMA_MACRO_TOO_FEW_ARGUMENTS
#endif
// In boost version 1.51, they seem to have neglected to define this.
// Without it, some functions will get confused about macros with no arguments
#ifndef BOOST_PP_TUPLE_TO_SEQ_0
#define BOOST_PP_TUPLE_TO_SEQ_0()
#endif
/// Count the number of arguments.
///
/// The underlying macro argument counting trick in the non-Windows
/// implementation originates from a posting on comp.std.c by Laurent Deniau.
///
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#if defined(ARCH_COMPILER_MSVC)
#define TF_NUM_ARGS(...) \
BOOST_PP_IIF(BOOST_VMD_IS_EMPTY(__VA_ARGS__),\
0, BOOST_PP_VARIADIC_SIZE(__VA_ARGS__))
#else
#define TF_NUM_ARGS(...) \
_TF_NUM_ARGS_CHECK(__VA_ARGS__) \
BOOST_PP_IIF(BOOST_PP_EQUAL(1, _TF_NUM_ARGS1(__VA_ARGS__)), \
BOOST_PP_EXPAND(TF_ARG_2 BOOST_PP_LPAREN() \
BOOST_PP_EXPAND(_TF_NUM_ARGS_0X TF_ARG_1(__VA_ARGS__) \
(BOOST_PP_REPEAT(TF_MAX_ARITY, _TF_NUM_ARGS_REP, _TF))) \
BOOST_PP_COMMA() 1 BOOST_PP_RPAREN()), \
_TF_NUM_ARGS1(__VA_ARGS__))
#define _TF_NUM_ARGS_CHECK(...) \
BOOST_PP_IIF(_TF_EXPAND(TF_ARG_2 BOOST_PP_LPAREN() \
BOOST_PP_CAT(_TF_NUM_ARGS_00, _TF_EXPAND( \
BOOST_PP_CAT(TF_ARG_, BOOST_PP_INC(TF_MAX_ARITY)) \
_TF_NUM_ARGS_TF(__VA_ARGS__))) BOOST_PP_COMMA() 1 BOOST_PP_RPAREN()), \
_TF_MAX_ARITY_OVERFLOW_IN_TF_NUM_ARGS, BOOST_PP_TUPLE_EAT(1))(...)
#define _TF_NUM_ARGS_00_TF 0, 0
#define _TF_MAX_ARITY_OVERFLOW_IN_TF_NUM_ARGS(a, b, c)
#define _TF_NUM_ARGS_0X(a, ...) \
_TF_NUM_ARGS_CHECK(a, __VA_ARGS__) 0, \
BOOST_PP_IIF(BOOST_PP_EQUAL(TF_MAX_ARITY, _TF_NUM_ARGS1(__VA_ARGS__)), \
0, 1 BOOST_PP_TUPLE_EAT(BOOST_PP_INC(TF_MAX_ARITY)))
#define _TF_EXPAND(x) x // We need this due to a bug in the preprocessor.
#define _TF_NUM_ARGS1(...) \
_TF_EXPAND(BOOST_PP_CAT(TF_ARG_, BOOST_PP_INC(TF_MAX_ARITY)) \
_TF_NUM_ARGS_EXT(__VA_ARGS__))
#define _TF_NUM_ARGS_DEC(z, i, n) BOOST_PP_COMMA() BOOST_PP_SUB(n, i)
#define _TF_NUM_ARGS_REP(z, i, n) BOOST_PP_COMMA() n
#define _TF_NUM_ARGS_EXT(...) \
(__VA_ARGS__ BOOST_PP_REPEAT(BOOST_PP_INC(TF_MAX_ARITY), \
_TF_NUM_ARGS_DEC, TF_MAX_ARITY))
#define _TF_NUM_ARGS_TF(...) \
(__VA_ARGS__ BOOST_PP_REPEAT(BOOST_PP_INC(TF_MAX_ARITY), \
_TF_NUM_ARGS_REP, _TF))
#endif
/// Return the arguments as is except if the first argument starts with a
/// matched parenthesis then remove those parentheses.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
//
// If the arguments satisfy _TF_PP_EAT_PARENS_IS_PARENS() then we expand to
// _TF_PP_EAT_PARENS_EXPAND1, otherwise to _TF_PP_EAT_PARENS_EXPAND. The
// former eats the parentheses while the latter passes the arguments
// unchanged.
//
// We add the ~ after the first __VA_ARGS__ in case there are zero
// arguments. MSVC will complain about insufficient arguments otherwise.
// The ~ will be discarded in any case.
#define TF_PP_EAT_PARENS(...) \
_TF_PP_EAT_PARENS_IFF(_TF_PP_EAT_PARENS_IS_PARENS(__VA_ARGS__ ~),\
_TF_PP_EAT_PARENS_EXPAND1,_TF_PP_EAT_PARENS_EXPAND)(__VA_ARGS__)
/// Expand the arguments and make the result a string.
// We can't use
// BOOST_PP_STRINGIZE because on MSVC passing no arguments will report "not
// enough actual parameters" and yield nothing. We want no warnings and an
// empty string. We do that by passing an unused first argument to the inner
// macro (we need an inner macro to cause expansion). This causes MSVC to
// yield "" for an empty __VA_ARGS__ list.
#define TF_PP_EAT_PARENS_STR(...) _TF_PP_EAT_PARENS_STR2(~, __VA_ARGS__)
#define _TF_PP_EAT_PARENS_STR2(x, ...) #__VA_ARGS__
// Expands to the second argument if c is 1 and the third argument if c is
// 0. No other values of c are allowed. We can't use BOOST_PP_IFF() because
// it won't expand during stringizing under MSVC.
#define _TF_PP_EAT_PARENS_IFF(c, t, f) \
BOOST_PP_CAT(_TF_PP_EAT_PARENS_IFF_, c)(t, f)
#define _TF_PP_EAT_PARENS_IFF_0(t, f) f
#define _TF_PP_EAT_PARENS_IFF_1(t, f) t
// Force expansion of the arguments.
#define _TF_PP_EAT_PARENS_EXPAND(...) __VA_ARGS__
// Similar to expand except it will eat the first matching pair of
// parentheses. For example, _TF_PP_EAT_PARENS_EXPAND1((x)(y)) yields x(y).
// The outer _TF_PP_EAT_PARENS_EXPAND() is needed for MSVC, which otherwise
// would stringizing to "_TF_PP_EAT_PARENS_EXPAND " plus the literal
// substitution of the arguments.
#define _TF_PP_EAT_PARENS_EXPAND1(...) \
_TF_PP_EAT_PARENS_EXPAND(_TF_PP_EAT_PARENS_EXPAND __VA_ARGS__)
// This works around a MSVC bug. When a macro expands to FOO(__VA_ARGS__,bar),
// MSVC will separate the arguments of __VA_ARGS__ even if they're inside
// matching parentheses. So, for example, if __VA_ARGS__ is (x,y) then we'll
// expand to FOO(x,y,bar) instead of FOO((x,y),bar). This macro works around
// that. Use: _TF_PP_EAT_PARENS_CALL(FOO,(__VA_ARGS__,bar)).
//
// We need the _TF_PP_EAT_PARENS_EXPAND() here otherwise stringizing will
// stringize the literal replacements, not the result of the expansion of x y.
// If FOO(x,y) expands to x+y then we'd get "FOO ((x,y),bar)" without
// _TF_PP_EAT_PARENS_EXPAND() instead of the correct "(x,y)+bar".
#define _TF_PP_EAT_PARENS_CALL(x, y) _TF_PP_EAT_PARENS_EXPAND(x y)
// Expands to 1 if x starts with a matched parenthesis, otherwise expands to
// 0. "_TF_PP_EAT_PARENS_IS_PARENS2 x" eats the parentheses if they exist and
// expands to "x, 1,", otherwise it expands to _TF_PP_EAT_PARENS_IS_PARENS2
// and the literal expansion of x. This result goes to
// _TF_PP_EAT_PARENS_IS_PARENS_CHECK_N() which extracts the 1 expanded from
// _TF_PP_EAT_PARENS_IS_PARENS2 or a 0 passed as a final argument. In either
// case the desired result is the second argument to
// _TF_PP_EAT_PARENS_IS_PARENS_CHECK_N.
#define _TF_PP_EAT_PARENS_IS_PARENS(x) \
_TF_PP_EAT_PARENS_IS_PARENS_CHECK(_TF_PP_EAT_PARENS_IS_PARENS2 x)
#define _TF_PP_EAT_PARENS_IS_PARENS_CHECK(...) \
_TF_PP_EAT_PARENS_CALL(_TF_PP_EAT_PARENS_IS_PARENS_CHECK_N,(__VA_ARGS__,0,))
#define _TF_PP_EAT_PARENS_IS_PARENS_CHECK_N(x, n, ...) n
#define _TF_PP_EAT_PARENS_IS_PARENS_TRUE(x) x, 1,
#define _TF_PP_EAT_PARENS_IS_PARENS2(...) _TF_PP_EAT_PARENS_IS_PARENS_TRUE(~)
/// Exapnds to 1 if the argument is a tuple, and 0 otherwise.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#if defined(ARCH_COMPILER_MSVC)
#define TF_PP_IS_TUPLE(sequence) \
BOOST_VMD_IS_TUPLE(sequence)
#else
#define TF_PP_IS_TUPLE(arg) \
BOOST_PP_CAT(_TF_PP_IS_TUPLE, BOOST_PP_EXPAND(_TF_PP_IS_TUPLE arg)) )
#define _TF_PP_IS_TUPLE(...) _TF
#define _TF_PP_IS_TUPLE_TF _TF_PP_IS_TUPLE_TRUE(
#define _TF_PP_IS_TUPLE_TF_PP_IS_TUPLE _TF_PP_IS_TUPLE_FALSE(
#define _TF_PP_IS_TUPLE_TRUE() 1
#define _TF_PP_IS_TUPLE_FALSE(arg) 0
#endif
/// Count the number of elements in a preprocessor tuple.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_PP_TUPLE_SIZE(tuple) \
BOOST_PP_EXPAND(TF_NUM_ARGS tuple)
/// Convert a preprocessor tuple to a preprocessor list.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_PP_TUPLE_TO_LIST(tuple) \
BOOST_PP_IIF( \
BOOST_PP_EQUAL(TF_PP_TUPLE_SIZE(tuple), 0), \
BOOST_PP_LIST_NIL, \
BOOST_PP_TUPLE_TO_LIST(TF_PP_TUPLE_SIZE(tuple), tuple))
/// Convert a preprocessor tuple to a preprocessor sequence.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_PP_TUPLE_TO_SEQ(tuple) \
BOOST_PP_IIF( \
BOOST_PP_EQUAL(TF_PP_TUPLE_SIZE(tuple), 0), \
BOOST_PP_EMPTY(), \
BOOST_PP_TUPLE_TO_SEQ(TF_PP_TUPLE_SIZE(tuple), tuple))
/// Create a preprocessor array.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_MAKE_PP_ARRAY(...) \
(TF_NUM_ARGS(__VA_ARGS__), (__VA_ARGS__))
/// Create a preprocessor list.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_MAKE_PP_LIST(...) \
TF_PP_TUPLE_TO_LIST((__VA_ARGS__))
/// Create a preprocessor sequence.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_MAKE_PP_SEQ(...) \
TF_PP_TUPLE_TO_SEQ((__VA_ARGS__))
/// Macros that expand to a specific argument.
/// \ingroup group_tf_Preprocessor
/// \hideinitializer
#define TF_ARG_1(_1,...) _1
#define TF_ARG_2(_1,_2,...) _2
#define TF_ARG_3(_1,_2,_3,...) _3
#define TF_ARG_4(_1,_2,_3,_4,...) _4
#define TF_ARG_5(_1,_2,_3,_4,_5,...) _5
#define TF_ARG_6(_1,_2,_3,_4,_5,_6,...) _6
#define TF_ARG_7(_1,_2,_3,_4,_5,_6,_7,...) _7
#define TF_ARG_8(_1,_2,_3,_4,_5,_6,_7,_8,...) _8
#define TF_ARG_9(_1,_2,_3,_4,_5,_6,_7,_8,_9,...) _9
#define TF_ARG_10(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,...) _10
#define TF_ARG_11(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,...) _11
#define TF_ARG_12(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,...) _12
#define TF_ARG_13(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,...) _13
#define TF_ARG_14(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,...) _14
#define TF_ARG_15(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,...) _15
#define TF_ARG_16(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,...) _16
#define TF_ARG_17(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,...) _17
#define TF_ARG_18(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,...) _18
#define TF_ARG_19(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,...) _19
#define TF_ARG_20(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,...) _20
#define TF_ARG_21(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,...) _21
#define TF_ARG_22(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,...) _22
#define TF_ARG_23(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,...) _23
#define TF_ARG_24(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,...) _24
#define TF_ARG_25(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,...) _25
#define TF_ARG_26(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,...) _26
#define TF_ARG_27(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,...) _27
#define TF_ARG_28(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,...) _28
#define TF_ARG_29(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,...) _29
#define TF_ARG_30(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,...) _30
#define TF_ARG_31(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,...) _31
#define TF_ARG_32(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,...) _32
#define TF_ARG_33(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,...) _33
#define TF_ARG_34(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,...) _34
#define TF_ARG_35(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,...) _35
#define TF_ARG_36(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,...) _36
#define TF_ARG_37(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,...) _37
#define TF_ARG_38(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,...) _38
#define TF_ARG_39(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,...) _39
#define TF_ARG_40(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,...) _40
#define TF_ARG_41(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,...) _41
#define TF_ARG_42(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,...) _42
#define TF_ARG_43(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,...) _43
#define TF_ARG_44(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,...) _44
#define TF_ARG_45(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,...) _45
#define TF_ARG_46(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,...) _46
#define TF_ARG_47(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,...) _47
#define TF_ARG_48(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,...) _48
#define TF_ARG_49(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,...) _49
#define TF_ARG_50(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,...) _50
#define TF_ARG_51(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,...) _51
#define TF_ARG_52(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,...) _52
#define TF_ARG_53(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,...) _53
#define TF_ARG_54(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,...) _54
#define TF_ARG_55(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,...) _55
#define TF_ARG_56(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,...) _56
#define TF_ARG_57(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,...) _57
#define TF_ARG_58(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,...) _58
#define TF_ARG_59(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,...) _59
#define TF_ARG_60(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,...) _60
#define TF_ARG_61(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,...) _61
#define TF_ARG_62(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,...) _62
#define TF_ARG_63(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,_63,...) _63
#define TF_ARG_64(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,_21,_22,_23,_24,_25,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,_63,_64,...) _64
#if TF_MAX_ARITY > 64
#error "TF_MAX_ARITY is larger than _MAX_ARGS"
#endif
#endif /* PXR_BASE_TF_PREPROCESSOR_UTILS_H */
+322
View File
@@ -0,0 +1,322 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PREPROCESSOR_UTILS_LITE_H
#define PXR_BASE_TF_PREPROCESSOR_UTILS_LITE_H
// This "lite" version of preprocessorUtils exists to avoid dependencies on
// boost. Do not add any includes of boost headers, such as
// <boost/preprocessor/...> or <boost/vmd/...> to this file.
#include "pxr/base/arch/defines.h"
// Helper for TF_PP_CAT. This extra indirection is required so that macros get
// expanded before the pasting occurs.
#define TF_PP_CAT_IMPL(x, y) x ## y
/// Paste concatenate preprocessor expressions x and y after expansion. This
/// is similar to BOOST_PP_CAT but doesn't require including the boost config
/// header which is somewhat heavy.
#define TF_PP_CAT(x, y) TF_PP_CAT_IMPL(x, y)
// Helper for TF_PP_STRINGIZE supplying macro expansion before pasting
#define TF_PP_STRINGIZE_IMPL(x) #x
/// Expand and convert the argument to a string, using a most minimal macro.
#define TF_PP_STRINGIZE(x) TF_PP_STRINGIZE_IMPL(x)
#ifdef ARCH_COMPILER_MSVC
/// Expand to the number of arguments passed. For example,
/// TF_PP_VARIADIC_SIZE(foo, bar, baz) expands to 3. Supports up to 64
/// arguments.
#define TF_PP_VARIADIC_SIZE(...) TF_PP_CAT(TF_PP_VARIADIC_SIZE_IMPL(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,),)
/// Expand to the \p n'th argument of the arguments following \p n,
/// zero-indexed. For example, TF_PP_VARIADIC_ELEM(0, a, b, c) expands to a,
/// and TF_PP_VARIADIC_ELEM(1, a, b, c) expands to b.
#define TF_PP_VARIADIC_ELEM(n, ...) TF_PP_VARIADIC_ELEM_IMPL(n,__VA_ARGS__)
#define TF_PP_VARIADIC_ELEM_IMPL(n, ...) TF_PP_CAT(TF_PP_CAT(TF_PP_VAE_, n)(__VA_ARGS__,),)
#else // NOT MSVC
/// Expand to the number of arguments passed. For example,
/// TF_PP_VARIADIC_SIZE(foo, bar, baz) expands to 3. Supports up to 64
/// arguments. Does not work for zero arguments, which is trickier.
#define TF_PP_VARIADIC_SIZE(...) TF_PP_VARIADIC_SIZE_IMPL(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,)
/// Expand to the \p n'th argument of the arguments following \p n,
/// zero-indexed. For example, TF_PP_VARIADIC_ELEM(0, a, b, c) expands to a,
/// and TF_PP_VARIADIC_ELEM(1, a, b, c) expands to b.
#define TF_PP_VARIADIC_ELEM(n, ...) TF_PP_CAT(TF_PP_VAE_, n)(__VA_ARGS__,)
#endif // ARCH_COMPILER_MSVC
#define TF_PP_VARIADIC_SIZE_IMPL(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, a61, a62, a63, size, ...) size
#define TF_PP_VAE_0(a0, ...) a0
#define TF_PP_VAE_1(a0, a1, ...) a1
#define TF_PP_VAE_2(a0, a1, a2, ...) a2
#define TF_PP_VAE_3(a0, a1, a2, a3, ...) a3
#define TF_PP_VAE_4(a0, a1, a2, a3, a4, ...) a4
#define TF_PP_VAE_5(a0, a1, a2, a3, a4, a5, ...) a5
#define TF_PP_VAE_6(a0, a1, a2, a3, a4, a5, a6, ...) a6
#define TF_PP_VAE_7(a0, a1, a2, a3, a4, a5, a6, a7, ...) a7
#define TF_PP_VAE_8(a0, a1, a2, a3, a4, a5, a6, a7, a8, ...) a8
#define TF_PP_VAE_9(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, ...) a9
#define TF_PP_VAE_10(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, ...) a10
#define TF_PP_VAE_11(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, ...) a11
#define TF_PP_VAE_12(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, ...) a12
#define TF_PP_VAE_13(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, ...) a13
#define TF_PP_VAE_14(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, ...) a14
#define TF_PP_VAE_15(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, ...) a15
#define TF_PP_VAE_16(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, ...) a16
#define TF_PP_VAE_17(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, ...) a17
#define TF_PP_VAE_18(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, ...) a18
#define TF_PP_VAE_19(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, ...) a19
#define TF_PP_VAE_20(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, ...) a20
#define TF_PP_VAE_21(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, ...) a21
#define TF_PP_VAE_22(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, ...) a22
#define TF_PP_VAE_23(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, ...) a23
#define TF_PP_VAE_24(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, ...) a24
#define TF_PP_VAE_25(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, ...) a25
#define TF_PP_VAE_26(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, ...) a26
#define TF_PP_VAE_27(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, ...) a27
#define TF_PP_VAE_28(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, ...) a28
#define TF_PP_VAE_29(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, ...) a29
#define TF_PP_VAE_30(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, ...) a30
#define TF_PP_VAE_31(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, ...) a31
#define TF_PP_VAE_32(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, ...) a32
#define TF_PP_VAE_33(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, ...) a33
#define TF_PP_VAE_34(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, ...) a34
#define TF_PP_VAE_35(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, ...) a35
#define TF_PP_VAE_36(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, ...) a36
#define TF_PP_VAE_37(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, ...) a37
#define TF_PP_VAE_38(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, ...) a38
#define TF_PP_VAE_39(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, ...) a39
#define TF_PP_VAE_40(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, ...) a40
#define TF_PP_VAE_41(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, ...) a41
#define TF_PP_VAE_42(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, ...) a42
#define TF_PP_VAE_43(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, ...) a43
#define TF_PP_VAE_44(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, ...) a44
#define TF_PP_VAE_45(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, ...) a45
#define TF_PP_VAE_46(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, ...) a46
#define TF_PP_VAE_47(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, ...) a47
#define TF_PP_VAE_48(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, ...) a48
#define TF_PP_VAE_49(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, ...) a49
#define TF_PP_VAE_50(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, ...) a50
#define TF_PP_VAE_51(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, ...) a51
#define TF_PP_VAE_52(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, ...) a52
#define TF_PP_VAE_53(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, ...) a53
#define TF_PP_VAE_54(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, ...) a54
#define TF_PP_VAE_55(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, ...) a55
#define TF_PP_VAE_56(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, ...) a56
#define TF_PP_VAE_57(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, ...) a57
#define TF_PP_VAE_58(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, ...) a58
#define TF_PP_VAE_59(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, ...) a59
#define TF_PP_VAE_60(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, ...) a60
#define TF_PP_VAE_61(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, a61, ...) a61
#define TF_PP_VAE_62(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, a61, a62, ...) a62
#define TF_PP_VAE_63(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, a61, a62, a63, ...) a63
#ifdef ARCH_COMPILER_MSVC
#define TF_PP_FE_0(_macro, ...)
#define TF_PP_FE_1(_macro, a) _macro(a)
#define TF_PP_FE_2(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_1,(_macro, __VA_ARGS__))
#define TF_PP_FE_3(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_2,(_macro, __VA_ARGS__))
#define TF_PP_FE_4(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_3,(_macro, __VA_ARGS__))
#define TF_PP_FE_5(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_4,(_macro, __VA_ARGS__))
#define TF_PP_FE_6(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_5,(_macro, __VA_ARGS__))
#define TF_PP_FE_7(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_6,(_macro, __VA_ARGS__))
#define TF_PP_FE_8(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_7,(_macro, __VA_ARGS__))
#define TF_PP_FE_9(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_8,(_macro, __VA_ARGS__))
#define TF_PP_FE_10(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_9,(_macro, __VA_ARGS__))
#define TF_PP_FE_11(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_10,(_macro, __VA_ARGS__))
#define TF_PP_FE_12(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_11,(_macro, __VA_ARGS__))
#define TF_PP_FE_13(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_12,(_macro, __VA_ARGS__))
#define TF_PP_FE_14(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_13,(_macro, __VA_ARGS__))
#define TF_PP_FE_15(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_14,(_macro, __VA_ARGS__))
#define TF_PP_FE_16(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_15,(_macro, __VA_ARGS__))
#define TF_PP_FE_17(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_16,(_macro, __VA_ARGS__))
#define TF_PP_FE_18(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_17,(_macro, __VA_ARGS__))
#define TF_PP_FE_19(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_18,(_macro, __VA_ARGS__))
#define TF_PP_FE_20(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_19,(_macro, __VA_ARGS__))
#define TF_PP_FE_21(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_20,(_macro, __VA_ARGS__))
#define TF_PP_FE_22(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_21,(_macro, __VA_ARGS__))
#define TF_PP_FE_23(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_22,(_macro, __VA_ARGS__))
#define TF_PP_FE_24(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_23,(_macro, __VA_ARGS__))
#define TF_PP_FE_25(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_24,(_macro, __VA_ARGS__))
#define TF_PP_FE_26(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_25,(_macro, __VA_ARGS__))
#define TF_PP_FE_27(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_26,(_macro, __VA_ARGS__))
#define TF_PP_FE_28(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_27,(_macro, __VA_ARGS__))
#define TF_PP_FE_29(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_28,(_macro, __VA_ARGS__))
#define TF_PP_FE_30(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_29,(_macro, __VA_ARGS__))
#define TF_PP_FE_31(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_30,(_macro, __VA_ARGS__))
#define TF_PP_FE_32(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_31,(_macro, __VA_ARGS__))
#define TF_PP_FE_33(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_32,(_macro, __VA_ARGS__))
#define TF_PP_FE_34(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_33,(_macro, __VA_ARGS__))
#define TF_PP_FE_35(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_34,(_macro, __VA_ARGS__))
#define TF_PP_FE_36(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_35,(_macro, __VA_ARGS__))
#define TF_PP_FE_37(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_36,(_macro, __VA_ARGS__))
#define TF_PP_FE_38(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_37,(_macro, __VA_ARGS__))
#define TF_PP_FE_39(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_38,(_macro, __VA_ARGS__))
#define TF_PP_FE_40(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_39,(_macro, __VA_ARGS__))
#define TF_PP_FE_41(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_40,(_macro, __VA_ARGS__))
#define TF_PP_FE_42(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_41,(_macro, __VA_ARGS__))
#define TF_PP_FE_43(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_42,(_macro, __VA_ARGS__))
#define TF_PP_FE_44(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_43,(_macro, __VA_ARGS__))
#define TF_PP_FE_45(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_44,(_macro, __VA_ARGS__))
#define TF_PP_FE_46(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_45,(_macro, __VA_ARGS__))
#define TF_PP_FE_47(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_46,(_macro, __VA_ARGS__))
#define TF_PP_FE_48(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_47,(_macro, __VA_ARGS__))
#define TF_PP_FE_49(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_48,(_macro, __VA_ARGS__))
#define TF_PP_FE_50(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_49,(_macro, __VA_ARGS__))
#define TF_PP_FE_51(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_50,(_macro, __VA_ARGS__))
#define TF_PP_FE_52(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_51,(_macro, __VA_ARGS__))
#define TF_PP_FE_53(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_52,(_macro, __VA_ARGS__))
#define TF_PP_FE_54(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_53,(_macro, __VA_ARGS__))
#define TF_PP_FE_55(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_54,(_macro, __VA_ARGS__))
#define TF_PP_FE_56(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_55,(_macro, __VA_ARGS__))
#define TF_PP_FE_57(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_56,(_macro, __VA_ARGS__))
#define TF_PP_FE_58(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_57,(_macro, __VA_ARGS__))
#define TF_PP_FE_59(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_58,(_macro, __VA_ARGS__))
#define TF_PP_FE_60(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_59,(_macro, __VA_ARGS__))
#define TF_PP_FE_61(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_60,(_macro, __VA_ARGS__))
#define TF_PP_FE_62(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_61,(_macro, __VA_ARGS__))
#define TF_PP_FE_63(_macro, a, ...) _macro(a) TF_PP_CAT(TF_PP_FE_62,(_macro, __VA_ARGS__))
#else // not MSVC
#define TF_PP_FE_0(_macro, ...)
#define TF_PP_FE_1(_macro, a) _macro(a)
#define TF_PP_FE_2(_macro, a, ...) _macro(a) TF_PP_FE_1(_macro, __VA_ARGS__)
#define TF_PP_FE_3(_macro, a, ...) _macro(a) TF_PP_FE_2(_macro, __VA_ARGS__)
#define TF_PP_FE_4(_macro, a, ...) _macro(a) TF_PP_FE_3(_macro, __VA_ARGS__)
#define TF_PP_FE_5(_macro, a, ...) _macro(a) TF_PP_FE_4(_macro, __VA_ARGS__)
#define TF_PP_FE_6(_macro, a, ...) _macro(a) TF_PP_FE_5(_macro, __VA_ARGS__)
#define TF_PP_FE_7(_macro, a, ...) _macro(a) TF_PP_FE_6(_macro, __VA_ARGS__)
#define TF_PP_FE_8(_macro, a, ...) _macro(a) TF_PP_FE_7(_macro, __VA_ARGS__)
#define TF_PP_FE_9(_macro, a, ...) _macro(a) TF_PP_FE_8(_macro, __VA_ARGS__)
#define TF_PP_FE_10(_macro, a, ...) _macro(a) TF_PP_FE_9(_macro, __VA_ARGS__)
#define TF_PP_FE_11(_macro, a, ...) _macro(a) TF_PP_FE_10(_macro, __VA_ARGS__)
#define TF_PP_FE_12(_macro, a, ...) _macro(a) TF_PP_FE_11(_macro, __VA_ARGS__)
#define TF_PP_FE_13(_macro, a, ...) _macro(a) TF_PP_FE_12(_macro, __VA_ARGS__)
#define TF_PP_FE_14(_macro, a, ...) _macro(a) TF_PP_FE_13(_macro, __VA_ARGS__)
#define TF_PP_FE_15(_macro, a, ...) _macro(a) TF_PP_FE_14(_macro, __VA_ARGS__)
#define TF_PP_FE_16(_macro, a, ...) _macro(a) TF_PP_FE_15(_macro, __VA_ARGS__)
#define TF_PP_FE_17(_macro, a, ...) _macro(a) TF_PP_FE_16(_macro, __VA_ARGS__)
#define TF_PP_FE_18(_macro, a, ...) _macro(a) TF_PP_FE_17(_macro, __VA_ARGS__)
#define TF_PP_FE_19(_macro, a, ...) _macro(a) TF_PP_FE_18(_macro, __VA_ARGS__)
#define TF_PP_FE_20(_macro, a, ...) _macro(a) TF_PP_FE_19(_macro, __VA_ARGS__)
#define TF_PP_FE_21(_macro, a, ...) _macro(a) TF_PP_FE_20(_macro, __VA_ARGS__)
#define TF_PP_FE_22(_macro, a, ...) _macro(a) TF_PP_FE_21(_macro, __VA_ARGS__)
#define TF_PP_FE_23(_macro, a, ...) _macro(a) TF_PP_FE_22(_macro, __VA_ARGS__)
#define TF_PP_FE_24(_macro, a, ...) _macro(a) TF_PP_FE_23(_macro, __VA_ARGS__)
#define TF_PP_FE_25(_macro, a, ...) _macro(a) TF_PP_FE_24(_macro, __VA_ARGS__)
#define TF_PP_FE_26(_macro, a, ...) _macro(a) TF_PP_FE_25(_macro, __VA_ARGS__)
#define TF_PP_FE_27(_macro, a, ...) _macro(a) TF_PP_FE_26(_macro, __VA_ARGS__)
#define TF_PP_FE_28(_macro, a, ...) _macro(a) TF_PP_FE_27(_macro, __VA_ARGS__)
#define TF_PP_FE_29(_macro, a, ...) _macro(a) TF_PP_FE_28(_macro, __VA_ARGS__)
#define TF_PP_FE_30(_macro, a, ...) _macro(a) TF_PP_FE_29(_macro, __VA_ARGS__)
#define TF_PP_FE_31(_macro, a, ...) _macro(a) TF_PP_FE_30(_macro, __VA_ARGS__)
#define TF_PP_FE_32(_macro, a, ...) _macro(a) TF_PP_FE_31(_macro, __VA_ARGS__)
#define TF_PP_FE_33(_macro, a, ...) _macro(a) TF_PP_FE_32(_macro, __VA_ARGS__)
#define TF_PP_FE_34(_macro, a, ...) _macro(a) TF_PP_FE_33(_macro, __VA_ARGS__)
#define TF_PP_FE_35(_macro, a, ...) _macro(a) TF_PP_FE_34(_macro, __VA_ARGS__)
#define TF_PP_FE_36(_macro, a, ...) _macro(a) TF_PP_FE_35(_macro, __VA_ARGS__)
#define TF_PP_FE_37(_macro, a, ...) _macro(a) TF_PP_FE_36(_macro, __VA_ARGS__)
#define TF_PP_FE_38(_macro, a, ...) _macro(a) TF_PP_FE_37(_macro, __VA_ARGS__)
#define TF_PP_FE_39(_macro, a, ...) _macro(a) TF_PP_FE_38(_macro, __VA_ARGS__)
#define TF_PP_FE_40(_macro, a, ...) _macro(a) TF_PP_FE_39(_macro, __VA_ARGS__)
#define TF_PP_FE_41(_macro, a, ...) _macro(a) TF_PP_FE_40(_macro, __VA_ARGS__)
#define TF_PP_FE_42(_macro, a, ...) _macro(a) TF_PP_FE_41(_macro, __VA_ARGS__)
#define TF_PP_FE_43(_macro, a, ...) _macro(a) TF_PP_FE_42(_macro, __VA_ARGS__)
#define TF_PP_FE_44(_macro, a, ...) _macro(a) TF_PP_FE_43(_macro, __VA_ARGS__)
#define TF_PP_FE_45(_macro, a, ...) _macro(a) TF_PP_FE_44(_macro, __VA_ARGS__)
#define TF_PP_FE_46(_macro, a, ...) _macro(a) TF_PP_FE_45(_macro, __VA_ARGS__)
#define TF_PP_FE_47(_macro, a, ...) _macro(a) TF_PP_FE_46(_macro, __VA_ARGS__)
#define TF_PP_FE_48(_macro, a, ...) _macro(a) TF_PP_FE_47(_macro, __VA_ARGS__)
#define TF_PP_FE_49(_macro, a, ...) _macro(a) TF_PP_FE_48(_macro, __VA_ARGS__)
#define TF_PP_FE_50(_macro, a, ...) _macro(a) TF_PP_FE_49(_macro, __VA_ARGS__)
#define TF_PP_FE_51(_macro, a, ...) _macro(a) TF_PP_FE_50(_macro, __VA_ARGS__)
#define TF_PP_FE_52(_macro, a, ...) _macro(a) TF_PP_FE_51(_macro, __VA_ARGS__)
#define TF_PP_FE_53(_macro, a, ...) _macro(a) TF_PP_FE_52(_macro, __VA_ARGS__)
#define TF_PP_FE_54(_macro, a, ...) _macro(a) TF_PP_FE_53(_macro, __VA_ARGS__)
#define TF_PP_FE_55(_macro, a, ...) _macro(a) TF_PP_FE_54(_macro, __VA_ARGS__)
#define TF_PP_FE_56(_macro, a, ...) _macro(a) TF_PP_FE_55(_macro, __VA_ARGS__)
#define TF_PP_FE_57(_macro, a, ...) _macro(a) TF_PP_FE_56(_macro, __VA_ARGS__)
#define TF_PP_FE_58(_macro, a, ...) _macro(a) TF_PP_FE_57(_macro, __VA_ARGS__)
#define TF_PP_FE_59(_macro, a, ...) _macro(a) TF_PP_FE_58(_macro, __VA_ARGS__)
#define TF_PP_FE_60(_macro, a, ...) _macro(a) TF_PP_FE_59(_macro, __VA_ARGS__)
#define TF_PP_FE_61(_macro, a, ...) _macro(a) TF_PP_FE_60(_macro, __VA_ARGS__)
#define TF_PP_FE_62(_macro, a, ...) _macro(a) TF_PP_FE_61(_macro, __VA_ARGS__)
#define TF_PP_FE_63(_macro, a, ...) _macro(a) TF_PP_FE_62(_macro, __VA_ARGS__)
#endif
#ifdef ARCH_COMPILER_MSVC
/// Expand the macro \p x on every variadic argument. For example
/// TF_PP_FOR_EACH(MACRO, foo, bar, baz) expands to MACRO(foo) MACRO(bar)
/// MACRO(baz). Supports up to 64 variadic arguments.
#define TF_PP_FOR_EACH(x, ...) \
TF_PP_CAT(TF_PP_VARIADIC_ELEM(TF_PP_VARIADIC_SIZE(__VA_ARGS__), \
TF_PP_FE_0, TF_PP_FE_1, TF_PP_FE_2, TF_PP_FE_3, TF_PP_FE_4, \
TF_PP_FE_5, TF_PP_FE_6, TF_PP_FE_7, TF_PP_FE_8, TF_PP_FE_9, \
TF_PP_FE_10, TF_PP_FE_11, TF_PP_FE_12, TF_PP_FE_13, TF_PP_FE_14, \
TF_PP_FE_15, TF_PP_FE_16, TF_PP_FE_17, TF_PP_FE_18, TF_PP_FE_19, \
TF_PP_FE_20, TF_PP_FE_21, TF_PP_FE_22, TF_PP_FE_23, TF_PP_FE_24, \
TF_PP_FE_25, TF_PP_FE_26, TF_PP_FE_27, TF_PP_FE_28, TF_PP_FE_29, \
TF_PP_FE_30, TF_PP_FE_31, TF_PP_FE_32, TF_PP_FE_33, TF_PP_FE_34, \
TF_PP_FE_35, TF_PP_FE_36, TF_PP_FE_37, TF_PP_FE_38, TF_PP_FE_39, \
TF_PP_FE_40, TF_PP_FE_41, TF_PP_FE_42, TF_PP_FE_43, TF_PP_FE_44, \
TF_PP_FE_45, TF_PP_FE_46, TF_PP_FE_47, TF_PP_FE_48, TF_PP_FE_49, \
TF_PP_FE_50, TF_PP_FE_51, TF_PP_FE_52, TF_PP_FE_53, TF_PP_FE_54, \
TF_PP_FE_55, TF_PP_FE_56, TF_PP_FE_57, TF_PP_FE_58, TF_PP_FE_59, \
TF_PP_FE_60, TF_PP_FE_61, TF_PP_FE_62, TF_PP_FE_63)(x, ##__VA_ARGS__),)
#else // Not MSVC.
/// Expand the macro \p x on every variadic argument. For example
/// TF_PP_FOR_EACH(MACRO, foo, bar, baz) expands to MACRO(foo) MACRO(bar)
/// MACRO(baz). Supports up to 64 variadic arguments.
#define TF_PP_FOR_EACH(x, ...) \
TF_PP_VARIADIC_ELEM(TF_PP_VARIADIC_SIZE(__VA_ARGS__), \
TF_PP_FE_0, TF_PP_FE_1, TF_PP_FE_2, TF_PP_FE_3, TF_PP_FE_4, \
TF_PP_FE_5, TF_PP_FE_6, TF_PP_FE_7, TF_PP_FE_8, TF_PP_FE_9, \
TF_PP_FE_10, TF_PP_FE_11, TF_PP_FE_12, TF_PP_FE_13, TF_PP_FE_14, \
TF_PP_FE_15, TF_PP_FE_16, TF_PP_FE_17, TF_PP_FE_18, TF_PP_FE_19, \
TF_PP_FE_20, TF_PP_FE_21, TF_PP_FE_22, TF_PP_FE_23, TF_PP_FE_24, \
TF_PP_FE_25, TF_PP_FE_26, TF_PP_FE_27, TF_PP_FE_28, TF_PP_FE_29, \
TF_PP_FE_30, TF_PP_FE_31, TF_PP_FE_32, TF_PP_FE_33, TF_PP_FE_34, \
TF_PP_FE_35, TF_PP_FE_36, TF_PP_FE_37, TF_PP_FE_38, TF_PP_FE_39, \
TF_PP_FE_40, TF_PP_FE_41, TF_PP_FE_42, TF_PP_FE_43, TF_PP_FE_44, \
TF_PP_FE_45, TF_PP_FE_46, TF_PP_FE_47, TF_PP_FE_48, TF_PP_FE_49, \
TF_PP_FE_50, TF_PP_FE_51, TF_PP_FE_52, TF_PP_FE_53, TF_PP_FE_54, \
TF_PP_FE_55, TF_PP_FE_56, TF_PP_FE_57, TF_PP_FE_58, TF_PP_FE_59, \
TF_PP_FE_60, TF_PP_FE_61, TF_PP_FE_62, TF_PP_FE_63)(x, ##__VA_ARGS__)
#endif
#endif // PXR_BASE_TF_PREPROCESSOR_UTILS_LITE_H
+79
View File
@@ -0,0 +1,79 @@
//
// Copyright 2020 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_3_COMPAT_H
#define PXR_BASE_TF_PY_3_COMPAT_H
/// \file tf/py3Compat.h
/// Compatibility code for supporting python 2 and 3
#include "pxr/pxr.h"
#include "pxr/base/tf/pySafePython.h"
PXR_NAMESPACE_OPEN_SCOPE
// Python 3 migrating helpers:
#if PY_MAJOR_VERSION >= 3
// These flags are needed in python 2 only, stub them out in python 3.
// In python 3 this behavior is the default. See PEP-3118
#define TfPy_TPFLAGS_HAVE_NEWBUFFER 0
#define TfPy_TPFLAGS_HAVE_GETCHARBUFFER 0
#define TfPyString_Check(a) (PyBytes_Check(a) || PyUnicode_Check(a))
#define TfPyString_AsString PyUnicode_AsUTF8
// PyInt -> PyLong remapping
#define TfPyInt_Check PyLong_Check
// Note: Slightly different semantics, the macro does not do any error checking
#define TfPyInt_AS_LONG PyLong_AsLong
// Method and module names that are changed in python 3
#define TfPyIteratorNextMethodName "__next__"
#define TfPyClassMethodFuncName "__func__"
#define TfPyBoolBuiltinFuncName "__bool__"
#define TfPyBuiltinModuleName "builtins"
#else // Python 2
#define TfPy_TPFLAGS_HAVE_NEWBUFFER Py_TPFLAGS_HAVE_NEWBUFFER
#define TfPy_TPFLAGS_HAVE_GETCHARBUFFER Py_TPFLAGS_HAVE_GETCHARBUFFER
#define TfPyInt_Check PyInt_Check
#define TfPyInt_AS_LONG PyInt_AS_LONG
#define TfPyIteratorNextMethodName "next"
#define TfPyClassMethodFuncName "im_func"
#define TfPyBoolBuiltinFuncName "__nonzero__"
#define TfPyBuiltinModuleName "__builtin__"
#define TfPyString_AsString PyString_AsString
#define TfPyString_Check PyString_Check
#endif
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_3_COMPAT_H
+150
View File
@@ -0,0 +1,150 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_ANNOTATED_BOOL_RESULT_H
#define PXR_BASE_TF_PY_ANNOTATED_BOOL_RESULT_H
#include "pxr/pxr.h"
#include "pxr/base/tf/py3Compat.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyUtils.h"
#include <boost/operators.hpp>
#include <boost/python/class.hpp>
#include <boost/python/operators.hpp>
#include <boost/python/return_by_value.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
template <class Annotation>
struct TfPyAnnotatedBoolResult :
boost::equality_comparable<TfPyAnnotatedBoolResult<Annotation>, bool>
{
TfPyAnnotatedBoolResult() {}
TfPyAnnotatedBoolResult(bool val, Annotation const &annotation) :
_val(val), _annotation(annotation) {}
bool GetValue() const {
return _val;
}
Annotation const &GetAnnotation() const {
return _annotation;
}
std::string GetRepr() const {
return GetValue() ? "True" :
"(False, " + TfPyRepr(GetAnnotation()) + ")";
}
/// Returns \c true if the result is the same as \p rhs.
bool operator==(bool rhs) const {
return _val == rhs;
}
template <class Derived>
static boost::python::class_<Derived>
Wrap(char const *name, char const *annotationName) {
typedef TfPyAnnotatedBoolResult<Annotation> This;
using namespace boost::python;
TfPyLock lock;
return class_<Derived>(name, no_init)
.def(TfPyBoolBuiltinFuncName, &Derived::GetValue)
.def("__repr__", &Derived::GetRepr)
.def(self == bool())
.def(self != bool())
.def(bool() == self)
.def(bool() != self)
// Use a helper function. We'd like to def_readonly the
// _annotation member but there are two problems with that.
// First, we can't control the return_value_policy and if the
// Annotation type has a custom to-Python converter then the
// def_readonly return_value_policy of return_internal_reference
// won't work since the object needs conversion. Second, if we
// try to use GetAnnotation() with add_property then we'll get
// a failure at runtime because Python has a Derived but
// GetAnnotation takes a TfPyAnnotatedBoolResult<Annotation>
// and boost python doesn't know the former is-a latter because
// TfPyAnnotatedBoolResult<Annotation> is not wrapped.
//
// So we provide a templated static method that takes a Derived
// and returns Annotation by value. We can add_property that
// with no problem.
.add_property(annotationName, &This::_GetAnnotation<Derived>)
.def("__getitem__", &This::_GetItem<Derived>)
;
}
using AnnotationType = Annotation;
private:
// Helper function for wrapper.
template <class Derived>
static Annotation _GetAnnotation(const Derived& x)
{
return x.GetAnnotation();
}
template <class Derived>
static boost::python::object _GetItem(const Derived& x, int i)
{
if (i == 0) {
return boost::python::object(x._val);
}
if (i == 1) {
return boost::python::object(x._annotation);
}
PyErr_SetString(PyExc_IndexError, "Index must be 0 or 1.");
boost::python::throw_error_already_set();
return boost::python::object();
}
private:
bool _val;
Annotation _annotation;
};
/// Returns \c true if the result of \p lhs is the same as \p rhs.
template <class Annotation>
bool operator==(bool lhs, TfPyAnnotatedBoolResult<Annotation>& rhs)
{
return rhs == lhs;
}
/// Returns \c false if the result of \p lhs is the same as \p rhs.
template <class Annotation>
bool operator!=(bool lhs, TfPyAnnotatedBoolResult<Annotation>& rhs)
{
return rhs != lhs;
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_ANNOTATED_BOOL_RESULT_H
+106
View File
@@ -0,0 +1,106 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_ARG_H
#define PXR_BASE_TF_PY_ARG_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <boost/python/dict.hpp>
#include <boost/python/tuple.hpp>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPyArg
///
/// Class representing a function argument.
///
/// This is similar to \c boost::python::arg, except it's not opaque and
/// provides more fields for documentation purposes.
class TfPyArg
{
public:
/// Create a TfPyArg representing an argument with the given \p name.
/// \p typeDoc and \p defaultValueDoc are optional documentation strings
/// describing the expected type and default value of this argument.
TfPyArg(const std::string& name,
const std::string& typeDoc = std::string(),
const std::string& defaultValueDoc = std::string())
: _name(name), _typeDoc(typeDoc), _defaultValueDoc(defaultValueDoc)
{ }
/// Returns argument name.
const std::string& GetName() const
{ return _name; }
/// Returns documentation for default value (if any) for this argument.
const std::string& GetDefaultValueDoc() const
{ return _defaultValueDoc; }
/// Returns documentation of type of value required by this argument.
const std::string& GetTypeDoc() const
{ return _typeDoc; }
private:
std::string _name;
std::string _typeDoc;
std::string _defaultValueDoc;
};
typedef std::vector<TfPyArg> TfPyArgs;
/// Helper function for processing optional arguments given as a tuple of
/// positional arguments and a dictionary of keyword arguments.
///
/// This function will match the given positional arguments in \p args with
/// the ordered list of allowed arguments in \p optionalArgs. Arguments that
/// are matched up in this way will be stored as (name, value) pairs and
/// merged with \p kwargs in the returned dictionary.
///
/// If \p allowExtraArgs is \c false, any unrecognized keyword or positional
/// arguments will cause a Python TypeError to be emitted. Otherwise,
/// unmatched arguments will be added to the returned tuple or dict.
TF_API
std::pair<boost::python::tuple, boost::python::dict>
TfPyProcessOptionalArgs(
const boost::python::tuple& args,
const boost::python::dict& kwargs,
const TfPyArgs& expectedArgs,
bool allowExtraArgs = false);
/// Create a doc string for a function with the given \p functionName,
/// \p requiredArguments and \p optionalArguments. An extra \p description
/// may also be supplied.
TF_API
std::string TfPyCreateFunctionDocString(
const std::string& functionName,
const TfPyArgs& requiredArguments = TfPyArgs(),
const TfPyArgs& optionalArguments = TfPyArgs(),
const std::string& description = std::string());
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_ARG_H
+92
View File
@@ -0,0 +1,92 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_CALL_H
#define PXR_BASE_TF_PY_CALL_H
/// \file tf/pyCall.h
/// Utilities for calling python callables.
///
/// These functions handle trapping python errors and converting them to \a
/// TfErrors.
#include "pxr/pxr.h"
#include "pxr/base/tf/pyError.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include <boost/python/call.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPyCall
///
/// Provide a way to call a Python callable.
///
/// Usage is as follows:
/// \code
/// return TfPyCall<RetType>(callable)(arg1, arg2, ... argN);
/// \endcode
/// Generally speaking, TfPyCall instances may be copied, assigned, destroyed,
/// and invoked without the client holding the GIL. However, if the \a Return
/// template parameter is a \a boost::python::object (or a derived class, such
/// as list or tuple) then the client must hold the GIL in order to invoke the
/// call operator.
template <typename Return>
struct TfPyCall {
/// Construct with callable \a c. Constructing with a \c
/// boost::python::object works, since those implicitly convert to \c
/// TfPyObjWrapper, however in that case the GIL must be held by the caller.
explicit TfPyCall(TfPyObjWrapper const &c) : _callable(c) {}
template <typename... Args>
Return operator()(Args... args);
private:
TfPyObjWrapper _callable;
};
template <typename Return>
template <typename... Args>
inline Return
TfPyCall<Return>::operator()(Args... args)
{
TfPyLock pyLock;
// Do *not* call through if there's an active python exception.
if (!PyErr_Occurred()) {
try {
return boost::python::call<Return>
(_callable.ptr(), args...);
} catch (boost::python::error_already_set const &) {
// Convert any exception to TF_ERRORs.
TfPyConvertPythonExceptionToTfErrors();
PyErr_Clear();
}
}
return Return();
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+39
View File
@@ -0,0 +1,39 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_CALL_CONTEXT_H
#define PXR_BASE_TF_PY_CALL_CONTEXT_H
#include "pxr/base/tf/callContext.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_API TfCallContext
Tf_PythonCallContext(char const *fileName,
char const *moduleName,
char const *functionName,
size_t line);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_CALL_CONTEXT_H
+102
View File
@@ -0,0 +1,102 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_CLASS_METHOD_H
#define PXR_BASE_TF_PY_CLASS_METHOD_H
#include "pxr/pxr.h"
#include <boost/python/class.hpp>
#include <boost/python/dict.hpp>
#include <boost/python/object.hpp>
#include <boost/python/def_visitor.hpp>
PXR_NAMESPACE_OPEN_SCOPE
namespace Tf_PyClassMethod {
using namespace boost::python;
// Visitor for wrapping functions as Python class methods.
// See typedef below for docs.
// This is very similar to the staticmethod() method on boost::python::class,
// except it uses PyClassMethod_New() instead of PyStaticMethod_New().
struct _TfPyClassMethod : def_visitor<_TfPyClassMethod>
{
friend class def_visitor_access;
_TfPyClassMethod(const std::string &methodName) :
_methodName(methodName) {}
explicit _TfPyClassMethod(const char *methodName) :
_methodName(methodName) {}
template <typename CLS>
void visit(CLS &c) const
{
PyTypeObject* self = downcast<PyTypeObject>( c.ptr() );
dict d((handle<>(borrowed(self->tp_dict))));
object method(d[_methodName]);
c.attr(_methodName.c_str()) = object(
handle<>( PyClassMethod_New((_CallableCheck)(method.ptr()) )));
}
private:
PyObject* _CallableCheck(PyObject* callable) const
{
if (PyCallable_Check(expect_non_null(callable)))
return callable;
PyErr_Format( PyExc_TypeError,
"classmethod expects callable object; got an object of type %s, "
"which is not callable",
callable->ob_type->tp_name);
throw_error_already_set();
return 0;
}
const std::string _methodName;
};
}
/// A boost.python class visitor which replaces the named method with a
/// classmethod()-wrapped one.
///
/// \code
/// void Foo( boost::python::object & pyClassObject ) { /* ... */ }
///
/// class_<...>(...)
/// .def("Foo", &Foo)
/// .def(TfPyClassMethod("Foo"))
/// ;
/// \endcode
///
typedef Tf_PyClassMethod::_TfPyClassMethod TfPyClassMethod;
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_CLASS_METHOD_H
@@ -0,0 +1,441 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_CONTAINER_CONVERSIONS_H
#define PXR_BASE_TF_PY_CONTAINER_CONVERSIONS_H
/// \file tf/pyContainerConversions.h
/// Utilities for providing C++ <-> Python container support.
/*
* Adapted (modified) from original at http://cctbx.sourceforge.net
* Original file:
* cctbx/scitbx/include/scitbx/boost_python/container_conversions.h
* License:
* http://cvs.sourceforge.net/viewcvs.py/cctbx/cctbx/
* LICENSE.txt?rev=1.2&view=markup
*/
#include "pxr/pxr.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/pyUtils.h"
#include <boost/python/list.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/to_python_converter.hpp>
#include <deque>
#include <list>
#include <set>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
// Converter from vector<string> to python list.
template <typename ContainerType>
struct TfPySequenceToPython
{
static PyObject* convert(ContainerType const &c)
{
boost::python::list result;
TF_FOR_ALL(i, c) {
result.append(*i);
}
return boost::python::incref(result.ptr());
}
};
template <typename ContainerType>
struct TfPyMapToPythonDict
{
static PyObject* convert(ContainerType const &c)
{
return boost::python::incref(TfPyCopyMapToDictionary(c).ptr());
}
};
namespace TfPyContainerConversions {
template <typename ContainerType>
struct to_tuple
{
static PyObject* convert(ContainerType const& a)
{
boost::python::list result;
typedef typename ContainerType::const_iterator const_iter;
for(const_iter p=a.begin();p!=a.end();p++) {
result.append(boost::python::object(*p));
}
return boost::python::incref(boost::python::tuple(result).ptr());
}
};
template <typename First, typename Second>
struct to_tuple<std::pair<First, Second> > {
static PyObject* convert(std::pair<First, Second> const& a)
{
boost::python::tuple result =
boost::python::make_tuple(a.first, a.second);
return boost::python::incref(result.ptr());
}
};
struct default_policy
{
static bool check_convertibility_per_element() { return false; }
template <typename ContainerType>
static bool check_size(boost::type<ContainerType>, std::size_t sz)
{
return true;
}
template <typename ContainerType>
static void assert_size(boost::type<ContainerType>, std::size_t sz) {}
template <typename ContainerType>
static void reserve(ContainerType& a, std::size_t sz) {}
};
struct fixed_size_policy
{
static bool check_convertibility_per_element() { return true; }
template <typename ContainerType>
static bool check_size(boost::type<ContainerType>, std::size_t sz)
{
return ContainerType::size() == sz;
}
template <typename ContainerType>
static void assert_size(boost::type<ContainerType>, std::size_t sz)
{
if (!check_size(boost::type<ContainerType>(), sz)) {
PyErr_SetString(PyExc_RuntimeError,
"Insufficient elements for fixed-size array.");
boost::python::throw_error_already_set();
}
}
template <typename ContainerType>
static void reserve(ContainerType& a, std::size_t sz)
{
if (sz > ContainerType::size()) {
PyErr_SetString(PyExc_RuntimeError,
"Too many elements for fixed-size array.");
boost::python::throw_error_already_set();
}
}
template <typename ContainerType, typename ValueType>
static void set_value(ContainerType& a, std::size_t i, ValueType const& v)
{
reserve(a, i+1);
a[i] = v;
}
};
struct variable_capacity_policy : default_policy
{
template <typename ContainerType>
static void reserve(ContainerType& a, std::size_t sz)
{
a.reserve(sz);
}
template <typename ContainerType, typename ValueType>
static void set_value(ContainerType& a, std::size_t i, ValueType const& v)
{
TF_AXIOM(a.size() == i);
a.push_back(v);
}
};
struct variable_capacity_all_items_convertible_policy : variable_capacity_policy
{
static bool check_convertibility_per_element() { return true; }
};
struct fixed_capacity_policy : variable_capacity_policy
{
template <typename ContainerType>
static bool check_size(boost::type<ContainerType>, std::size_t sz)
{
return ContainerType::max_size() >= sz;
}
};
struct linked_list_policy : default_policy
{
template <typename ContainerType, typename ValueType>
static void set_value(ContainerType& a, std::size_t i, ValueType const& v)
{
a.push_back(v);
}
};
struct set_policy : default_policy
{
template <typename ContainerType, typename ValueType>
static void set_value(ContainerType& a, std::size_t i, ValueType const& v)
{
a.insert(v);
}
};
template <typename ContainerType, typename ConversionPolicy>
struct from_python_sequence
{
typedef typename ContainerType::value_type container_element_type;
from_python_sequence()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<ContainerType>());
}
static void* convertible(PyObject* obj_ptr)
{
if (!( PyList_Check(obj_ptr)
|| PyTuple_Check(obj_ptr)
|| PySet_Check(obj_ptr)
|| PyFrozenSet_Check(obj_ptr)
|| PyIter_Check(obj_ptr)
|| PyRange_Check(obj_ptr)
|| ( !PyBytes_Check(obj_ptr)
&& !PyUnicode_Check(obj_ptr)
&& ( Py_TYPE(obj_ptr) == 0
|| Py_TYPE(Py_TYPE(obj_ptr)) == 0
|| Py_TYPE(Py_TYPE(obj_ptr))->tp_name == 0
|| std::strcmp(
Py_TYPE(Py_TYPE(obj_ptr))->tp_name,
"Boost.Python.class") != 0)
&& PyObject_HasAttrString(obj_ptr, "__len__")
&& PyObject_HasAttrString(obj_ptr, "__getitem__")))) return 0;
boost::python::handle<> obj_iter(
boost::python::allow_null(PyObject_GetIter(obj_ptr)));
if (!obj_iter.get()) { // must be convertible to an iterator
PyErr_Clear();
return 0;
}
if (ConversionPolicy::check_convertibility_per_element()) {
Py_ssize_t obj_size = PyObject_Length(obj_ptr);
if (obj_size < 0) { // must be a measurable sequence
PyErr_Clear();
return 0;
}
if (!ConversionPolicy::check_size(
boost::type<ContainerType>(), obj_size)) return 0;
bool is_range = PyRange_Check(obj_ptr);
std::size_t i=0;
if (!all_elements_convertible(obj_iter, is_range, i)) return 0;
if (!is_range) assert(i == (std::size_t)obj_size);
}
return obj_ptr;
}
// This loop factored out by Achim Domma to avoid Visual C++
// Internal Compiler Error.
static bool
all_elements_convertible(
boost::python::handle<>& obj_iter,
bool is_range,
std::size_t& i)
{
for(;;i++) {
boost::python::handle<> py_elem_hdl(
boost::python::allow_null(PyIter_Next(obj_iter.get())));
if (PyErr_Occurred()) {
PyErr_Clear();
return false;
}
if (!py_elem_hdl.get()) break; // end of iteration
boost::python::object py_elem_obj(py_elem_hdl);
boost::python::extract<container_element_type>
elem_proxy(py_elem_obj);
if (!elem_proxy.check()) return false;
if (is_range) break; // in a range all elements are of the same type
}
return true;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
boost::python::handle<> obj_iter(PyObject_GetIter(obj_ptr));
void* storage = (
(boost::python::converter::rvalue_from_python_storage<ContainerType>*)
data)->storage.bytes;
new (storage) ContainerType();
data->convertible = storage;
ContainerType& result = *((ContainerType*)storage);
std::size_t i=0;
for(;;i++) {
boost::python::handle<> py_elem_hdl(
boost::python::allow_null(PyIter_Next(obj_iter.get())));
if (PyErr_Occurred()) boost::python::throw_error_already_set();
if (!py_elem_hdl.get()) break; // end of iteration
boost::python::object py_elem_obj(py_elem_hdl);
boost::python::extract<container_element_type> elem_proxy(py_elem_obj);
ConversionPolicy::set_value(result, i, elem_proxy());
}
ConversionPolicy::assert_size(boost::type<ContainerType>(), i);
}
};
template <typename PairType>
struct from_python_tuple_pair {
typedef typename PairType::first_type first_type;
typedef typename PairType::second_type second_type;
from_python_tuple_pair()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<PairType>());
}
static void* convertible(PyObject* obj_ptr)
{
if (!PyTuple_Check(obj_ptr) || PyTuple_Size(obj_ptr) != 2) {
return 0;
}
boost::python::extract<first_type> e1(PyTuple_GetItem(obj_ptr, 0));
boost::python::extract<second_type> e2(PyTuple_GetItem(obj_ptr, 1));
if (!e1.check() || !e2.check()) {
return 0;
}
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
void* storage = (
(boost::python::converter::rvalue_from_python_storage<PairType>*)
data)->storage.bytes;
boost::python::extract<first_type> e1(PyTuple_GetItem(obj_ptr, 0));
boost::python::extract<second_type> e2(PyTuple_GetItem(obj_ptr, 1));
new (storage) PairType(e1(), e2());
data->convertible = storage;
}
};
template <typename ContainerType>
struct to_tuple_mapping
{
to_tuple_mapping() {
boost::python::to_python_converter<
ContainerType,
to_tuple<ContainerType> >();
}
};
template <typename ContainerType, typename ConversionPolicy>
struct tuple_mapping : to_tuple_mapping<ContainerType>
{
tuple_mapping() {
from_python_sequence<
ContainerType,
ConversionPolicy>();
}
};
template <typename ContainerType>
struct tuple_mapping_fixed_size
{
tuple_mapping_fixed_size() {
tuple_mapping<
ContainerType,
fixed_size_policy>();
}
};
template <typename ContainerType>
struct tuple_mapping_fixed_capacity
{
tuple_mapping_fixed_capacity() {
tuple_mapping<
ContainerType,
fixed_capacity_policy>();
}
};
template <typename ContainerType>
struct tuple_mapping_variable_capacity
{
tuple_mapping_variable_capacity() {
tuple_mapping<
ContainerType,
variable_capacity_policy>();
}
};
template <typename ContainerType>
struct tuple_mapping_set
{
tuple_mapping_set() {
tuple_mapping<
ContainerType,
set_policy>();
}
};
template <typename ContainerType>
struct tuple_mapping_pair
{
tuple_mapping_pair() {
boost::python::to_python_converter<
ContainerType,
to_tuple<ContainerType> >();
from_python_tuple_pair<ContainerType>();
}
};
} // namespace TfPyContainerConversions
template <class T>
void TfPyRegisterStlSequencesFromPython()
{
using namespace TfPyContainerConversions;
from_python_sequence<
std::vector<T>, variable_capacity_all_items_convertible_policy>();
from_python_sequence<
std::list<T>, variable_capacity_all_items_convertible_policy>();
from_python_sequence<
std::deque<T>, variable_capacity_all_items_convertible_policy>();
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_CONTAINER_CONVERSIONS_H
+496
View File
@@ -0,0 +1,496 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_ENUM_H
#define PXR_BASE_TF_PY_ENUM_H
/// \file tf/pyEnum.h
/// Provide facilities for wrapping enums for script.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/stringUtils.h"
#include <boost/python/class.hpp>
#include <boost/python/converter/from_python.hpp>
#include <boost/python/converter/registered.hpp>
#include <boost/python/converter/rvalue_from_python_data.hpp>
#include <boost/python/list.hpp>
#include <boost/python/object.hpp>
#include <boost/python/operators.hpp>
#include <boost/python/refcount.hpp>
#include <boost/python/scope.hpp>
#include <boost/python/to_python_converter.hpp>
#include <boost/python/tuple.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class Tf_PyEnum
///
/// Base class of all python enum classes.
class Tf_PyEnum { };
/// \class Tf_PyEnumRegistry
///
/// This is a private class that manages registered enum objects.
/// \private
class Tf_PyEnumRegistry {
public:
typedef Tf_PyEnumRegistry This;
private:
Tf_PyEnumRegistry();
virtual ~Tf_PyEnumRegistry();
friend class TfSingleton<This>;
public:
TF_API static This &GetInstance() {
return TfSingleton<This>::GetInstance();
}
TF_API
void RegisterValue(TfEnum const &e, boost::python::object const &obj);
template <typename T>
void RegisterEnumConversions() {
// Register conversions to and from python.
boost::python::to_python_converter<T, _EnumToPython<T> >();
_EnumFromPython<T>();
}
private:
template <typename T>
struct _EnumFromPython {
_EnumFromPython() {
boost::python::converter::registry::insert
(&convertible, &construct, boost::python::type_id<T>());
}
static void *convertible(PyObject *obj) {
TfHashMap<PyObject *, TfEnum, _ObjectHash> const &o2e =
Tf_PyEnumRegistry::GetInstance()._objectsToEnums;
TfHashMap<PyObject *, TfEnum, _ObjectHash>::const_iterator
i = o2e.find(obj);
// In the case of producing a TfEnum or an integer, any
// registered enum type is fine. In all other cases, the
// enum types must match.
if (boost::is_same<T, TfEnum>::value ||
(boost::is_integral<T>::value && !boost::is_enum<T>::value))
return i != o2e.end() ? obj : 0;
else
return (i != o2e.end() && i->second.IsA<T>()) ? obj : 0;
}
static void construct(PyObject *src, boost::python::converter::
rvalue_from_python_stage1_data *data) {
void *storage =
((boost::python::converter::
rvalue_from_python_storage<T> *)data)->storage.bytes;
new (storage) T(_GetEnumValue(src, (T *)0));
data->convertible = storage;
}
private:
// Overloads to explicitly allow conversion of the TfEnum integer
// value to other enum/integral types.
template <typename U>
static U _GetEnumValue(PyObject *src, U *) {
return U(Tf_PyEnumRegistry::GetInstance()._objectsToEnums[src].
GetValueAsInt());
}
static TfEnum _GetEnumValue(PyObject *src, TfEnum *) {
return Tf_PyEnumRegistry::GetInstance()._objectsToEnums[src];
}
};
template <typename T>
struct _EnumToPython {
static PyObject *convert(T const &t);
};
// Since our enum objects live as long as the registry does, we can use the
// pointer values for a hash.
struct _ObjectHash {
size_t operator()(PyObject *o) const {
return reinterpret_cast<size_t>(o);
}
};
TfHashMap<TfEnum, PyObject *, TfHash> _enumsToObjects;
TfHashMap<PyObject *, TfEnum, _ObjectHash> _objectsToEnums;
};
TF_API_TEMPLATE_CLASS(TfSingleton<Tf_PyEnumRegistry>);
// Private function used for __repr__ of wrapped enum types.
TF_API
std::string Tf_PyEnumRepr(boost::python::object const &self);
// Private base class for types which are instantiated and exposed to python
// for each registered enum type.
struct Tf_PyEnumWrapper
: public Tf_PyEnum, boost::totally_ordered<Tf_PyEnumWrapper>
{
typedef Tf_PyEnumWrapper This;
Tf_PyEnumWrapper(std::string const &n, TfEnum const &val) :
name(n), value(val) {}
long GetValue() const {
return value.GetValueAsInt();
}
std::string GetName() const{
return name;
}
std::string GetDisplayName() const {
return TfEnum::GetDisplayName(value);
}
std::string GetFullName() const {
return TfEnum::GetFullName(value);
}
friend bool operator ==(Tf_PyEnumWrapper const &self,
long other) {
return self.value.GetValueAsInt() == other;
}
friend bool operator ==(Tf_PyEnumWrapper const &lhs,
Tf_PyEnumWrapper const &rhs) {
return lhs.value == rhs.value;
}
friend bool operator <(Tf_PyEnumWrapper const &lhs,
Tf_PyEnumWrapper const &rhs)
{
// If same, not less.
if (lhs == rhs)
return false;
// If types don't match, string compare names.
if (!lhs.value.IsA(rhs.value.GetType()))
return TfEnum::GetFullName(lhs.value) <
TfEnum::GetFullName(rhs.value);
// If types do match, numerically compare values.
return lhs.GetValue() < rhs.GetValue();
}
//
// XXX Bitwise operators for Enums are a temporary measure to support the
// use of Enums as Bitmasks in libSd. It should be noted that Enums are
// NOT closed under these operators. The proper place for such operators
// is in a yet-nonexistent Bitmask type.
//
friend TfEnum operator |(Tf_PyEnumWrapper const &lhs,
Tf_PyEnumWrapper const &rhs) {
if (lhs.value.IsA(rhs.value.GetType())) {
return TfEnum(lhs.value.GetType(),
lhs.value.GetValueAsInt() |
rhs.value.GetValueAsInt());
}
TfPyThrowTypeError("Enum type mismatch");
return TfEnum();
}
friend TfEnum operator |(Tf_PyEnumWrapper const &lhs, long rhs) {
return TfEnum(lhs.value.GetType(), lhs.value.GetValueAsInt() | rhs);
}
friend TfEnum operator |(long lhs, Tf_PyEnumWrapper const &rhs) {
return TfEnum(rhs.value.GetType(), lhs | rhs.value.GetValueAsInt());
}
friend TfEnum operator &(Tf_PyEnumWrapper const &lhs,
Tf_PyEnumWrapper const &rhs) {
if (lhs.value.IsA(rhs.value.GetType())) {
return TfEnum(lhs.value.GetType(),
lhs.value.GetValueAsInt() &
rhs.value.GetValueAsInt());
}
TfPyThrowTypeError("Enum type mismatch");
return TfEnum();
}
friend TfEnum operator &(Tf_PyEnumWrapper const &lhs, long rhs) {
return TfEnum(lhs.value.GetType(), lhs.value.GetValueAsInt() & rhs);
}
friend TfEnum operator &(long lhs, Tf_PyEnumWrapper const &rhs) {
return TfEnum(rhs.value.GetType(), lhs & rhs.value.GetValueAsInt());
}
friend TfEnum operator ^(Tf_PyEnumWrapper const &lhs,
Tf_PyEnumWrapper const &rhs) {
if (lhs.value.IsA(rhs.value.GetType())) {
return TfEnum(lhs.value.GetType(),
lhs.value.GetValueAsInt() ^
rhs.value.GetValueAsInt());
}
TfPyThrowTypeError("Enum type mismatch");
return TfEnum();
}
friend TfEnum operator ^(Tf_PyEnumWrapper const &lhs, long rhs) {
return TfEnum(lhs.value.GetType(), lhs.value.GetValueAsInt() ^ rhs);
}
friend TfEnum operator ^(long lhs, Tf_PyEnumWrapper const &rhs) {
return TfEnum(rhs.value.GetType(), lhs ^ rhs.value.GetValueAsInt());
}
friend TfEnum operator ~(Tf_PyEnumWrapper const &rhs) {
return TfEnum(rhs.value.GetType(), ~rhs.value.GetValueAsInt());
}
std::string name;
TfEnum value;
};
template <typename T>
PyObject *
Tf_PyEnumRegistry::_EnumToPython<T>::convert(T const &t)
{
TfEnum e(t);
// If there is no registered enum object, create a new one of
// the appropriate type.
if (!Tf_PyEnumRegistry::GetInstance()._enumsToObjects.count(e)) {
std::string name = ArchGetDemangled(e.GetType());
name = TfStringReplace(name, " ", "_");
name = TfStringReplace(name, "::", "_");
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
name = "AutoGenerated_" + name + "_" +
TfStringify(e.GetValueAsInt());
boost::python::object wrappedVal =
boost::python::object(Tf_PyEnumWrapper(name, e));
wrappedVal.attr("_baseName") = std::string();
Tf_PyEnumRegistry::GetInstance().RegisterValue(e, wrappedVal);
}
return boost::python::
incref(Tf_PyEnumRegistry::GetInstance()._enumsToObjects[e]);
}
// Private template class which is instantiated and exposed to python for each
// registered enum type.
template <typename T>
struct Tf_TypedPyEnumWrapper : Tf_PyEnumWrapper
{
Tf_TypedPyEnumWrapper(std::string const &n, TfEnum const &val) :
Tf_PyEnumWrapper(n, val) {}
static boost::python::object GetValueFromName(const std::string& name) {
bool found = false;
const TfEnum value = TfEnum::GetValueFromName<T>(name, &found);
if (found) return boost::python::object(value);
return boost::python::object();
}
};
// Removes the MFB package prefix from name if it starts with it, and replaces
// spaces with underscores.
TF_API
std::string Tf_PyCleanEnumName(std::string name);
// Adds attribute of given name with given value to given scope.
// Issues a coding error if attribute by that name already existed.
TF_API
void Tf_PyEnumAddAttribute(boost::python::scope &s,
const std::string &name,
const boost::python::object &value);
/// \class TfPyWrapEnum
///
/// Used to wrap enum types for script.
///
/// TfPyWrapEnum provides a way to wrap enums for python, tying in with the \a
/// TfEnum system, and potentially providing automatic wrapping by using names
/// registered with the \a TfEnum system and by making some assumptions about
/// the way we structure our code. Enums that are not registered with TfEnum
/// may be manually wrapped using boost::python::enum_ instead.
///
/// Example usage. For an enum that looks like this:
/// \code
/// enum FooChoices {
/// FooFirst,
/// FooSecond,
/// FooThird
/// };
/// \endcode
///
/// Which has been registered in the \a TfEnum system and has names provided for
/// all values, it may be wrapped like this:
/// \code
/// TfPyWrapEnum<FooChoices>();
/// \endcode
///
/// The enum will appear in script as Foo.Choices.{First, Second, Third} and
/// the values will also appear as Foo.{First, Second, Third}.
///
/// An enum may be given an explicit name by passing a string to
/// TfPyWrapEnum's constructor.
///
/// If the enum is a C++11 scoped enum (aka enum class), the values will appear
/// as Foo.Choices.{First, Second, Third} in the following example:
/// \code
/// enum class FooChoices {
/// First,
/// Second,
/// Third
/// };
/// \endcode
///
// Detect scoped enums by using that the C++ standard does not allow them to
// be converted to int implicitly.
template <typename T, bool IsScopedEnum = !std::is_convertible<T, int>::value>
struct TfPyWrapEnum {
private:
typedef boost::python::class_<
Tf_TypedPyEnumWrapper<T>, boost::python::bases<Tf_PyEnumWrapper> >
_EnumPyClassType;
public:
/// Construct an enum wrapper object.
/// If \a name is provided, it is used as the name of the enum. Otherwise
/// the type name of \a T is used, with a leading MFB package name
/// stripped.
explicit TfPyWrapEnum( std::string const &name = std::string())
{
using namespace boost::python;
const bool explicitName = !name.empty();
// First, take either the given name, or the demangled type name.
std::string enumName = explicitName ? name :
TfStringReplace(ArchGetDemangled(typeid(T)), "::", ".");
// If the name is dotted, take everything before the dot as the base
// name. This is used in repr.
std::string baseName = TfStringGetBeforeSuffix(enumName);
if (baseName == enumName)
baseName = std::string();
// If the name is dotted, take the last element as the enum name.
if (!TfStringGetSuffix(enumName).empty())
enumName = TfStringGetSuffix(enumName);
// If the name was not explicitly given, then clean it up by removing
// the mfb package name prefix if it exists.
if (!explicitName) {
if (!baseName.empty())
baseName = Tf_PyCleanEnumName(baseName);
else
enumName = Tf_PyCleanEnumName(enumName);
}
if (IsScopedEnum) {
// Make the enumName appear in python representation
// for scoped enums.
if (!baseName.empty()) {
baseName += ".";
}
baseName += enumName;
}
// Make a python type for T.
_EnumPyClassType enumClass(enumName.c_str(), no_init);
enumClass.def("GetValueFromName", &Tf_TypedPyEnumWrapper<T>::GetValueFromName, arg("name"));
enumClass.staticmethod("GetValueFromName");
enumClass.setattr("_baseName", baseName);
// Register conversions for it.
Tf_PyEnumRegistry::GetInstance().RegisterEnumConversions<T>();
// Export values. Only clean names if basename is empty (i.e. the enum
// is top-level).
_ExportValues(baseName.empty(), enumClass);
// Register with Tf so that python clients of a TfType
// that represents an enum are able to get to the equivalent
// python class with .pythonclass
const TfType &type = TfType::Find<T>();
if (!type.IsUnknown())
type.DefinePythonClass(enumClass);
}
private:
/// Export all values in this enum to the enclosing scope.
/// If no explicit names have been registered, this will export the TfEnum
/// registered names and values (if any).
void _ExportValues(bool cleanNames, _EnumPyClassType &enumClass) {
boost::python::list valueList;
std::vector<std::string> names = TfEnum::GetAllNames<T>();
TF_FOR_ALL(name, names) {
bool success = false;
TfEnum enumValue = TfEnum::GetValueFromName<T>(*name, &success);
if (!success) {
continue;
}
std::string cleanedName = cleanNames ?
Tf_PyCleanEnumName(*name) : *name;
// convert value to python.
Tf_TypedPyEnumWrapper<T> wrappedValue(cleanedName, enumValue);
boost::python::object pyValue(wrappedValue);
// register it as the python object for this value.
Tf_PyEnumRegistry::GetInstance().RegisterValue(enumValue, pyValue);
// Take all the values and export them into the current scope.
std::string valueName = wrappedValue.GetName();
if (IsScopedEnum) {
// If scoped enum, enum values appear on the enumClass ...
boost::python::scope s(enumClass);
Tf_PyEnumAddAttribute(s, valueName, pyValue);
} else {
// ... otherwise, enum values appear on the enclosing scope.
boost::python::scope s;
Tf_PyEnumAddAttribute(s, valueName, pyValue);
}
valueList.append(pyValue);
}
// Add a tuple of all the values to the enum class.
enumClass.setattr("allValues", boost::python::tuple(valueList));
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_ENUM_H
+118
View File
@@ -0,0 +1,118 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_ERROR_H
#define PXR_BASE_TF_PY_ERROR_H
/// \file tf/error.h
/// Provide facilities for error handling in script.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/errorMark.h"
#include <boost/python/default_call_policies.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// Converts any \a TfError objects in \a m into python exceptions. User code
/// should generally not have to call this. User code should generally not
/// have to call this, unless it's manually bridging between C++ & Python.
TF_API
bool TfPyConvertTfErrorsToPythonException(TfErrorMark const &m);
/// Convert the current python exception to \a TfError objects and post them
/// to the error system. User code should generally not have to call this,
/// unless it's manually bridging between C++ & Python.
TF_API
void TfPyConvertPythonExceptionToTfErrors();
/// \class TfPyRaiseOnError
///
/// A boost.python call policy class which, when applied to a wrapped
/// function, will create an error mark before calling the function, and check
/// that error mark after the function has completed. If any TfErrors have
/// occurred, they will be raised as python exceptions.
///
/// This facility does not need to be used by clients in general. It is only
/// required for wrapped functions and methods that do not appear directly in an
/// extension module. For instance, the map and sequence proxy objects use
/// this, since they are created on the fly.
template <typename Base = boost::python::default_call_policies>
struct TfPyRaiseOnError : Base
{
public:
// This call policy provides a customized argument_package. We need to do
// this to store the TfErrorMark that we use to collect TfErrors that
// occurred during the call and convert them to a python exception at the
// end. It doesn't work to do this in the precall() and postcall()
// because if the call itself throws a c++ exception, the postcall() isn't
// executed and we can't destroy the TfErrorMark, leaving it dangling.
// Using the argument_package solves this since it is a local variable it
// will be destroyed whether or not the call throws. This is not really a
// publicly documented boost.python feature, however. :-/
template <class BaseArgs>
struct ErrorMarkAndArgs {
/* implicit */ErrorMarkAndArgs(BaseArgs base_) : base(base_) {}
operator const BaseArgs &() const { return base; }
operator BaseArgs &() { return base; }
BaseArgs base;
TfErrorMark errorMark;
};
typedef ErrorMarkAndArgs<typename Base::argument_package> argument_package;
/// Default constructor.
TfPyRaiseOnError() {}
// Only accept our argument_package type, since we must ensure that we're
// using it so we track a TfErrorMark.
bool precall(argument_package const &a) { return Base::precall(a); }
// Only accept our argument_package type, since we must ensure that we're
// using it so we track a TfErrorMark.
PyObject *postcall(argument_package const &a, PyObject *result) {
result = Base::postcall(a, result);
if (result && TfPyConvertTfErrorsToPythonException(a.errorMark)) {
Py_DECREF(result);
result = NULL;
}
return result;
}
};
struct Tf_PyErrorClearer {
Tf_PyErrorClearer() : clearOnDestruction(true) {}
~Tf_PyErrorClearer() {
if (clearOnDestruction)
mark.Clear();
}
void Dismiss() { clearOnDestruction = false; }
TfErrorMark mark;
bool clearOnDestruction;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_ERROR_H
+54
View File
@@ -0,0 +1,54 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/errorMark.h"
#include <boost/python/handle.hpp>
PXR_NAMESPACE_OPEN_SCOPE
struct TfPyExceptionState {
TfPyExceptionState(boost::python::handle<> const &type,
boost::python::handle<> const &value,
boost::python::handle<> const &trace) :
_type(type), _value(value), _trace(trace) {}
boost::python::handle<> const &GetType() const { return _type; }
boost::python::handle<> const &GetValue() const { return _value; }
boost::python::handle<> const &GetTrace() const { return _trace; }
void Release() {
_type.release();
_value.release();
_trace.release();
}
TF_API
std::string GetExceptionString() const;
private:
boost::python::handle<> _type, _value, _trace;
};
PXR_NAMESPACE_CLOSE_SCOPE
+207
View File
@@ -0,0 +1,207 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_FUNCTION_H
#define PXR_BASE_TF_PY_FUNCTION_H
#include "pxr/pxr.h"
#include "pxr/base/tf/pyCall.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include "pxr/base/tf/pyUtils.h"
#include <boost/python/converter/from_python.hpp>
#include <boost/python/converter/registered.hpp>
#include <boost/python/converter/rvalue_from_python_data.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/object.hpp>
#include <boost/function.hpp>
#include <functional>
PXR_NAMESPACE_OPEN_SCOPE
template <typename T>
struct TfPyFunctionFromPython;
template <typename Ret, typename... Args>
struct TfPyFunctionFromPython<Ret (Args...)>
{
struct Call
{
TfPyObjWrapper callable;
Ret operator()(Args... args) {
TfPyLock lock;
return TfPyCall<Ret>(callable)(args...);
}
};
struct CallWeak
{
TfPyObjWrapper weak;
Ret operator()(Args... args) {
using namespace boost::python;
// Attempt to get the referenced callable object.
TfPyLock lock;
object callable(handle<>(borrowed(PyWeakref_GetObject(weak.ptr()))));
if (TfPyIsNone(callable)) {
TF_WARN("Tried to call an expired python callback");
return Ret();
}
return TfPyCall<Ret>(callable)(args...);
}
};
struct CallMethod
{
TfPyObjWrapper func;
TfPyObjWrapper weakSelf;
#if PY_MAJOR_VERSION == 2
TfPyObjWrapper cls;
#endif
Ret operator()(Args... args) {
using namespace boost::python;
// Attempt to get the referenced self parameter, then build a new
// instance method and call it.
TfPyLock lock;
PyObject *self = PyWeakref_GetObject(weakSelf.ptr());
if (self == Py_None) {
TF_WARN("Tried to call a method on an expired python instance");
return Ret();
}
#if PY_MAJOR_VERSION == 2
object method(handle<>(PyMethod_New(func.ptr(), self, cls.ptr())));
#else
object method(handle<>(PyMethod_New(func.ptr(), self)));
#endif
return TfPyCall<Ret>(method)(args...);
}
};
TfPyFunctionFromPython() {
RegisterFunctionType<boost::function<Ret (Args...)>>();
RegisterFunctionType<std::function<Ret (Args...)>>();
}
template <typename FuncType>
static void
RegisterFunctionType() {
using namespace boost::python;
converter::registry::
insert(&convertible, &construct<FuncType>, type_id<FuncType>());
}
static void *convertible(PyObject *obj) {
return ((obj == Py_None) || PyCallable_Check(obj)) ? obj : 0;
}
template <typename FuncType>
static void construct(PyObject *src, boost::python::converter::
rvalue_from_python_stage1_data *data) {
using std::string;
using namespace boost::python;
void *storage = ((converter::rvalue_from_python_storage<FuncType> *)
data)->storage.bytes;
if (src == Py_None) {
new (storage) FuncType();
} else {
// In the case of instance methods, holding a strong reference will
// keep the bound 'self' argument alive indefinitely, which is
// undesirable. Unfortunately, we can't just keep a weak reference to
// the instance method, because python synthesizes these on-the-fly.
// Instead we do something like what PyQt's SIP does, and break the
// method into three parts: the class, the function, and the self
// parameter. We keep strong references to the class and the
// function, but a weak reference to 'self'. Then at call-time, if
// self has not expired, we build a new instancemethod and call it.
//
// Otherwise if the callable is a lambda (checked in a hacky way, but
// mirroring SIP), we take a strong reference.
//
// For all other callables, we attempt to take weak references to
// them. If that fails, we take a strong reference.
//
// This is all sort of contrived, but seems to have the right behavior
// for most usage patterns.
object callable(handle<>(borrowed(src)));
PyObject *pyCallable = callable.ptr();
PyObject *self =
PyMethod_Check(pyCallable) ?
PyMethod_GET_SELF(pyCallable) : NULL;
if (self) {
// Deconstruct the method and attempt to get a weak reference to
// the self instance.
#if PY_MAJOR_VERSION == 2
object cls(handle<>(borrowed(PyMethod_GET_CLASS(pyCallable))));
#endif
object func(handle<>(borrowed(PyMethod_GET_FUNCTION(
pyCallable))));
object weakSelf(handle<>(PyWeakref_NewRef(self, NULL)));
new (storage)
FuncType(CallMethod{
TfPyObjWrapper(func),
TfPyObjWrapper(weakSelf)
#if PY_MAJOR_VERSION == 2
, TfPyObjWrapper(cls)
#endif
});
} else if (PyObject_HasAttrString(pyCallable, "__name__") &&
extract<string>(callable.attr("__name__"))()
== "<lambda>") {
// Explicitly hold on to strong references to lambdas.
new (storage) FuncType(Call{TfPyObjWrapper(callable)});
} else {
// Attempt to get a weak reference to the callable.
if (PyObject *weakCallable =
PyWeakref_NewRef(pyCallable, NULL)) {
new (storage)
FuncType(
CallWeak{TfPyObjWrapper(
object(handle<>(weakCallable)))});
} else {
// Fall back to taking a strong reference.
PyErr_Clear();
new (storage) FuncType(Call{TfPyObjWrapper(callable)});
}
}
}
data->convertible = storage;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_FUNCTION_H
+270
View File
@@ -0,0 +1,270 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_IDENTITY_H
#define PXR_BASE_TF_PY_IDENTITY_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/safeTypeCompare.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/weakPtr.h"
#include <boost/python/class.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/object.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/utility.hpp>
#include "pxr/base/tf/hashmap.h"
// Specializations for boost::python::pointee and get_pointer for TfRefPtr and
// TfWeakPtr.
namespace boost { namespace python {
// TfWeakPtrFacade
template <template <class> class X, class Y>
struct pointee< PXR_NS::TfWeakPtrFacade<X, Y> > {
typedef Y type;
};
// TfRefPtr
template <typename T>
struct pointee< PXR_NS::TfRefPtr<T> > {
typedef T type;
};
}}
PXR_NAMESPACE_OPEN_SCOPE
struct Tf_PyIdentityHelper
{
// Set the identity of ptr (which derives from TfPtrBase) to be the
// python object \a obj.
TF_API
static void Set(void const *id, PyObject *obj);
// Return a new reference to the python object associated with ptr. If
// there is none, return 0.
TF_API
static PyObject *Get(void const *id);
TF_API
static void Erase(void const *id);
// Acquire a reference to the python object associated with ptrBase
// if not already acquired.
TF_API
static void Acquire(void const *id);
// Release a reference to the python object associated with ptrBase
// if we own a reference.
TF_API
static void Release(void const *id);
};
template <class Ptr>
void Tf_PyReleasePythonIdentity(Ptr const &ptr, PyObject *obj)
{
Tf_PySetPythonIdentity(ptr, obj);
Tf_PyIdentityHelper::Release(ptr.GetUniqueIdentifier());
}
void Tf_PyOwnershipRefBaseUniqueChanged(TfRefBase const *refBase,
bool isNowUnique);
struct Tf_PyOwnershipPtrMap
{
typedef TfHashMap<TfRefBase const *, void const *, TfHash>
_CacheType;
TF_API
static void Insert(TfRefBase *refBase, void const *uniqueId);
TF_API
static void const *Lookup(TfRefBase const *refBase);
TF_API
static void Erase(TfRefBase *refBase);
private:
static _CacheType _cache;
};
// Doxygen generates files whose names are mangled typenames. This is fine
// except when the filenames get longer than 256 characters. This is one case
// of that, so we'll just disable doxygen. There's no actual doxygen doc here,
// so this is fine. If/when this gets solved for real, we can remove this
// (6/06)
#ifndef doxygen
template <class Ptr, typename Enable = void>
struct Tf_PyOwnershipHelper {
template <typename U>
static void Add(U const &, const void *, PyObject *) {}
template <typename U>
static void Remove(U const &, PyObject *) {}
};
template <typename Ptr>
struct Tf_PyOwnershipHelper<Ptr,
typename boost::enable_if<
boost::mpl::and_<boost::is_same<TfRefPtr<typename Ptr::DataType>, Ptr>,
boost::is_base_of<TfRefBase, typename Ptr::DataType> > >::type>
{
struct _RefPtrHolder {
static boost::python::object
Get(Ptr const &refptr) {
TfPyLock pyLock;
_WrapIfNecessary();
return boost::python::object(_RefPtrHolder(refptr));
}
static void _WrapIfNecessary() {
TfPyLock pyLock;
if (TfPyIsNone(TfPyGetClassObject<_RefPtrHolder>())) {
std::string name =
"__" + ArchGetDemangled(typeid(typename Ptr::DataType)) +
"__RefPtrHolder";
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
name = TfStringReplace(name, "::", "_");
boost::python::class_<_RefPtrHolder>(name.c_str(),
boost::python::no_init);
}
}
private:
explicit _RefPtrHolder(Ptr const &refptr) : _refptr(refptr) {}
Ptr _refptr;
};
static void Add(Ptr ptr, const void *uniqueId, PyObject *self) {
TfPyLock pyLock;
// Make the python object keep the c++ object alive.
int ret = PyObject_SetAttrString(self, "__owner",
_RefPtrHolder::Get(ptr).ptr());
if (ret == -1) {
// CODE_COVERAGE_OFF
TF_WARN("Could not set __owner attribute on python object!");
PyErr_Clear();
return;
// CODE_COVERAGE_ON
}
TfRefBase *refBase =
static_cast<TfRefBase *>(get_pointer(ptr));
Tf_PyOwnershipPtrMap::Insert(refBase, uniqueId);
}
static void Remove(Ptr ptr, PyObject *obj) {
TfPyLock pyLock;
if (!ptr) {
// CODE_COVERAGE_OFF Can only happen if there's a bug.
TF_CODING_ERROR("Removing ownership from null/expired ptr!");
return;
// CODE_COVERAGE_ON
}
if (PyObject_HasAttrString(obj, "__owner")) {
// We are guaranteed that ptr is not unique at this point,
// as __owner has a reference and ptr is itself a
// reference. This also guarantees us that the object owns
// a reference to its python object, so we don't need to
// explicitly acquire a reference here.
TF_AXIOM(!ptr->IsUnique());
// Remove this object from the cache of refbase to uniqueId
// that we use for python-owned things.
Tf_PyOwnershipPtrMap::Erase(get_pointer(ptr));
// Remove the __owner attribute.
if (PyObject_DelAttrString(obj, "__owner") == -1) {
// CODE_COVERAGE_OFF It's hard to make this occur.
TF_WARN("Undeletable __owner attribute on python object!");
PyErr_Clear();
// CODE_COVERAGE_ON
}
}
}
};
#endif // doxygen -- see comment above.
template <typename Ptr>
struct Tf_PyIsRefPtr {
static const bool value = false;
};
template <typename T>
struct Tf_PyIsRefPtr<TfRefPtr<T> > {
static const bool value = true;
};
template <class Ptr>
typename boost::enable_if<Tf_PyIsRefPtr<Ptr> >::type
Tf_PySetPythonIdentity(Ptr const &, PyObject *)
{
}
template <class Ptr>
typename boost::disable_if<Tf_PyIsRefPtr<Ptr> >::type
Tf_PySetPythonIdentity(Ptr const &ptr, PyObject *obj)
{
if (ptr.GetUniqueIdentifier()) {
Tf_PyIdentityHelper::Set(ptr.GetUniqueIdentifier(), obj);
// Make sure we hear about it when this weak base dies so we can remove
// it from the map.
ptr.EnableExtraNotification();
}
}
template <class Ptr>
PyObject *Tf_PyGetPythonIdentity(Ptr const &ptr)
{
PyObject *ret = Tf_PyIdentityHelper::Get(ptr.GetUniqueIdentifier());
return ret;
}
template <class Ptr>
void Tf_PyRemovePythonOwnership(Ptr const &t, PyObject *obj)
{
Tf_PyOwnershipHelper<Ptr>::Remove(t, obj);
}
template <class Ptr>
void Tf_PyAddPythonOwnership(Ptr const &t, const void *uniqueId, PyObject *obj)
{
Tf_PyOwnershipHelper<Ptr>::Add(t, uniqueId, obj);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_IDENTITY_H
+96
View File
@@ -0,0 +1,96 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_INTERPRETER_H
#define PXR_BASE_TF_PY_INTERPRETER_H
/// \file tf/pyInterpreter.h
/// Python runtime utilities.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <boost/python/handle.hpp>
#include <boost/python/object.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// Starts up the python runtime.
/// IMPORTANT: The GIL will NOT be held when this returns.
/// (If Python is already initialized, the GIL will be unchanged)
///
/// The program name and arguments are set automatically. sys.argv has no
/// arguments other than an argv[0] matching the program name.
TF_API
extern void TfPyInitialize();
/// Runs the given string using PyRun_SimpleString().
///
/// Starts the interpreter if necessary. Deals with necessary thread state
/// setup.
TF_API
extern int TfPyRunSimpleString(const std::string & cmd);
/// Runs the given string using PyRun_String().
///
/// \a start is Py_eval_input, Py_single_input or Py_file_input.
/// \a globals and locals can be dictionaries to use when evaluating the
/// string in python. Defaults to reusing globals from main module. If
/// only the globals are provided, they will also be used as locals.
///
/// Starts the interpreter if necessary. Deals with necessary thread state
/// setup.
TF_API
extern boost::python::handle<>
TfPyRunString(const std::string & cmd, int start,
boost::python::object const &globals = boost::python::object(),
boost::python::object const &locals = boost::python::object()
);
/// Runs the given file using PyRun_File().
///
/// \a start is Py_eval_input, Py_single_input or Py_file_input.
/// \a globals and locals can be dictionaries to use when evaluating the
/// string in python. Defaults to reusing globals from main module. If
/// only the globals are provided, they will also be used as locals.
///
/// Starts the interpreter if necessary. Deals with necessary thread state
/// setup.
TF_API
extern boost::python::handle<>
TfPyRunFile(const std::string &filename, int start,
boost::python::object const &globals = boost::python::object(),
boost::python::object const &locals = boost::python::object()
);
/// Returns the disk path to the given module as an NSString.
///
/// Starts the interpreter if necessary. Deals with necessary thread state
/// setup.
TF_API
extern std::string TfPyGetModulePath(const std::string & moduleName);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_INTERPRETER_H
+345
View File
@@ -0,0 +1,345 @@
//
// Copyright 2021 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_INVOKE_H
#define PXR_BASE_TF_PY_INVOKE_H
/// \file
/// Flexible, high-level interface for calling Python functions.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/diagnosticLite.h"
#include "pxr/base/tf/pyError.h"
#include "pxr/base/tf/pyInterpreter.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include <boost/python/dict.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/list.hpp>
#include <boost/python/object.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
// To-Python arg conversion
#ifndef doxygen
// Convert any type to boost::python::object.
template <typename T>
boost::python::object Tf_ArgToPy(const T &value)
{
return boost::python::object(value);
}
// Convert nullptr to None.
TF_API boost::python::object Tf_ArgToPy(const std::nullptr_t &value);
#endif // !doxygen
////////////////////////////////////////////////////////////////////////////////
// Keyword arg specification
/// Wrapper object for a keyword-argument pair in a call to TfPyInvoke*. Any
/// value type may be provided, as long as it is convertible to Python.
/// Typically passed as an inline temporary object:
///
/// \code
/// const bool ok = TfPyInvoke(
/// "MyModule", "MyFunction",
/// arg1value, arg2value, TfPyKwArg("arg4", arg4value));
/// \endcode
///
/// \code{.py}
/// def MyFunction(arg1, arg2, arg3 = None, arg4 = None, arg5 = None):
/// # ...
/// \endcode
///
struct TfPyKwArg
{
template <typename T>
TfPyKwArg(const std::string &nameIn, const T &valueIn)
: name(nameIn)
{
// Constructing boost::python::object requires the GIL.
TfPyLock lock;
// The object constructor throws if the type is not convertible.
value = Tf_ArgToPy(valueIn);
}
std::string name;
TfPyObjWrapper value;
};
////////////////////////////////////////////////////////////////////////////////
// Argument collection by variadic template functions
#ifndef doxygen
// Variadic helper: trivial base case.
TF_API void Tf_BuildPyInvokeKwArgs(
boost::python::dict *kwArgsOut);
// Poisoned variadic template helper that provides an error message when
// non-keyword args are used after keyword args.
template <typename Arg, typename... RestArgs>
void Tf_BuildPyInvokeKwArgs(
boost::python::dict *kwArgsOut,
const Arg &kwArg,
RestArgs... rest)
{
// This assertion will always be false, since TfPyKwArg will select the
// overload below instead.
static_assert(
std::is_same<Arg, TfPyKwArg>::value,
"Non-keyword args not allowed after keyword args");
}
// Recursive variadic template helper for keyword args.
template <typename... RestArgs>
void Tf_BuildPyInvokeKwArgs(
boost::python::dict *kwArgsOut,
const TfPyKwArg &kwArg,
RestArgs... rest)
{
// Store mapping in kwargs dict.
(*kwArgsOut)[kwArg.name] = kwArg.value.Get();
// Recurse to handle next arg.
Tf_BuildPyInvokeKwArgs(kwArgsOut, rest...);
}
// Variadic helper: trivial base case.
TF_API void Tf_BuildPyInvokeArgs(
boost::python::list *posArgsOut,
boost::python::dict *kwArgsOut);
// Recursive general-purpose variadic template helper.
template <typename Arg, typename... RestArgs>
void Tf_BuildPyInvokeArgs(
boost::python::list *posArgsOut,
boost::python::dict *kwArgsOut,
const Arg &arg,
RestArgs... rest)
{
// Convert value to Python, and store in args list.
// The object constructor throws if the type is not convertible.
posArgsOut->append(Tf_ArgToPy(arg));
// Recurse to handle next arg.
Tf_BuildPyInvokeArgs(posArgsOut, kwArgsOut, rest...);
}
// Recursive variadic template helper for keyword args.
template <typename... RestArgs>
void Tf_BuildPyInvokeArgs(
boost::python::list *posArgsOut,
boost::python::dict *kwArgsOut,
const TfPyKwArg &kwArg,
RestArgs... rest)
{
// Switch to kwargs-only processing, enforcing (at compile time) the Python
// rule that there may not be non-kwargs after kwargs. If we relaxed this
// rule, some strange argument ordering could occur.
Tf_BuildPyInvokeKwArgs(kwArgsOut, kwArg, rest...);
}
#endif // !doxygen
////////////////////////////////////////////////////////////////////////////////
// Declarations
#ifndef doxygen
// Helper for TfPyInvokeAndExtract.
TF_API bool Tf_PyInvokeImpl(
const std::string &moduleName,
const std::string &callableExpr,
const boost::python::list &posArgs,
const boost::python::dict &kwArgs,
boost::python::object *resultObjOut);
// Forward declaration.
template <typename... Args>
bool TfPyInvokeAndReturn(
const std::string &moduleName,
const std::string &callableExpr,
boost::python::object *resultOut,
Args... args);
#endif // !doxygen
////////////////////////////////////////////////////////////////////////////////
// Main entry points
/// Call a Python function and obtain its return value.
///
/// Example:
/// \code
/// // Call MyModule.MyFunction(arg1, arg2), which returns a string.
/// std::string result;
/// const bool ok = TfPyInvokeAndExtract(
/// "MyModule", "MyFunction", &result, arg1Value, arg2Value);
/// \endcode
///
/// \p moduleName is the name of the module in which to find the function. This
/// name will be directly imported in an \c import statement, so anything that
/// you know is in \c sys.path should work. The module name will also be
/// prepended to \p callableExpr to look up the function.
///
/// \p callableExpr is a Python expression that, when appended to \p moduleName
/// (with an intervening dot), yields a callable object. Typically this is just
/// a function name, optionally prefixed with object names (such as a class in
/// which the callable resides).
///
/// \p resultOut is a pointer that will receive the Python function's return
/// value. A from-Python converter must be registered for the type of \c
/// *resultOut.
///
/// \p args is zero or more function arguments, of any types for which to-Python
/// conversions are registered. Any \c nullptr arguments are converted to \c
/// None. \p args may also contain TfPyKwArg objects to pass keyword arguments.
/// As in Python, once a keyword argument is passed, all remaining arguments
/// must also be keyword arguments.
///
/// The return value of TfPyInvokeAndExtract is true if the call completed,
/// false otherwise. When the return value is false, at least one TfError
/// should have been raised, describing the failure. TfPyInvokeAndExtract never
/// raises exceptions.
///
/// It should be safe to call this function without doing any other setup
/// first. It is not necessary to call TfPyInitialize or lock the GIL; this
/// function does those things itself.
///
/// If you don't need the function's return value, call TfPyInvoke instead.
///
/// If you need the function's return value, but the return value isn't
/// guaranteed to be a consistent type that's convertible to C++, call
/// TfPyInvokeAndReturn instead. This includes cases where the function's
/// return value may be \c None.
///
template <typename Result, typename... Args>
bool TfPyInvokeAndExtract(
const std::string &moduleName,
const std::string &callableExpr,
Result *resultOut,
Args... args)
{
if (!resultOut) {
TF_CODING_ERROR("Bad pointer to TfPyInvokeAndExtract");
return false;
}
// Init Python and grab the GIL.
TfPyInitialize();
TfPyLock lock;
boost::python::object resultObj;
if (!TfPyInvokeAndReturn(
moduleName, callableExpr, &resultObj, args...)) {
return false;
}
// Extract return value.
boost::python::extract<Result> extractor(resultObj);
if (!extractor.check()) {
TF_CODING_ERROR("Result type mismatched or not convertible");
return false;
}
*resultOut = extractor();
return true;
}
/// A version of TfPyInvokeAndExtract that provides the Python function's return
/// value as a \c boost::python::object, rather than extracting a particular C++
/// type from it.
///
template <typename... Args>
bool TfPyInvokeAndReturn(
const std::string &moduleName,
const std::string &callableExpr,
boost::python::object *resultOut,
Args... args)
{
if (!resultOut) {
TF_CODING_ERROR("Bad pointer to TfPyInvokeAndExtract");
return false;
}
// Init Python and grab the GIL.
TfPyInitialize();
TfPyLock lock;
try {
// Convert args to Python and store in list+dict form.
boost::python::list posArgs;
boost::python::dict kwArgs;
Tf_BuildPyInvokeArgs(&posArgs, &kwArgs, args...);
// Import, find callable, and call.
if (!Tf_PyInvokeImpl(
moduleName, callableExpr, posArgs, kwArgs, resultOut)) {
return false;
}
}
catch (boost::python::error_already_set const &) {
// Handle exceptions.
TfPyConvertPythonExceptionToTfErrors();
PyErr_Clear();
return false;
}
return true;
}
/// A version of TfPyInvokeAndExtract that ignores the Python function's return
/// value.
///
template <typename... Args>
bool TfPyInvoke(
const std::string &moduleName,
const std::string &callableExpr,
Args... args)
{
// Init Python and grab the GIL.
TfPyInitialize();
TfPyLock lock;
boost::python::object ignoredResult;
return TfPyInvokeAndReturn(
moduleName, callableExpr, &ignoredResult, args...);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_INVOKE_H
+202
View File
@@ -0,0 +1,202 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_LOCK_H
#define PXR_BASE_TF_PY_LOCK_H
#include "pxr/pxr.h"
#ifdef PXR_PYTHON_SUPPORT_ENABLED
#include "pxr/base/tf/pySafePython.h"
#include "pxr/base/tf/api.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPyLock
///
/// Convenience class for accessing the Python Global Interpreter Lock.
///
/// The Python API is not thread-safe. Accessing the Python API from outside
/// the context of Python execution requires extra care when multiple threads
/// may be present. There are various schemes for how this should be done,
/// and the conventions have been changing with Python versions through 2.X.
///
/// This class provides a convenient and centralized location for managing the
/// Python Global Interpreter Lock and related Python Thread State.
///
/// The easiest way to use this class is to simply create a local variable in
/// any function that will access the Python API. Upon construction, this will
/// acquire the Python lock and establish the correct thread state for the
/// caller. Upon exit from the current scope, when the instance is destroyed,
/// the thread state will be restored and the lock will be released.
///
/// \code
/// void MyFunc()
/// {
/// TfPyLock dummy;
/// ...(access Python API)...
/// }
/// \endcode
///
/// If you need to temporarily release the lock during execution, (to perform
/// blocking I/O for example), you can call Release() explicitly, then call
/// Acquire() again to reclaim the lock.
///
/// \code
/// void MyFunc()
/// {
/// TfPyLock pyLock;
/// ...(access Python API)...
/// pyLock.Release(); // let other threads run while we're blocked
/// ...(some blocking I/O or long running operation)...
/// pyLock.Acquire();
/// ...(more access to Python API)...
/// }
/// \endcode
///
/// Note that it IS EXPLICITLY OK to recursively create instances of this
/// class, and thus recursively acquire the GIL and thread state. It is NOT OK
/// to recursively attempt to Acquire() the same instance, that will have no
/// effect and will generate a diagnostic warning.
///
/// This class also provides an exception-safe way to release the GIL
/// temporarily for blocking calls, like Py_BEGIN/END_ALLOW_THREADS in the
/// Python C API.
///
/// \code
/// void MyFunc()
/// {
/// TfPyLock lock;
/// ...(access Python API)...
/// lock.BeginAllowThreads(); // totally unlock the GIL temporarily.
/// ...(some blocking I/O or long running operation)...
/// lock.EndAllowThreads();
/// ...(more access to Python API)...
/// }
/// \endcode
///
/// This looks similar to the above example using \a Release(), but it is
/// different. The Python lock is recursive, so the call to \a Release() is
/// not guaranteed to actually release the lock, it just releases the deepest
/// lock. In contrast \a BeginAllowThreads() will fully unlock the GIL so that
/// other threads can run temporarily regardless of how many times the lock is
/// recursively taken.
///
/// The valid states and transitions for this class are as follows.
///
/// State Valid Transitions
/// --------------------------------------------------------------
/// Released Acquire() -> Acquired
/// Acquired Release() -> Released, BeginAllowThreads() -> AllowsThreads
/// AllowsThreads EndAllowThreads() -> Acquired
///
/// Note that upon construction the class is in the Acquired state. Upon
/// destruction, the class will move to the Released state.
///
/// \warning Instances of this class should only be used as automatic (stack)
/// variables, or in thread local storage. DO NOT create a single instance
/// that could be shared across multiple threads.
///
class TfPyLock {
public:
/// Acquires the Python GIL and swaps in callers thread state.
TF_API TfPyLock();
/// Releases Python GIL and restores prior threads state.
TF_API ~TfPyLock();
/// (Re)acquires GIL and thread state, if previously released.
TF_API void Acquire();
/// Explicitly releases GIL and thread state.
TF_API void Release();
/// Unlock the GIL temporarily to allow other threads to use python.
/// Typically this is used to unblock threads during operations like
/// blocking I/O. The lock must be acquired when called.
TF_API void BeginAllowThreads();
/// End allowing other threads, reacquiring the lock state.
/// \a BeginAllowThreads must have been successfully called first.
TF_API void EndAllowThreads();
private:
// Non-acquiring constructor for TfPyEnsureGILUnlockedObj's use.
friend struct TfPyEnsureGILUnlockedObj;
enum _UnlockedTag { _ConstructUnlocked };
explicit TfPyLock(_UnlockedTag);
PyGILState_STATE _gilState;
PyThreadState *_savedState;
bool _acquired:1;
bool _allowingThreads:1;
};
// Helper class for TF_PY_ALLOW_THREADS_IN_SCOPE()
struct TfPyEnsureGILUnlockedObj
{
// Do nothing if the current thread does not have the GIL, otherwise unlock
// the GIL, and relock upon destruction.
TF_API TfPyEnsureGILUnlockedObj();
private:
TfPyLock _lock;
};
/// If the current thread of execution has the python GIL, release it,
/// allowing python threads to run, then upon leaving the current scope
/// reacquire the python GIL. Otherwise, do nothing.
///
/// For example:
/// \code
/// {
/// TF_PY_ALLOW_THREADS_IN_SCOPE();
/// // ... long running or blocking operation ...
/// }
/// \endcode
///
/// This is functionally similar to the following, except that it does nothing
/// in case the current thread of execution does not have the GIL.
///
/// \code
/// {
/// TfPyLock lock; lock.BeginAllowThreads();
/// // ... long running or blocking operation ...
/// }
/// \endcode
///
/// \hideinitializer
#define TF_PY_ALLOW_THREADS_IN_SCOPE() \
TfPyEnsureGILUnlockedObj __py_lock_allow_threads__
PXR_NAMESPACE_CLOSE_SCOPE
#else
// When python is disabled, we stub this macro out to nothing.
#define TF_PY_ALLOW_THREADS_IN_SCOPE()
#endif // PXR_PYTHON_SUPPORT_ENABLED
#endif // PXR_BASE_TF_PY_LOCK_H
+172
View File
@@ -0,0 +1,172 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifdef PXR_BASE_TF_PY_MODULE_H
#error This file should only be included once in any given source (.cpp) file.
#endif
#define PXR_BASE_TF_PY_MODULE_H
#include "pxr/pxr.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include <boost/preprocessor/cat.hpp>
#include <boost/python/module.hpp>
// Helper macros for module files. If you implement your wrappers for classes
// as functions named wrapClassName(), then you can create your module like
// this:
//
// TF_WRAP_MODULE(ModuleName) {
// TF_WRAP(ClassName1);
// TF_WRAP(ClassName2);
// TF_WRAP(ClassName3);
// }
//
// Forward declare the function that will be provided that does the wrapping.
static void WrapModule();
PXR_NAMESPACE_OPEN_SCOPE
TF_API
void Tf_PyInitWrapModule(void (*wrapModule)(),
const char* packageModule,
const char* packageName,
const char* packageTag,
const char* packageTag2);
ARCH_EXPORT
void BOOST_PP_CAT(init_module_, MFB_PACKAGE_NAME)() {
Tf_PyInitWrapModule(
WrapModule,
TF_PP_STRINGIZE(MFB_PACKAGE_MODULE),
TF_PP_STRINGIZE(MFB_ALT_PACKAGE_NAME),
"Wrap " TF_PP_STRINGIZE(MFB_ALT_PACKAGE_NAME),
TF_PP_STRINGIZE(MFB_PACKAGE_NAME)
);
}
PXR_NAMESPACE_CLOSE_SCOPE
#if PY_MAJOR_VERSION == 2
// When we generate boost python bindings for a library named Foo,
// we generate a python package that has __init__.py and _Foo.so,
// and we put all the python bindings in _Foo.so. The __init__.py
// file imports _Foo and then publishes _Foo's symbols as its own.
// Since the module with the bindings is named _Foo, the init routine
// must be named init_Foo. This little block produces that function.
//
extern "C"
ARCH_EXPORT
void BOOST_PP_CAT(init_, MFB_PACKAGE_NAME)() {
PXR_NAMESPACE_USING_DIRECTIVE
boost::python::detail::init_module
(TF_PP_STRINGIZE(BOOST_PP_CAT(_,MFB_PACKAGE_NAME)),
TF_PP_CAT(&init_module_, MFB_PACKAGE_NAME));
}
// We also support the case where both the library contents and the
// python bindings go into libfoo.so. We still generate a package named foo
// but the __init__.py file in the package foo imports libfoo and
// publishes it's symbols as its own. Since the module with the
// bindings is named libfoo, the init routine must be named initlibfoo.
// This little block produces that function.
//
// So there are two init routines in every library, but only the one
// that matches the name of the python module will be called by python
// when the module is imported. So the total cost is a 1-line
// function that doesn't get called.
//
extern "C"
ARCH_EXPORT
void BOOST_PP_CAT(initlib, MFB_PACKAGE_NAME)() {
PXR_NAMESPACE_USING_DIRECTIVE
boost::python::detail::init_module
(TF_PP_STRINGIZE(BOOST_PP_CAT(lib,MFB_PACKAGE_NAME)),
TF_PP_CAT(&init_module_, MFB_PACKAGE_NAME));
}
#else // Python 3:
// These functions serve the same purpose as the python 2 implementations
// above, but are updated for the overhauled approach to module initialization
// in python 3. In python 3 init<name> is replaced by PyInit_<name>, and
// initlib<name> becomes PyInit_lib<name>. The init_module function still
// exists, but now takes a struct of input values instead of a list of
// parameters. Also, these functions now return a PyObject* instead of void.
//
// See https://docs.python.org/3/c-api/module.html#initializing-c-modules_
//
extern "C"
ARCH_EXPORT
PyObject* BOOST_PP_CAT(PyInit__, MFB_PACKAGE_NAME)() {
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
TF_PP_STRINGIZE(BOOST_PP_CAT(_, MFB_PACKAGE_NAME)), // m_name
0, // m_doc
-1, // m_size
NULL, // m_methods
0, // m_reload
0, // m_traverse
0, // m_clear
0, // m_free
};
PXR_NAMESPACE_USING_DIRECTIVE
return boost::python::detail::init_module(moduledef,
BOOST_PP_CAT(init_module_, MFB_PACKAGE_NAME));
}
extern "C"
ARCH_EXPORT
PyObject* BOOST_PP_CAT(PyInit_lib, MFB_PACKAGE_NAME)() {
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
TF_PP_STRINGIZE(BOOST_PP_CAT(lib, MFB_PACKAGE_NAME)), // m_name
0, // m_doc
-1, // m_size
NULL, // m_methods
0, // m_reload
0, // m_traverse
0, // m_clear
0, // m_free
};
PXR_NAMESPACE_USING_DIRECTIVE
return boost::python::detail::init_module(moduledef,
BOOST_PP_CAT(init_module_, MFB_PACKAGE_NAME));
}
#endif
#define TF_WRAP_MODULE static void WrapModule()
// Declares and calls the class wrapper for x
#define TF_WRAP(x) ARCH_HIDDEN void wrap ## x (); wrap ## x ()
+59
View File
@@ -0,0 +1,59 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_MODULE_NOTICE_H
#define PXR_BASE_TF_PY_MODULE_NOTICE_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/notice.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPyModuleWasLoaded
///
/// A \a TfNotice that is sent when a script module is loaded. Since many
/// modules may be loaded at once, listeners are encouraged to defer work
/// triggered by this notice to the end of an application iteration. This, of
/// course, is good practice in general.
///
class TfPyModuleWasLoaded : public TfNotice {
public:
explicit TfPyModuleWasLoaded(std::string const &name) : _name(name) {}
TF_API
virtual ~TfPyModuleWasLoaded();
/// Return the name of the module that was loaded.
std::string const &GetName() { return _name; }
private:
std::string _name;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_MODULE_NOTICE_H
+166
View File
@@ -0,0 +1,166 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_NOTICE_WRAPPER_H
#define PXR_BASE_TF_PY_NOTICE_WRAPPER_H
#include "pxr/pxr.h"
#include "pxr/base/tf/notice.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyObjectFinder.h"
#include "pxr/base/tf/wrapTypeHelpers.h"
#include <boost/mpl/and.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/or.hpp>
#include <boost/python/bases.hpp>
#include <boost/python/class.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/handle.hpp>
#include <type_traits>
#include <map>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
struct Tf_PyNoticeObjectGenerator {
typedef Tf_PyNoticeObjectGenerator This;
typedef boost::python::object (*MakeObjectFunc)(TfNotice const &);
// Register the generator for notice type T.
template <typename T>
static void Register() {
// XXX this stuff should be keyed directly off TfType now
(*_generators)[typeid(T).name()] = This::_Generate<T>;
}
// Produce a boost::python::object for the correct derived type of \a n.
TF_API static boost::python::object Invoke(TfNotice const &n);
private:
template <typename T>
static boost::python::object _Generate(TfNotice const &n) {
// Python locking is left to the caller.
return boost::python::object(static_cast<T const &>(n));
}
static MakeObjectFunc _Lookup(TfNotice const &n);
TF_API static TfStaticData<std::map<std::string, MakeObjectFunc> > _generators;
};
struct TfPyNoticeWrapperBase : public TfType::PyPolymorphicBase {
TF_API virtual ~TfPyNoticeWrapperBase();
virtual boost::python::handle<> GetNoticePythonObject() const = 0;
};
template <class Notice>
struct Tf_PyNoticeObjectFinder : public Tf_PyObjectFinderBase {
virtual ~Tf_PyNoticeObjectFinder() {}
virtual boost::python::object Find(void const *objPtr) const {
using namespace boost::python;
TfPyLock lock;
Notice const *wrapper = static_cast<Notice const *>(objPtr);
return wrapper ? object(wrapper->GetNoticePythonObject()) : object();
}
};
template <typename NoticeType, typename BaseType>
struct TfPyNoticeWrapper : public NoticeType, public TfPyNoticeWrapperBase {
private:
static_assert(std::is_base_of<TfNotice, NoticeType>::value
|| std::is_same<TfNotice, NoticeType>::value,
"Notice type must be derived from or equal to TfNotice.");
static_assert(std::is_base_of<TfNotice, BaseType>::value
|| std::is_same<TfNotice, BaseType>::value,
"BaseType type must be derived from or equal to TfNotice.");
static_assert(std::is_base_of<BaseType, NoticeType>::value
|| (std::is_same<NoticeType, TfNotice>::value
&& std::is_same<BaseType, TfNotice>::value),
"BaseType type must be a base of notice, unless both "
"BaseType and Notice type are equal to TfNotice.");
public:
typedef TfPyNoticeWrapper<NoticeType, BaseType> This;
// If Notice is really TfNotice, then this is the root of the hierarchy and
// bases is empty, otherwise bases contains the base class.
typedef typename boost::mpl::if_<
boost::is_same<NoticeType, TfNotice>
, boost::python::bases<>, boost::python::bases<BaseType> >::type Bases;
typedef boost::python::class_<NoticeType, This, Bases> ClassType;
static ClassType Wrap(std::string const &name = std::string()) {
std::string wrappedName = name;
if (wrappedName.empty()) {
// Assume they want the last bit of a qualified name.
wrappedName = TfType::Find<NoticeType>().GetTypeName();
if (!TfStringGetSuffix(wrappedName, ':').empty())
wrappedName = TfStringGetSuffix(wrappedName, ':');
}
Tf_PyNoticeObjectGenerator::Register<NoticeType>();
Tf_RegisterPythonObjectFinderInternal
(typeid(TfPyNoticeWrapper),
new Tf_PyNoticeObjectFinder<TfPyNoticeWrapper>);
return ClassType(wrappedName.c_str(), boost::python::no_init)
.def(TfTypePythonClass());
}
// Implement the base class's virtual method.
virtual boost::python::handle<> GetNoticePythonObject() const {
TfPyLock lock;
return boost::python::handle<>(boost::python::borrowed(_self));
}
// Arbitrary argument constructor (with a leading PyObject *) which
// forwards to the base Notice class's constructor.
template <typename... Args>
TfPyNoticeWrapper(PyObject *self, Args... args)
: NoticeType(args...)
, _self(self) {}
private:
PyObject *_self;
};
#define TF_INSTANTIATE_NOTICE_WRAPPER(T, Base) \
TF_REGISTRY_FUNCTION(TfType) \
{ \
TfType::Define< TfPyNoticeWrapper<T, Base>, \
TfType::Bases<Base> >(); \
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_NOTICE_WRAPPER_H
+131
View File
@@ -0,0 +1,131 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_OBJ_WRAPPER_H
#define PXR_BASE_TF_PY_OBJ_WRAPPER_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <boost/functional/hash.hpp>
#include <boost/python/object_fwd.hpp>
#include <boost/python/object_operators.hpp>
#include <iosfwd>
#include <memory>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPyObjWrapper
///
/// Boost Python object wrapper.
///
/// Provides a wrapper around boost::python::object that works correctly for the
/// following basic operations regardless of the GIL state: default construction,
/// copy construction, assignment, (in)equality comparison, hash_value(), and
/// destruction.
///
/// None of those work correctly in the presence of an unlocked GIL for
/// boost::python::object. This class only actually acquires the GIL for default
/// construction, destruction and for some (in)equality comparisons. The other
/// operations do not require taking the GIL.
///
/// This is primarily useful in cases where a boost::python::object might be
/// destroyed without a locked GIL by a client blind to that fact. This occurs
/// when a registry, for example, holds type-erased objects. If one
/// of the type-erased objects in the registry happens to hold a
/// boost::python::object, that type-erased object must be destroyed while the
/// GIL is held but it's unreasonable to require that the registry know that.
/// This class helps solve that problem.
///
/// This class also provides many of the operators that boost::python::object
/// provides, by virtue of deriving from boost::python::api::object_operators<T>.
/// However it is important to note that callers must ensure the GIL is held
/// before using these operators!
class TfPyObjWrapper
: public boost::python::api::object_operators<TfPyObjWrapper>
{
typedef boost::python::object object;
public:
/// Default construct a TfPyObjWrapper holding a reference to python None.
/// The GIL need not be held by the caller.
TF_API TfPyObjWrapper();
/// Construct a TfPyObjectWrapper wrapping \a obj.
/// The GIL must be held by the caller. Note, allowing the implicit
/// conversion is intended here.
TF_API TfPyObjWrapper(object obj);
/// Underlying object access.
/// This method returns a reference, so technically, the GIL need not be
/// held to call this. However, the caller is strongly advised to ensure
/// the GIL is held, since assigning this object to another or otherwise
/// operating on the returned object requires it.
object const &Get() const {
return *_objectPtr;
}
/// Underlying PyObject* access.
/// This method returns a pointer, so technically, the GIL need not be
/// held to call this. However, the caller is strongly advised to ensure
/// the GIL is held, since assigning this object to another or otherwise
/// operating on the returned object requires it. The returned PyObject *
/// is a "borrowed reference", meaning that the underlying object's
/// reference count has not been incremented on behalf of the caller.
TF_API PyObject *ptr() const;
/// Produce a hash code for this object.
/// Note that this does not attempt to hash the underlying python object,
/// it returns a hash code that's suitable for hash-table lookup of
/// TfPyObjWrapper instances, and does not require taking the python lock.
friend inline size_t hash_value(TfPyObjWrapper const &o) {
return (size_t) o.ptr();
}
/// Equality.
/// Returns true if \a other refers to the same python object.
TF_API bool operator==(TfPyObjWrapper const &other) const;
/// Inequality.
/// Returns false if \a other refers to the same python object.
TF_API bool operator!=(TfPyObjWrapper const &other) const;
private:
// Befriend object_operators to allow it access to implicit conversion to
// boost::python::object.
friend class boost::python::api::object_operators<TfPyObjWrapper>;
operator object const &() const {
return Get();
}
// Store a shared_ptr to a python object.
std::shared_ptr<object> _objectPtr;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_OBJ_WRAPPER_H
+71
View File
@@ -0,0 +1,71 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_OBJECT_FINDER_H
#define PXR_BASE_TF_PY_OBJECT_FINDER_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/pyIdentity.h"
#include <boost/python/handle.hpp>
#include <boost/python/object.hpp>
#include <typeinfo>
PXR_NAMESPACE_OPEN_SCOPE
struct Tf_PyObjectFinderBase {
TF_API virtual ~Tf_PyObjectFinderBase();
virtual boost::python::object Find(void const *objPtr) const = 0;
};
template <class T, class PtrType>
struct Tf_PyObjectFinder : public Tf_PyObjectFinderBase {
virtual ~Tf_PyObjectFinder() {}
virtual boost::python::object Find(void const *objPtr) const {
using namespace boost::python;
TfPyLock lock;
void *p = const_cast<void *>(objPtr);
PyObject *obj = Tf_PyGetPythonIdentity(PtrType(static_cast<T *>(p)));
return obj ? object(handle<>(obj)) : object();
}
};
TF_API
void Tf_RegisterPythonObjectFinderInternal(std::type_info const &type,
Tf_PyObjectFinderBase const *finder);
template <class T, class PtrType>
void Tf_RegisterPythonObjectFinder() {
Tf_RegisterPythonObjectFinderInternal(typeid(T),
new Tf_PyObjectFinder<T, PtrType>());
}
TF_API boost::python::object
Tf_FindPythonObject(void const *objPtr, std::type_info const &type);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_OBJECT_FINDER_H
+121
View File
@@ -0,0 +1,121 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_OPTIONAL_H
#define PXR_BASE_TF_PY_OPTIONAL_H
/// \file tf/pyOptional.h
#include "pxr/pxr.h"
#include "pxr/base/tf/pyUtils.h"
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <boost/python/converter/from_python.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/to_python_converter.hpp>
#include <boost/python/to_python_value.hpp>
PXR_NAMESPACE_OPEN_SCOPE
// Adapted from original at:
// http://mail.python.org/pipermail/cplusplus-sig/2007-May/012003.html
namespace TfPyOptional {
template <typename T, typename TfromPy>
struct object_from_python
{
object_from_python() {
boost::python::converter::registry::push_back
(&TfromPy::convertible, &TfromPy::construct,
boost::python::type_id<T>());
}
};
template <typename T, typename TtoPy, typename TfromPy>
struct register_python_conversion
{
register_python_conversion() {
boost::python::to_python_converter<T, TtoPy>();
object_from_python<T, TfromPy>();
}
};
template <typename T>
struct python_optional : public boost::noncopyable
{
struct optional_to_python
{
static PyObject * convert(const boost::optional<T>& value)
{
if (value) {
boost::python::object obj = TfPyObject(*value);
Py_INCREF(obj.ptr());
return obj.ptr();
}
return boost::python::detail::none();
}
};
struct optional_from_python
{
static void * convertible(PyObject * source)
{
using namespace boost::python::converter;
if ((source == Py_None) || boost::python::extract<T>(source).check())
return source;
return NULL;
}
static void construct(PyObject * source,
boost::python::converter::rvalue_from_python_stage1_data * data)
{
using namespace boost::python::converter;
void * const storage =
((rvalue_from_python_storage<T> *)data)->storage.bytes;
if (data->convertible == Py_None) {
new (storage) boost::optional<T>(); // An uninitialized optional
} else {
new (storage) boost::optional<T>(boost::python::extract<T>(source));
}
data->convertible = storage;
}
};
explicit python_optional() {
register_python_conversion<boost::optional<T>,
optional_to_python, optional_from_python>();
}
};
} // namespace TfPyOptional
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_OPTIONAL_H
+152
View File
@@ -0,0 +1,152 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_OVERRIDE_H
#define PXR_BASE_TF_PY_OVERRIDE_H
#include "pxr/pxr.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyObjWrapper.h"
#include <boost/python/override.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfPyMethodResult
///
/// A reimplementation of boost::python::detail::method_result.
///
/// This class is reimplemented from the boost class simply because the
/// provided class only allows construction from it's friended class
/// boost::python::override, which we also reimplement below.
///
/// \see TfPyOverride
class TfPyMethodResult
{
private:
/// Clients must hold GIL to construct.
friend class TfPyOverride;
explicit TfPyMethodResult(PyObject* x)
: m_obj(x)
{}
public:
/// Implement copy to do python refcounting while holding the GIL.
TfPyMethodResult(TfPyMethodResult const &other);
/// Implement dtor to do python refcounting while holding the GIL.
~TfPyMethodResult();
/// Implement assign to do python refcounting while holding the GIL.
TfPyMethodResult &operator=(TfPyMethodResult const &other);
template <class T>
operator T()
{
TfPyLock lock;
boost::python::converter::return_from_python<T> converter;
return converter(m_obj.release());
}
template <class T>
operator T&() const
{
TfPyLock lock;
boost::python::converter::return_from_python<T&> converter;
return converter(
const_cast<boost::python::handle<>&>(m_obj).release());
}
template <class T>
T as(boost::type<T>* = 0)
{
TfPyLock lock;
boost::python::converter::return_from_python<T> converter;
return converter(m_obj.release());
}
template <class T>
T unchecked(boost::type<T>* = 0)
{
TfPyLock lock;
return boost::python::extract<T>(m_obj)();
}
private:
mutable boost::python::handle<> m_obj;
};
/// \class TfPyOverride
///
/// A reimplementation of boost::python::override.
///
/// This class is reimplemented from the boost class simply because the
/// provided class only allows construction from, ultimately,
/// boost::python::wrapper::get_override(). Unfortunately, that method
/// returns the wrong result when the overridden function we are asking about
/// lives not on the directly wrapped C++ class, but a wrapped ancestor.
/// So we provide our own version, TfPyOverride, with a public constructor.
///
/// Note that clients must have the python GIL when constructing a
/// TfPyOverride object.
///
class TfPyOverride : public TfPyObjWrapper
{
// Helper to generate Py_BuildValue-style format strings at compile time.
template <typename Arg>
constexpr static char _PyObjArg()
{
return 'O';
}
public:
/// Clients must hold the GIL to construct.
TfPyOverride(boost::python::handle<> callable)
: TfPyObjWrapper(boost::python::object(callable))
{}
/// Call the override.
/// Clients need not hold the GIL to invoke the call operator.
template <typename... Args>
TfPyMethodResult
operator()(Args const&... args) const
{
TfPyLock lock;
// Use the Args parameter pack together with the _PyObjArg helper to
// unpack the right number of 'O' elements into the format string.
static const char pyCallFormat[] =
{ '(', _PyObjArg<Args>()..., ')', '\0' };
TfPyMethodResult x(
PyEval_CallFunction(
this->ptr(),
const_cast<char*>(pyCallFormat),
boost::python::converter::arg_to_python<Args>(args).get()...));
return x;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_OVERRIDE_H
+272
View File
@@ -0,0 +1,272 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_POLYMORPHIC_H
#define PXR_BASE_TF_PY_POLYMORPHIC_H
/// \file tf/pyPolymorphic.h
#include "pxr/pxr.h"
#include "pxr/base/tf/pyOverride.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/pyCall.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/type.h"
#include <boost/python/object/class_detail.hpp>
#include <boost/python/wrapper.hpp>
#include <boost/type_traits.hpp>
#include <boost/python/has_back_reference.hpp>
#include <functional>
#include <type_traits>
// TODO: All this stuff with holding onto the class needs to go away.
PXR_NAMESPACE_OPEN_SCOPE
template <typename Derived>
struct TfPyPolymorphic :
public TfType::PyPolymorphicBase,
public boost::python::wrapper<Derived>
{
typedef TfPyPolymorphic<Derived> This;
typedef TfPyOverride Override;
Override GetOverride(char const *func) const {
TfPyLock pyLock;
using namespace boost::python;
// don't use boost::python::wrapper::get_override(), as it can return
// the wrong result. instead, implement our own version which does
// better
PyObject * m_self = detail::wrapper_base_::get_owner(*this);
if (m_self) {
// using pythons mro, get the attribute string that represents
// the named function. this will return something valid if it exists
// in this or any ancestor class
if (handle<> m = handle<>(
allow_null(
PyObject_GetAttrString(
m_self, const_cast<char*>(func))))
)
{
// now get the typehandle to the class. we will use this to
// determine if this method exists on the derived class
type_handle typeHandle =
objects::registered_class_object(
typeid(Derived));
PyTypeObject* class_object = typeHandle.get();
PyObject* func_object = 0;
if (
PyMethod_Check(m.get())
&& ((PyMethodObject*)m.get())->im_self == m_self
&& class_object->tp_dict != 0
)
{
// look for the method on the class object.
handle<> borrowed_f(
allow_null(
PyObject_GetAttrString(
(PyObject *)class_object,
const_cast<char*>(func))));
// Don't leave an exception if there's no base class method
PyErr_Clear();
// do the appropriate conversion, if possible
if (borrowed_f && PyMethod_Check(borrowed_f.get())) {
func_object =
((PyMethodObject*)borrowed_f.get())->im_func;
}
}
// now, func_object is either NULL, or pointing at the method
// on the class or one of it's ancestors. m is holding the
// actual method that pythons mro would find. if that thing
// is not the same, it must be an override
if (func_object != ((PyMethodObject*)m.get())->im_func)
return Override(m);
}
}
PyErr_Clear(); // Don't leave an exception if there's no override.
return Override(handle<>(detail::none()));
}
Override GetPureOverride(char const *func) const {
TfPyLock pyLock;
Override ret = GetOverride(func);
if (!ret) {
// Raise a *python* exception when no virtual is found. This is
// because a subsequent attempt to call ret will result in a python
// exception, but a far less useful one. If we were to simply make
// a TfError here, it would be trumped by that python exception.
PyErr_SetString(PyExc_AttributeError, TfStringPrintf
("Pure virtual method '%s' called -- "
"must provide a python implementation.",
func).c_str());
TfPyConvertPythonExceptionToTfErrors();
}
return ret;
}
template <typename Ret>
TfPyCall<Ret> CallPureVirtual(char const *func) const {
TfPyLock lock;
return TfPyCall<Ret>(GetPureOverride(func));
}
template <class Ret, class Cls, typename... Arg>
std::function<Ret (Arg...)>
CallVirtual(
char const *fname,
Ret (Cls::*defaultImpl)(Arg...));
template <class Ret, class Cls, typename... Arg>
std::function<Ret (Arg...)>
CallVirtual(
char const *fname,
Ret (Cls::*defaultImpl)(Arg...) const) const;
protected:
virtual ~TfPyPolymorphic();
private:
// Helper to bind a pointer-to-member-function and a pointer to an
// instance.
template <class Ret, class Cls, typename... Args>
struct _BindMemFn
{
using MemFn = typename std::conditional<
std::is_const<Cls>::value,
Ret (Cls::*)(Args...) const, Ret (Cls::*)(Args...)>::type;
_BindMemFn(MemFn memFn, Cls *obj)
: _memFn(memFn)
, _obj(obj)
{}
Ret
operator()(Args... args) const
{
return (_obj->*_memFn)(args...);
}
private:
MemFn _memFn;
Cls *_obj;
};
};
template <typename Derived>
TfPyPolymorphic<Derived>::~TfPyPolymorphic()
{
}
template <typename Derived>
template <class Ret, class Cls, typename... Args>
inline
std::function<Ret (Args...)>
TfPyPolymorphic<Derived>::CallVirtual(
char const *fname,
Ret (Cls::*defaultImpl)(Args...))
{
static_assert(std::is_base_of<This, Cls>::value,
"This must be a base of Cls.");
TfPyLock lock;
if (Override o = GetOverride(fname))
return std::function<Ret (Args...)>(TfPyCall<Ret>(o));
return _BindMemFn<Ret, Cls, Args...>(
defaultImpl, static_cast<Cls *>(this));
}
template <typename Derived>
template <class Ret, class Cls, typename... Args>
inline
std::function<Ret (Args...)>
TfPyPolymorphic<Derived>::CallVirtual(
char const *fname,
Ret (Cls::*defaultImpl)(Args...) const) const
{
static_assert(std::is_base_of<This, Cls>::value,
"This must be a base of Cls.");
TfPyLock lock;
if (Override o = GetOverride(fname))
return std::function<Ret (Args...)>(TfPyCall<Ret>(o));
return _BindMemFn<Ret, Cls const, Args...>(
defaultImpl, static_cast<Cls const *>(this));
}
PXR_NAMESPACE_CLOSE_SCOPE
// Specialize has_back_reference<> so that boost.python will pass
// PyObject* as the 1st argument to TfPyPolymorphic's ctor.
namespace boost { namespace python {
template <typename T>
struct has_back_reference< PXR_NS::TfPyPolymorphic<T> >
: mpl::true_ {};
}} // end namespace boost
PXR_NAMESPACE_OPEN_SCOPE
// Base case for internal Tf_PyMemberFunctionPointerUpcast.
template <typename Base, typename Fn>
struct Tf_PyMemberFunctionPointerUpcast;
template <typename Base, typename Derived,
typename Ret, typename... Args>
struct Tf_PyMemberFunctionPointerUpcast< Base, Ret (Derived::*)(Args...) >
{
typedef Ret (Base::*Type)(Args...);
};
template <typename Base, typename Derived,
typename Ret, typename... Args>
struct Tf_PyMemberFunctionPointerUpcast< Base, Ret (Derived::*)(Args...) const >
{
typedef Ret (Base::*Type)(Args...) const;
};
template <typename Base, typename Fn>
typename Tf_PyMemberFunctionPointerUpcast<Base, Fn>::Type
TfPyProtectedVirtual( Fn fn )
{
typedef typename Tf_PyMemberFunctionPointerUpcast<Base, Fn>::Type Ret;
return static_cast<Ret>(fn);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_POLYMORPHIC_H
+432
View File
@@ -0,0 +1,432 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_PTR_HELPERS_H
#define PXR_BASE_TF_PY_PTR_HELPERS_H
/// \file tf/pyPtrHelpers.h
/// Enables wrapping of Weak or Ref & Weak held types to python.
#include "pxr/pxr.h"
#include "pxr/base/tf/py3Compat.h"
#include "pxr/base/tf/pyIdentity.h"
#include "pxr/base/tf/pyObjectFinder.h"
#include "pxr/base/tf/wrapTypeHelpers.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/anyWeakPtr.h"
#include <boost/python/class.hpp>
#include <boost/python/converter/from_python.hpp>
#include <boost/python/converter/registered.hpp>
#include <boost/python/converter/registrations.hpp>
#include <boost/python/converter/registry.hpp>
#include <boost/python/converter/rvalue_from_python_data.hpp>
#include <boost/python/converter/to_python_function_type.hpp>
#include <boost/python/def_visitor.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/to_python_converter.hpp>
#include <memory>
PXR_NAMESPACE_OPEN_SCOPE
//
// Boost.Python def visitors for wrapping objects held by weak pointers. This
// will create a read-only property on your class called 'expired' which is
// true if the object has expired. This also adds an implementation for __eq__
// and __ne__ which compare the pointers for equality and non-equality,
// respectively.
//
// Example usage:
//
// class_<MyClass, MyClassPtr>("MyClass", no_init)
// .def(TfPyWeakPtr())
// .def(...)
// ...
//
// Helper class to return or create a PyObject holder for a Ptr. This
// can be specialized for custom behavior.
template <typename Ptr>
struct TfMakePyPtr {
typedef typename Ptr::DataType Pointee;
typedef boost::python::objects::pointer_holder<Ptr, Pointee> Holder;
typedef std::pair<PyObject*, bool> Result;
// Return an existing PyObject for the pointer paired with false or
// create and return a new PyObject paired with true. The PyObject
// ref count must have been incremented.
static Result Execute(Ptr const& p)
{
// null pointers -> python None.
if (!p.GetUniqueIdentifier())
return Result(boost::python::detail::none(), false);
// Force instantiation. We must do this before checking if we
// have a python identity, otherwise the identity might be set
// during instantiation and our caller will attempt to set it
// again, which isn't allowed.
get_pointer(p);
if (PyObject *id = Tf_PyGetPythonIdentity(p))
return Result(id, false);
// Just make a new python object holding this pointer.
// TODO: use existing to-python conversion?
PyObject *res = boost::python::objects::make_ptr_instance
<Pointee, Holder>::execute(p);
// If we got back Py_None, no new object was made, so make sure
// to pass back false in result.
return Result(res, res != Py_None);
}
};
namespace Tf_PyDefHelpers {
using namespace boost::python;
template <typename Ptr>
struct _PtrInterface {
typedef typename Ptr::DataType Pointee;
typedef typename boost::add_const<Pointee>::type ConstPointee;
typedef typename boost::remove_const<Pointee>::type NonConstPointee;
template <typename U>
struct Rebind {
typedef typename Ptr::template Rebind<U>::Type Type;
};
typedef typename Rebind<ConstPointee>::Type ConstPtr;
typedef typename Rebind<NonConstPointee>::Type NonConstPtr;
};
template <typename PtrType>
bool _IsPtrExpired(object const &self) {
try {
PtrType p = extract<PtrType>(self);
return !p;
} catch (boost::python::error_already_set const &) {
PyErr_Clear();
return true;
}
}
template <typename PtrType>
bool _IsPtrValid(object const &self) {
return !_IsPtrExpired<PtrType>(self);
}
template <typename PtrType>
bool _ArePtrsEqual(PtrType const &self,
PtrType const &other) { return self == other; }
template <typename PtrType>
bool _ArePtrsNotEqual(PtrType const &self,
PtrType const &other) { return self != other; }
// Default ownership policy does nothing.
template <class PtrType>
struct _PtrFromPythonConversionPolicy {
static void Apply(PtrType const &, PyObject *) { }
};
// Ownership policy for ref ptrs when going from python to c++ is to
// transfer ownership (remove ownership from python if it has it).
template <typename T>
struct _PtrFromPythonConversionPolicy<TfRefPtr<T> > {
static void Apply(TfRefPtr<T> const &p, PyObject *obj) {
Tf_PyRemovePythonOwnership(p, obj);
}
};
template <class Ptr>
struct _PtrFromPython {
typedef typename _PtrInterface<Ptr>::Pointee Pointee;
_PtrFromPython() {
converter::registry::insert(&convertible, &construct,
type_id<Ptr>());
}
private:
static void *convertible(PyObject *p) {
if (p == Py_None)
return p;
void *result = converter::get_lvalue_from_python
(p, converter::registered<Pointee>::converters);
return result;
}
static void construct(PyObject* source, converter::
rvalue_from_python_stage1_data* data) {
void* const storage = ((converter::rvalue_from_python_storage<Ptr>*)
data)->storage.bytes;
// Deal with the "None" case.
if (data->convertible == source)
new (storage) Ptr();
else {
Ptr ptr(static_cast<Pointee*>(data->convertible));
new (storage) Ptr(ptr);
_PtrFromPythonConversionPolicy<Ptr>::Apply(ptr, source);
// Set ptr's python object to source if the pointer is valid.
if (ptr)
Tf_PySetPythonIdentity(ptr, source);
}
data->convertible = storage;
}
};
// Converter from python to AnyWeakPtr. We use this converter to wrap
// the weak-pointable object into an AnyWeakPtr when we don't know what
// specific C++ type it has--for example, see wrapNotice.cpp.
template <typename PtrType>
struct _AnyWeakPtrFromPython {
_AnyWeakPtrFromPython() {
converter::registry::insert(&convertible, &construct,
type_id<TfAnyWeakPtr>());
}
static void *convertible(PyObject *p) {
if (p == Py_None)
return p;
void *result = converter::get_lvalue_from_python
(p, converter::registered
<typename _PtrInterface<PtrType>::Pointee>::converters);
return result;
}
static void construct(PyObject* source, converter::
rvalue_from_python_stage1_data* data) {
void* const storage = ((converter::rvalue_from_python_storage
<TfAnyWeakPtr>*)data)->storage.bytes;
// Deal with the "None" case.
if (data->convertible == source)
new (storage) TfAnyWeakPtr();
else {
typedef typename _PtrInterface<PtrType>::Pointee T;
T *ptr = static_cast<T*>(data->convertible);
PtrType smartPtr(ptr);
new (storage) TfAnyWeakPtr(smartPtr);
}
data->convertible = storage;
}
};
template <typename Ptr>
struct _ConstPtrToPython {
typedef typename _PtrInterface<Ptr>::ConstPtr ConstPtr;
typedef typename _PtrInterface<Ptr>::NonConstPtr NonConstPtr;
_ConstPtrToPython() {
to_python_converter<ConstPtr, _ConstPtrToPython<Ptr> >();
}
static PyObject *convert(ConstPtr const &p) {
return incref(object(TfConst_cast<NonConstPtr>(p)).ptr());
}
};
template <typename Ptr>
struct _PtrToPython {
_PtrToPython() {
to_python_converter<Ptr, _PtrToPython<Ptr> >();
}
static PyObject *convert(Ptr const &p) {
std::pair<PyObject*, bool> ret = TfMakePyPtr<Ptr>::Execute(p);
if (ret.second) {
Tf_PySetPythonIdentity(p, ret.first);
}
return ret.first;
}
};
template <typename SrcPtr, typename DstPtr>
struct _ConvertPtrToPython {
_ConvertPtrToPython() {
to_python_converter<SrcPtr, _ConvertPtrToPython<SrcPtr, DstPtr> >();
}
static PyObject *convert(SrcPtr const &p) {
DstPtr dst = p;
return incref(object(dst).ptr());
}
};
template <typename Ptr>
struct _PtrToPythonWrapper {
// We store the original to-python converter for our use. It's fine to be
// static, as there's only one to-python converter for a type T, and there's
// one instantiation of this template for each T.
static converter::to_python_function_t _originalConverter;
// This signature has to match to_python_function_t
static PyObject *Convert(void const *x) {
// See boost/python/converter/as_to_python_function.hpp
Ptr const &p = *static_cast<Ptr const *>(x);
std::pair<PyObject*, bool> ret = TfMakePyPtr<Ptr>::Execute(p);
if (ret.first == Py_None) {
// Fallback to the original converter.
Py_DECREF(ret.first);
ret.first = _originalConverter(x);
}
if (ret.second) {
Tf_PySetPythonIdentity(p, ret.first);
}
return ret.first;
}
};
template <typename T>
converter::to_python_function_t
_PtrToPythonWrapper<T>::_originalConverter = 0;
struct WeakPtr : def_visitor<WeakPtr> {
friend class def_visitor_access;
template <typename WrapperPtrType, typename Wrapper, typename T>
static void _RegisterConversions(Wrapper *, T *) {
_RegisterConversionsHelper<WrapperPtrType, Wrapper, T>();
}
template <typename WrapperPtrType, typename Wrapper, typename T>
static void _RegisterConversionsHelper() {
static_assert(std::is_same<
typename _PtrInterface<WrapperPtrType>::Pointee,
Wrapper>::value,
"Pointee must be same type as Wrapper.");
typedef typename
_PtrInterface<WrapperPtrType>::template Rebind<T>::Type PtrType;
// Register the from-python conversion.
_PtrFromPython<PtrType>();
// Register AnyWeakPtr from python conversion.
_AnyWeakPtrFromPython<PtrType>();
// From python, can always make a const pointer from a non-const one.
implicitly_convertible<PtrType,
typename _PtrInterface<PtrType>::ConstPtr >();
// Register a conversion that casts away constness when going to python.
_ConstPtrToPython<PtrType>();
// Replace the existing to_python conversion for weakptr<wrapper> to do
// object id first. It would be great if we could get better support in
// boost python for doing this sort of thing.
//
// We do this for wrapper because this is the "wrapped type" -- the type
// for which boost python has already registered a to-python
// conversion. The unwrapped type is handled separately -- we don't
// have to replace an existing converter, we can just register our own.
converter::registration *r = const_cast<converter::registration *>
(converter::registry::query(type_id<WrapperPtrType>()));
if (r) {
_PtrToPythonWrapper<WrapperPtrType>::
_originalConverter = r->m_to_python;
r->m_to_python = _PtrToPythonWrapper<WrapperPtrType>::Convert;
} else {
// CODE_COVERAGE_OFF Can only happen if there's a bug.
TF_CODING_ERROR("No python registration for '%s'!",
ArchGetDemangled(typeid(WrapperPtrType)).c_str());
// CODE_COVERAGE_ON
}
if (!std::is_same<Wrapper, T>::value)
_PtrToPython<PtrType>();
}
template <typename PtrType, typename CLS, typename Wrapper, typename T>
static void _AddAPI(CLS &c, Wrapper *, T *) {
typedef typename
_PtrInterface<PtrType>::template Rebind<T>::Type UnwrappedPtrType;
// Add 'expired' property and (in)equality testing.
c.add_property("expired", _IsPtrExpired<UnwrappedPtrType>,
(const char *)
"True if this object has expired, False otherwise.");
c.def(TfPyBoolBuiltinFuncName, _IsPtrValid<UnwrappedPtrType>,
(char const *)
"True if this object has not expired. False otherwise.");
c.def("__eq__", _ArePtrsEqual<UnwrappedPtrType>,
"Equality operator: x == y");
c.def("__ne__", _ArePtrsNotEqual<UnwrappedPtrType>,
"Non-equality operator: x != y");
c.def( TfTypePythonClass() );
}
template <typename CLS>
void visit(CLS &c) const {
typedef typename CLS::wrapped_type Type;
typedef typename CLS::metadata::held_type_arg PtrType;
static_assert(TF_SUPPORTS_WEAKPTR(Type),
"Type must support TfWeakPtr.");
// Register conversions
_RegisterConversions<PtrType>
((Type *)0, detail::unwrap_wrapper((Type *)0));
// Register a PyObjectFinder.
Tf_RegisterPythonObjectFinder<Type, PtrType>();
// Add weak ptr api.
_AddAPI<PtrType>(c, (Type *)0, detail::unwrap_wrapper((Type *)0));
}
};
struct RefAndWeakPtr : def_visitor<RefAndWeakPtr> {
friend class def_visitor_access;
template <typename CLS, typename Wrapper, typename T>
static void _AddAPI(Wrapper *, T *) {
_PtrFromPython<TfRefPtr<T> >();
typedef typename
_PtrInterface<typename CLS::metadata::held_type>::template
Rebind<T>::Type PtrType;
_ConvertPtrToPython<TfRefPtr<T>, PtrType>();
}
template <typename CLS>
void visit(CLS &c) const {
typedef typename CLS::wrapped_type Type;
static_assert(TF_SUPPORTS_REFPTR(Type),
"Type must support TfRefPtr.");
// Same as weak ptr plus ref conversions.
WeakPtr().visit(c);
_AddAPI<CLS>((Type *)0, detail::unwrap_wrapper((Type *)0));
}
};
};
struct TfPyWeakPtr : Tf_PyDefHelpers::WeakPtr {};
struct TfPyRefAndWeakPtr : Tf_PyDefHelpers::RefAndWeakPtr {};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_PTR_HELPERS_H
+215
View File
@@ -0,0 +1,215 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_RESULT_CONVERSIONS_H
#define PXR_BASE_TF_PY_RESULT_CONVERSIONS_H
#include "pxr/pxr.h"
#include "pxr/base/tf/pyUtils.h"
#include <boost/python/tuple.hpp>
#include <boost/python/list.hpp>
#include <boost/python/dict.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
template <typename T> struct Tf_PySequenceToListConverter;
template <typename T> struct Tf_PySequenceToSetConverter;
template <typename T> struct Tf_PyMapToDictionaryConverter;
template <typename T> struct Tf_PySequenceToTupleConverter;
template <typename First, typename Second> struct Tf_PyPairToTupleConverter;
/// \class TfPySequenceToList
///
/// A \c boost::python result converter generator which converts standard
/// library sequences to lists.
///
/// The way to use this is as a return value policy for a function which
/// returns a sequence or a const reference to a sequence. For example this
/// function:
/// \code
/// vector<double> getDoubles() {
/// vector<double> ret;
/// ret.push_back(1.0);
/// ret.push_back(2.0);
/// ret.push_back(3.0);
/// return ret;
/// }
/// \endcode
///
/// May be wrapped as:
/// \code
/// def("getDoubles", &getDoubles, return_value_policy<TfPySequenceToList>())
/// \endcode
struct TfPySequenceToList {
template <typename T>
struct apply {
typedef Tf_PySequenceToListConverter<T> type;
};
};
/// \class TfPySequenceToSet
///
/// A \c boost::python result converter generator which converts standard
/// library sequences to sets.
///
/// The way to use this is as a return value policy for a function which
/// returns a sequence or a const reference to a sequence. For example this
/// function:
/// \code
/// unordered_set<double> getDoubles() {
/// unordered_set<double> ret;
/// ret.insert(1.0);
/// ret.insert(2.0);
/// ret.insert(3.0);
/// return ret;
/// }
/// \endcode
///
/// May be wrapped as:
/// \code
/// def("getDoubles", &getDoubles, return_value_policy<TfPySequenceToSet>())
/// \endcode
struct TfPySequenceToSet {
template <typename T>
struct apply {
typedef Tf_PySequenceToSetConverter<T> type;
};
};
/// \class TfPyMapToDictionary
///
/// A \c boost::python result converter generator which converts standard
/// library maps to dictionaries.
struct TfPyMapToDictionary {
template <typename T>
struct apply {
typedef Tf_PyMapToDictionaryConverter<T> type;
};
};
/// \class TfPySequenceToTuple
///
/// A \c boost::python result converter generator which converts standard
/// library sequences to tuples.
/// \see TfPySequenceToList.
struct TfPySequenceToTuple {
template <typename T>
struct apply {
typedef Tf_PySequenceToTupleConverter<T> type;
};
};
/// A \c boost::python result converter generator which converts standard
/// library pairs to tuples.
struct TfPyPairToTuple {
template <typename T>
struct apply {
typedef Tf_PyPairToTupleConverter<typename T::first_type,
typename T::second_type> type;
};
};
template <typename T>
struct Tf_PySequenceToListConverter {
typedef typename boost::remove_reference<T>::type SeqType;
bool convertible() const {
return true;
}
PyObject *operator()(T seq) const {
return boost::python::incref(TfPyCopySequenceToList(seq).ptr());
}
PyTypeObject *get_pytype() {
return &PyList_Type;
}
};
template <typename T>
struct Tf_PySequenceToSetConverter {
typedef typename std::remove_reference<T>::type SeqType;
bool convertible() const {
return true;
}
PyObject *operator()(T seq) const {
return boost::python::incref(TfPyCopySequenceToSet(seq).ptr());
}
PyTypeObject *get_pytype() {
return &PySet_Type;
}
};
template <typename T>
struct Tf_PyMapToDictionaryConverter {
typedef typename boost::remove_reference<T>::type SeqType;
// TODO: convertible() should be made more robust by checking that the
// value_type of the container is pair<const key_type, data_type>
bool convertible() const {
return true;
}
PyObject *operator()(T seq) const {
return boost::python::incref(TfPyCopyMapToDictionary(seq).ptr());
}
PyTypeObject *get_pytype() {
return &PyDict_Type;
}
};
template <typename T>
struct Tf_PySequenceToTupleConverter {
typedef typename boost::remove_reference<T>::type SeqType;
bool convertible() const {
return true;
}
PyObject *operator()(T seq) const {
return boost::python::incref(TfPyCopySequenceToTuple(seq).ptr());
}
PyTypeObject *get_pytype() {
return &PyTuple_Type;
}
};
template <typename First, typename Second>
struct Tf_PyPairToTupleConverter {
typedef std::pair<First, Second> PairType;
bool convertible() const {
return true;
}
PyObject *operator()(PairType const& a) const {
boost::python::tuple result =
boost::python::make_tuple(a.first, a.second);
return boost::python::incref(result.ptr());
}
PyTypeObject *get_pytype() {
return &PyTuple_Type;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // TF_RESULT_CONVERSIONS_H
+34
View File
@@ -0,0 +1,34 @@
//
// Copyright 2020 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_SAFE_PYTHON_H
#define PXR_BASE_TF_PY_SAFE_PYTHON_H
/// \file tf/pySafePython.h
/// Intended to replace a direct include of Python.h, which causes several
/// build problems with certain configurations and platforms (e.g., debug
/// builds on Windows)
#include <boost/python/detail/wrap_python.hpp>
#endif // PXR_BASE_TF_PY_SAFE_PYTHON_H
+120
View File
@@ -0,0 +1,120 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_SINGLETON_H
#define PXR_BASE_TF_PY_SINGLETON_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/pyPtrHelpers.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/weakPtr.h"
#include <boost/mpl/vector/vector10.hpp>
#include <boost/python/class.hpp>
#include <boost/python/default_call_policies.hpp>
#include <boost/python/def_visitor.hpp>
#include <boost/python/raw_function.hpp>
#include <functional>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
namespace Tf_PySingleton {
namespace bp = boost::python;
TF_API
bp::object _DummyInit(bp::tuple const & /* args */,
bp::dict const & /* kw */);
template <class T>
TfWeakPtr<T> GetWeakPtr(T &t) {
return TfCreateWeakPtr(&t);
}
template <class T>
TfWeakPtr<T> GetWeakPtr(T const &t) {
// cast away constness for python...
return TfConst_cast<TfWeakPtr<T> >(TfCreateWeakPtr(&t));
}
template <class T>
TfWeakPtr<T> GetWeakPtr(TfWeakPtr<T> const &t) {
return t;
}
template <typename PtrType>
PtrType _GetSingletonWeakPtr(bp::object const & /* classObj */) {
typedef typename PtrType::DataType Singleton;
return GetWeakPtr(Singleton::GetInstance());
}
TF_API
std::string _Repr(bp::object const &self, std::string const &prefix);
struct Visitor : bp::def_visitor<Visitor> {
explicit Visitor(std::string const &reprPrefix = std::string()) :
_reprPrefix(reprPrefix) {}
friend class bp::def_visitor_access;
template <typename CLS>
void visit(CLS &c) const {
typedef typename CLS::metadata::held_type PtrType;
// Singleton implies WeakPtr.
c.def(TfPyWeakPtr());
// Wrap __new__ to return a weak pointer to the singleton instance.
c.def("__new__", _GetSingletonWeakPtr<PtrType>).staticmethod("__new__");
// Make __init__ do nothing.
c.def("__init__", bp::raw_function(_DummyInit));
// If they supplied a repr prefix, provide a repr implementation.
if (!_reprPrefix.empty())
c.def("__repr__",
make_function(std::bind(
_Repr, std::placeholders::_1, _reprPrefix),
bp::default_call_policies(),
boost::mpl::vector2<std::string,
bp::object const &>()));
}
private:
std::string _reprPrefix;
};
}
TF_API
Tf_PySingleton::Visitor TfPySingleton();
TF_API
Tf_PySingleton::Visitor TfPySingleton(std::string const &reprPrefix);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_SINGLETON_H
+117
View File
@@ -0,0 +1,117 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_STATIC_TOKENS_H
#define PXR_BASE_TF_PY_STATIC_TOKENS_H
/// \file tf/pyStaticTokens.h
#include "pxr/pxr.h"
#include <locale>
#include "pxr/base/tf/staticTokens.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include <boost/python/class.hpp>
#include <boost/python/scope.hpp>
PXR_NAMESPACE_OPEN_SCOPE
// TODO: Should wrap token arrays to Python.
/// Macro to wrap static tokens defined with \c TF_DEFINE_PUBLIC_TOKENS to
/// Python. It creates a class of name \p name in the current scope
/// containing just the tokens in \p seq in the static tokens named by \p key.
/// Arrays are not wrapped but their components are.
///
/// \hideinitializer
#define TF_PY_WRAP_PUBLIC_TOKENS(name, key, seq) \
boost::python::class_<_TF_TOKENS_STRUCT_NAME(key), boost::noncopyable>( \
name, boost::python::no_init) \
_TF_PY_TOKENS_WRAP_SEQ(key, _TF_PY_TOKENS_EXPAND(seq))
/// Macro to wrap static tokens defined with \c TF_DEFINE_PUBLIC_TOKENS to
/// Python. This wraps tokens in \p seq in the static tokens named by \p key
/// as attributes on the current boost python scope. Arrays are not wrapped
/// but their components are.
///
/// \hideinitializer
#define TF_PY_WRAP_PUBLIC_TOKENS_IN_CURRENT_SCOPE(key, seq) \
_TF_PY_TOKENS_WRAP_ATTR_SEQ(key, _TF_PY_TOKENS_EXPAND(seq))
// Helper to return a static token as a string. We wrap tokens as Python
// strings and for some reason simply wrapping the token using def_readonly
// bypasses to-Python conversion, leading to the error that there's no
// Python type for the C++ TfToken type. So we wrap this functor instead.
class _TfPyWrapStaticToken {
public:
_TfPyWrapStaticToken(const TfToken* token) : _token(token) { }
std::string operator()() const
{
return _token->GetString();
}
private:
const TfToken* _token;
};
// Private macros to add a single data member.
#define _TF_PY_TOKENS_WRAP_ATTR_MEMBER(r, key, name) \
boost::python::scope().attr( \
TF_PP_STRINGIZE(name)) = key->name.GetString();
#define _TF_PY_TOKENS_WRAP_MEMBER(r, key, name) \
.add_static_property(TF_PP_STRINGIZE(name), \
boost::python::make_function(_TfPyWrapStaticToken((&key->name)), \
boost::python::return_value_policy< \
boost::python::return_by_value>(), \
boost::mpl::vector1<std::string>()))
#define _TF_PY_TOKENS_EXPAND(seq) \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_NOT_ARRAY, ~, seq) \
_TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq)
// Private macros to wrap a single element in a sequence.
#define _TF_PY_TOKENS_WRAP_ELEMENT(r, key, elem) \
_TF_PY_TOKENS_WRAP_MEMBER(r, key, _TF_PY_TOKEN_GET_ELEM(elem))
#define _TF_PY_TOKENS_WRAP_ATTR_ELEMENT(r, key, elem) \
_TF_PY_TOKENS_WRAP_ATTR_MEMBER(r, key, _TF_PY_TOKEN_GET_ELEM(elem))
#define _TF_PY_TOKEN_GET_ELEM(elem) \
BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
BOOST_PP_TUPLE_ELEM(2, 0, elem), elem)
// Private macros to wrap a sequence.
#define _TF_PY_TOKENS_WRAP_SEQ(key, seq) \
BOOST_PP_SEQ_FOR_EACH(_TF_PY_TOKENS_WRAP_ELEMENT, key, seq)
#define _TF_PY_TOKENS_WRAP_ATTR_SEQ(key, seq) \
BOOST_PP_SEQ_FOR_EACH(_TF_PY_TOKENS_WRAP_ATTR_ELEMENT, key, seq)
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_STATIC_TOKENS_H
+65
View File
@@ -0,0 +1,65 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_TRACING_H
#define PXR_BASE_TF_PY_TRACING_H
#include "pxr/base/tf/pySafePython.h"
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <functional>
#include <memory>
PXR_NAMESPACE_OPEN_SCOPE
/// \struct TfPyTraceInfo
/// Structure passed to python trace functions. See the Python C API
/// documentation reference for the meaning of \a what and \a arg.
struct TfPyTraceInfo {
PyObject *arg;
char const *funcName;
char const *fileName;
int funcLine;
int what;
};
typedef std::function<void (TfPyTraceInfo const &)> TfPyTraceFn;
typedef std::shared_ptr<TfPyTraceFn> TfPyTraceFnId;
/// Register \a f as a python trace function.
/// It will be invoked for python tracing events. If python is not yet
/// initialized, the function will not be invoked until python is initialized.
TF_API TfPyTraceFnId TfPyRegisterTraceFn(TfPyTraceFn const &f);
// For internal use only. Do not use.
void Tf_PyFabricateTraceEvent(TfPyTraceInfo const &info);
// For internal use only. Do not use.
void Tf_PyTracingPythonInitialized();
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_TRACING_H
+395
View File
@@ -0,0 +1,395 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_UTILS_H
#define PXR_BASE_TF_PY_UTILS_H
/// \file tf/pyUtils.h
/// Miscellaneous Utilities for dealing with script.
#include "pxr/pxr.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/diagnosticLite.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include "pxr/base/tf/py3Compat.h"
#include "pxr/base/tf/pyInterpreter.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/api.h"
#include <functional>
#include <typeinfo>
#include <string>
#include <vector>
#include <boost/python/dict.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/object.hpp>
#include <boost/python/type_id.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// A macro which expands to the proper __repr__ prefix for a library. This is
/// the "canonical" name of the module that the system uses to identify it
/// followed by a '.'. This can be used in the implementation of __repr__
///
/// \hideinitializer
#define TF_PY_REPR_PREFIX \
std::string(TF_PP_STRINGIZE(MFB_PACKAGE_MODULE) ".")
/// Returns true if python is initialized.
TF_API bool TfPyIsInitialized();
/// Raises a python \c IndexError and throws a C++ exception.
/// Intended to be used in wrapper code.
TF_API void TfPyThrowIndexError(std::string const &msg);
/// Raises a python \c RuntimError and throws a C++ exception.
/// Intended to be used in wrapper code.
TF_API void TfPyThrowRuntimeError(std::string const &msg);
/// Raises a python \c StopIteration exception and throws a C++ exception.
/// Intended to be used in wrapper code.
TF_API void TfPyThrowStopIteration(std::string const &msg);
/// Raises a python \c KeyError and throws a C++ exception.
/// Intended to be used in wrapper code.
TF_API void TfPyThrowKeyError(std::string const &msg);
/// Raises a python \c ValueError and throws a C++ exception.
/// Intended to be used in wrapper code.
TF_API void TfPyThrowValueError(std::string const &msg);
/// Raises a python \c TypeError and throws a C++ exception.
/// Intended to be used in wrapper code.
TF_API void TfPyThrowTypeError(std::string const &msg);
/// Return true iff \a obj is None.
TF_API bool TfPyIsNone(boost::python::object const &obj);
/// Return true iff \a obj is None.
TF_API bool TfPyIsNone(boost::python::handle<> const &obj);
// Helper for \c TfPyObject().
TF_API void Tf_PyObjectError(bool printError);
/// Return a python object for the given C++ object, loading the appropriate
/// wrapper code if necessary. Spams users if complainOnFailure is true and
/// conversion fails.
template <typename T>
boost::python::object TfPyObject(T const &t, bool complainOnFailure = true) {
// initialize python if it isn't already, so at least we can try to return
// an object
if (!TfPyIsInitialized()) {
TF_CODING_ERROR("Called TfPyObject without python being initialized!");
TfPyInitialize();
}
TfPyLock pyLock;
// Will only be able to return objects which have been wrapped.
// Returns None otherwise
try {
return boost::python::object(t);
} catch (boost::python::error_already_set const &) {
Tf_PyObjectError(complainOnFailure);
return boost::python::object();
}
}
inline
boost::python::object TfPyObject(PyObject* t, bool complainOnFailure = true) {
TfPyLock pyLock;
return boost::python::object(boost::python::handle<>(t));
}
/// Return repr(t).
///
/// Calls PyObject_Repr on the given python object.
TF_API std::string TfPyObjectRepr(boost::python::object const &t);
/// Return repr(t).
///
/// Converts t to its equivalent python object and then calls PyObject_Repr on
/// that.
template <typename T>
std::string TfPyRepr(T const &t) {
if (!TfPyIsInitialized())
return "<python not initialized>";
TfPyLock lock;
return TfPyObjectRepr(TfPyObject(t));
}
/// Return repr(t) for a vector as a python list.
template <typename T>
std::string TfPyRepr(const std::vector<T> &v) {
std::string result("[");
typename std::vector<T>::const_iterator i = v.begin();
if (i != v.end()) {
result += TfPyRepr(*i);
++i;
}
while (i != v.end()) {
result += ", " + TfPyRepr(*i);
++i;
}
result += "]";
return result;
}
/// Evaluate python expression \a expr with all the known script modules
/// imported under their standard names. Additional globals may be provided in
/// the \p extraGlobals dictionary.
TF_API
boost::python::object
TfPyEvaluate(
std::string const &expr,
boost::python::dict const &extraGlobals = boost::python::dict());
/// Return a positive index in the range [0,size). If \a throwError is true,
/// this will throw an index error if the resulting index is out of range.
TF_API
int64_t
TfPyNormalizeIndex(int64_t index, uint64_t size, bool throwError = false);
/// Return the name of the class of \a obj.
TF_API std::string TfPyGetClassName(boost::python::object const &obj);
/// Return the python class object for \a type if \a type has been wrapped.
/// Otherwise return None.
TF_API boost::python::object
TfPyGetClassObject(std::type_info const &type);
/// Return the python class object for T if T has been wrapped.
/// Otherwise return None.
template <typename T>
boost::python::object
TfPyGetClassObject() {
return TfPyGetClassObject(typeid(T));
}
TF_API
void
Tf_PyWrapOnceImpl(boost::python::type_info const &,
std::function<void()> const&,
bool *);
/// Invokes \p wrapFunc to wrap type \c T if \c T is not already wrapped.
///
/// Executing \p wrapFunc *must* register \c T with boost python. Otherwise,
/// \p wrapFunc may be executed more than once.
///
/// TfPyWrapOnce will acquire the GIL prior to invoking \p wrapFunc. Does not
/// invoke \p wrapFunc if Python has not been initialized.
template <typename T>
void
TfPyWrapOnce(std::function<void()> const &wrapFunc)
{
// Don't try to wrap if python isn't initialized.
if (!TfPyIsInitialized()) {
return;
}
static bool isTypeWrapped = false;
if (isTypeWrapped) {
return;
}
Tf_PyWrapOnceImpl(boost::python::type_id<T>(), wrapFunc, &isTypeWrapped);
}
/// Load the python module \a moduleName. This is used by some low-level
/// infrastructure code to load python wrapper modules corresponding to C++
/// shared libraries when they are needed. It should generally not need to be
/// called from normal user code.
TF_API
void Tf_PyLoadScriptModule(std::string const &name);
/// Creates a python dictionary from a std::map.
template <class Map>
boost::python::dict TfPyCopyMapToDictionary(Map const &map) {
TfPyLock lock;
boost::python::dict d;
for (typename Map::const_iterator i = map.begin(); i != map.end(); ++i)
d[i->first] = i->second;
return d;
}
template<class Seq>
boost::python::list TfPyCopySequenceToList(Seq const &seq) {
TfPyLock lock;
boost::python::list l;
for (typename Seq::const_iterator i = seq.begin();
i != seq.end(); ++i)
l.append(*i);
return l;
}
/// Create a python set from an iterable sequence.
///
/// If Seq::value_type is not hashable, TypeError is raised via throwing
/// boost::python::error_already_set.
template <class Seq>
boost::python::object TfPyCopySequenceToSet(Seq const &seq) {
TfPyLock lock;
boost::python::handle<> set{boost::python::allow_null(PySet_New(nullptr))};
if (!set) {
boost::python::throw_error_already_set();
}
for (auto const& item : seq) {
boost::python::object obj(item);
if (PySet_Add(set.get(), obj.ptr()) == -1) {
boost::python::throw_error_already_set();
}
}
return boost::python::object(set);
}
template<class Seq>
boost::python::tuple TfPyCopySequenceToTuple(Seq const &seq) {
return boost::python::tuple(TfPyCopySequenceToList(seq));
}
/// Create a python bytearray from an input buffer and size.
///
/// If a size of zero is passed in this function will return a valid python
/// bytearray of size zero.
///
/// An invalid object handle is returned on failure.
TF_API
boost::python::object TfPyCopyBufferToByteArray(const char* buffer, size_t size);
/// Return a vector of strings containing the current python traceback.
///
/// The vector contains the same strings that python's traceback.format_stack()
/// returns.
TF_API
std::vector<std::string> TfPyGetTraceback();
/// Populates the vector passed in with pointers to strings containing the
/// python interpreter stack frames.
/// Note that TfPyGetStackFrames allocates these strings on the heap and its
/// the caller's responsibility to free them.
TF_API
void TfPyGetStackFrames(std::vector<uintptr_t> *frames);
/// Print the current python traceback to stdout.
TF_API
void TfPyDumpTraceback();
/// Set an environment variable in \c os.environ.
///
/// This function is equivalent to
///
/// \code
/// def PySetenv(name, value):
/// try:
/// import os
/// os.environ[name] = value
/// return True
/// except:
/// return False
/// \endcode
///
/// Calling this function without first initializing Python is an error and
/// returns \c false.
///
/// Note that this function will import the \c os module, causing \c
/// os.environ to be poputated. All modifications to the environment after \c
/// os has been imported must be made with this function or \c TfSetenv if it
/// important that they appear in \c os.environ.
TF_API
bool TfPySetenv(const std::string & name, const std::string & value);
/// Remove an environment variable from \c os.environ.
///
/// This function is equivalent to
///
/// \code
/// def PyUnsetenv(name):
/// try:
/// import os
/// if name in os.environ:
/// del os.environ[name]
/// return True
/// except:
/// return False
/// \endcode
///
/// Calling this function without first initializing Python is an error and
/// returns \c false.
///
/// Note that this function will import the \c os module, causing \c
/// os.environ to be poputated. All modifications to the environment after \c
/// os has been imported must be made with this function or \c TfUnsetenv if
/// it important that they appear in \c os.environ.
TF_API
bool TfPyUnsetenv(const std::string & name);
// Private helper method to TfPyEvaluateAndExtract.
//
TF_API bool Tf_PyEvaluateWithErrorCheck(
const std::string & expr, boost::python::object * obj);
/// Safely evaluates \p expr and extracts the return object of type T. If
/// successful, returns \c true and sets *t to the return value, otherwise
/// returns \c false.
template <typename T>
bool TfPyEvaluateAndExtract(const std::string & expr, T * t)
{
if (expr.empty())
return false;
// Take the lock before doing anything with boost::python.
TfPyLock lock;
// Though TfPyEvaluate (called by Tf_PyEvaluateWithErroCheck) takes the
// python lock, it is important that we lock before we initialize the
// boost::python::object, since it will increment and decrement ref counts
// outside of the call to TfPyEvaluate.
boost::python::object obj;
if (!Tf_PyEvaluateWithErrorCheck(expr, &obj))
return false;
boost::python::extract<T> extractor(obj);
if (!extractor.check())
return false;
*t = extractor();
return true;
}
/// Print a standard traceback to sys.stderr and clear the error indicator.
/// If the error is a KeyboardInterrupt then this does nothing. Call this
/// function only when the error indicator is set.
TF_API
void TfPyPrintError();
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_UTILS_H
+73
View File
@@ -0,0 +1,73 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_PY_WRAP_CONTEXT_H
#define PXR_BASE_TF_PY_WRAP_CONTEXT_H
#include "pxr/pxr.h"
#include "pxr/base/tf/singleton.h"
#include <boost/noncopyable.hpp>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
// This is used internally by the Tf python wrapping infrastructure.
class Tf_PyWrapContextManager : public boost::noncopyable {
public:
typedef Tf_PyWrapContextManager This;
static This &GetInstance() {
return TfSingleton<This>::GetInstance();
}
std::string GetCurrentContext() const {
return _contextStack.empty() ? std::string() : _contextStack.back();
}
void PushContext(std::string const &ctx) {
_contextStack.push_back(ctx);
}
void PopContext() {
_contextStack.pop_back();
}
private:
Tf_PyWrapContextManager();
friend class TfSingleton<This>;
std::vector<std::string> _contextStack;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_PY_WRAP_CONTEXT_H
+138
View File
@@ -0,0 +1,138 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_REF_BASE_H
#define PXR_BASE_TF_REF_BASE_H
/// \file tf/refBase.h
/// \ingroup group_tf_Memory
#include "pxr/pxr.h"
#include "pxr/base/tf/refCount.h"
#include "pxr/base/tf/api.h"
PXR_NAMESPACE_OPEN_SCOPE
template <class T> class TfRefPtr;
template <class T> class TfWeakPtr;
/// \class TfRefBase
/// \ingroup group_tf_Memory
///
/// Enable a concrete base class for use with \c TfRefPtr.
///
/// You should be familiar with the \c TfRefPtr type before reading further.
///
/// A class (but not an interface class) is enabled for reference
/// counting via the \c TfRefPtr type by publicly deriving from \c
/// TfRefBase.
///
/// For example,
/// \code
/// #include "pxr/base/tf/refPtr.h"
///
/// class Simple : public TfRefBase {
/// public:
/// TfRefPtr<Simple> New() {
/// return TfCreateRefPtr(new Simple);
/// }
/// private:
/// Simple();
/// };
/// \endcode
///
/// The class \c Simple can now only be manipulated in terms of
/// a \c TfRefPtr<Simple>.
///
/// To disable the cost of the "unique changed" system, derive
/// from TfSimpleRefBase instead.
///
class TfRefBase {
public:
typedef void (*UniqueChangedFuncPtr)(TfRefBase const *, bool);
struct UniqueChangedListener {
void (*lock)();
UniqueChangedFuncPtr func;
void (*unlock)();
};
TfRefBase() : _shouldInvokeUniqueChangedListener(false) { }
/// Return the current reference count of this object.
size_t GetCurrentCount() const {
return GetRefCount().Get();
}
/// Return true if only one \c TfRefPtr points to this object.
bool IsUnique() const {
return GetRefCount().Get() == 1;
}
const TfRefCount& GetRefCount() const {
return _refCount;
}
void SetShouldInvokeUniqueChangedListener(bool shouldCall) {
_shouldInvokeUniqueChangedListener = shouldCall;
}
TF_API static void SetUniqueChangedListener(UniqueChangedListener listener);
protected:
/*
* Prohibit deletion through a TfRefBase pointer.
*/
TF_API virtual ~TfRefBase();
private:
TfRefCount _refCount;
bool _shouldInvokeUniqueChangedListener;
static UniqueChangedListener _uniqueChangedListener;
template <typename T> friend class TfRefPtr;
friend struct Tf_RefPtr_UniqueChangedCounter;
friend struct Tf_RefPtr_Counter;
template <typename T> friend TfRefPtr<T>
TfCreateRefPtrFromProtectedWeakPtr(TfWeakPtr<T> const &);
};
/// \class TfSimpleRefBase
/// \ingroup group_tf_Memory
///
/// Enable a concrete base class for use with \c TfRefPtr that inhibits the
/// "unique changed" facility of TfRefPtr.
///
/// Derive from this class if you don't plan on wrapping your
/// reference-counted object via boost::python.
///
class TfSimpleRefBase : public TfRefBase {
public:
TF_API virtual ~TfSimpleRefBase();
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_REF_BASE_H
+113
View File
@@ -0,0 +1,113 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_REF_COUNT_H
#define PXR_BASE_TF_REF_COUNT_H
/// \file tf/refCount.h
/// \ingroup group_tf_Memory
#include "pxr/pxr.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/tf/api.h"
#include <atomic>
PXR_NAMESPACE_OPEN_SCOPE
template <typename T> class TfRefPtr;
/// \class TfRefCount
/// \ingroup group_tf_Memory
///
/// Reference counter class
///
/// This class is intended to be embedded in other classes, for use as
/// a reference counter. Unless you need to provide extraordinary
/// customization, you should forgo direct use of this class and instead
/// make use of the base class \c TfRefBase.
///
/// Initialization of a reference counter is somewhat counterintuitive.
/// Consider an object T with a reference counter R. When T is
/// initialized, R should be initialized to one, even if T is
/// copy-constructed. This implies that \e all constructors of \c
/// TfRefCount set the counter to one, even the copy constructor.
///
/// Conversely, if T is assigned to, the reference counter R in T should not
/// change. This implies that the assignment operator for \c TfRefCount
/// does not change the counter's value.
///
/// Finally, for thread-safety, the counter should be atomic.
///
/// This class was written primarily for use in classes whose access is
/// encapsulated by means of the \c TfRefPtr interface; such classes require
/// reference counting semantics as described above. Note that
/// the behavior of a \c TfRefCount in a class T is invariant with respect
/// to T's copy constructors and assignment operators.
///
/// Again, please do not directly embed a \c TfRefCount in a structure
/// unless the functionality of \c TfRefBase is insufficient for your needs.
///
class TfRefCount {
public:
/// Initialize counter to one.
TfRefCount() : _counter(1) {
}
/// Initialize counter to one.
///
/// Even if you copy from a reference counter, you want the
/// newly constructed counter to start at one.
TfRefCount(const TfRefCount&) : _counter(1) {
}
/// Returns counter's value.
int Get() const {
return _counter;
}
/// Assignment to a reference counter has no effect.
const TfRefCount& operator=(const TfRefCount&) const {
return *this;
}
private:
/// Decrements counter by \c 1, returning true if the result is 0.
bool _DecrementAndTestIfZero() const {
return (--_counter == 0);
}
/// Adds \c amount to the count, returning the prior value.
int _FetchAndAdd(int amount) const {
return _counter.fetch_add(amount);
}
private:
mutable std::atomic<int> _counter;
template <typename T> friend class TfRefPtr;
friend struct Tf_RefPtr_UniqueChangedCounter;
friend struct Tf_RefPtr_Counter;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_REF_COUNT_H
File diff suppressed because it is too large. Load diff
+263
View File
@@ -0,0 +1,263 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_REF_PTR_TRACKER_H
#define PXR_BASE_TF_REF_PTR_TRACKER_H
/// \file tf/refPtrTracker.h
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/tf/singleton.h"
#include <boost/noncopyable.hpp>
#include <iosfwd>
#include <mutex>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class TfRefBase;
template <class T> class TfRefPtr;
/// \class TfRefPtrTracker
///
/// Provides tracking of \c TfRefPtr objects to particular objects.
///
/// Clients can enable, at compile time, tracking of \c TfRefPtr objects that
/// point to particular instances of classes derived from \c TfRefBase.
/// This is useful if you have a ref counted object with a ref count that
/// should've gone to zero but didn't. This tracker can tell you every
/// \c TfRefPtr that's holding the \c TfRefBase and a stack trace where it
/// was created or last assigned to.
///
/// Clients can get a report of all watched instances and how many \c TfRefPtr
/// objects are holding them using \c ReportAllWatchedCounts() (in python use
/// \c Tf.RefPtrTracker().GetAllWatchedCountsReport()). You can see all of
/// the stack traces using \c ReportAllTraces() (in python use
/// \c Tf.RefPtrTracker().GetAllTracesReport()).
///
/// Clients will typically enable tracking using code like this:
///
/// \code
/// #include "pxr/base/tf/refPtrTracker.h"
///
/// class MyRefBaseType;
/// typedef TfRefPtr<MyRefBaseType> MyRefBaseTypeRefPtr;
///
/// TF_DECLARE_REFPTR_TRACK(MyRefBaseType);
///
/// class MyRefBaseType {
/// ...
/// public:
/// static bool _ShouldWatch(const MyRefBaseType*);
/// ...
/// };
///
/// TF_DEFINE_REFPTR_TRACK(MyRefBaseType, MyRefBaseType::_ShouldWatch);
/// \endcode
///
/// Note that the \c TF_DECLARE_REFPTR_TRACK() macro must be invoked before
/// any use of the \c MyRefBaseTypeRefPtr type.
///
/// The \c MyRefBaseType::_ShouldWatch() function returns \c true if the
/// given instance of \c MyRefBaseType should be tracked. You can also
/// use \c TfRefPtrTracker::WatchAll() to watch every instance (but that
/// might use a lot of memory and time).
///
/// If you have a base type, \c B, and a derived type, \c D, and you hold
/// instances of \c D in a \c TfRefPtr<\c B> (i.e. a pointer to the base) then
/// you must track both type \c B and type \c D. But you can use
/// \c TfRefPtrTracker::WatchNone() when tracking \c B if you're not
/// interested in instances of \c B.
///
class TfRefPtrTracker : public TfWeakBase, boost::noncopyable {
public:
enum TraceType { Add, Assign };
TF_API static TfRefPtrTracker& GetInstance()
{
return TfSingleton<TfRefPtrTracker>::GetInstance();
}
/// Returns the maximum stack trace depth.
TF_API
size_t GetStackTraceMaxDepth() const;
/// Sets the maximum stack trace depth.
TF_API
void SetStackTraceMaxDepth(size_t);
/// A track trace.
struct Trace {
/// The stack trace when the \c TfRefPtr was created or assigned to.
std::vector<uintptr_t> trace;
/// The object being pointed to.
const TfRefBase* obj;
/// Whether the \c TfRefPtr was created or assigned to.
TraceType type;
};
/// Maps a \c TfRefPtr address to the most recent trace for it.
typedef TfHashMap<const void*, Trace, TfHash> OwnerTraces;
/// Maps a \c TfRefBase object pointer to the number of \c TfRefPtr
/// objects using it. This should be the ref count on the \c TfRefBase
/// but it's tracked separately.
typedef TfHashMap<const TfRefBase*, size_t, TfHash> WatchedCounts;
/// Returns the watched objects and the number of owners of each.
/// Returns a copy for thread safety.
TF_API
WatchedCounts GetWatchedCounts() const;
/// Returns traces for all owners. Returns a copy for thread safety.
TF_API
OwnerTraces GetAllTraces() const;
/// Writes all watched objects and the number of owners of each
/// to \p stream.
TF_API
void ReportAllWatchedCounts(std::ostream& stream) const;
/// Writes all traces to \p stream.
TF_API
void ReportAllTraces(std::ostream& stream) const;
/// Writes traces for all owners of \p watched.
TF_API
void ReportTracesForWatched(std::ostream& stream,
const TfRefBase* watched) const;
/// Handy function to pass as second argument to \c TF_DEFINE_REFPTR_TRACK.
/// No objects of the type will be watched but you can watch derived types.
/// This is important if you'll be holding TfRefPtr objects to base types;
/// if you don't track the base types, you'll fail to track all uses of
/// the derived objects.
static bool WatchNone(const void*)
{
return false;
}
/// Handy function to pass as second argument to \c TF_DEFINE_REFPTR_TRACK.
/// All objects of the type will be watched.
static bool WatchAll(const void*)
{
return true;
}
private:
TfRefPtrTracker();
~TfRefPtrTracker();
/// Start watching \p obj. Only watched objects are traced.
void _Watch(const TfRefBase* obj);
/// Stop watching \p obj. Existing traces for \p obj are kept.
void _Unwatch(const TfRefBase* obj);
/// Add a trace for a new owner \p owner of object \p obj if \p obj
/// is being watched.
void _AddTrace(const void* owner, const TfRefBase* obj, TraceType = Add);
/// Remove traces for owner \p owner.
void _RemoveTraces(const void* owner);
private:
typedef std::mutex _Mutex;
typedef std::lock_guard<std::mutex> _Lock;
mutable _Mutex _mutex;
size_t _maxDepth;
WatchedCounts _watched;
OwnerTraces _traces;
friend class Tf_RefPtrTrackerUtil;
friend class TfSingleton<TfRefPtrTracker>;
};
TF_API_TEMPLATE_CLASS(TfSingleton<TfRefPtrTracker>);
// For internal use only.
class Tf_RefPtrTrackerUtil {
public:
/// Start watching \p obj. Only watched objects are traced.
static void Watch(const TfRefBase* obj)
{
TfRefPtrTracker::GetInstance()._Watch(obj);
}
/// Stop watching \p obj. Existing traces for \p obj are kept.
static void Unwatch(const TfRefBase* obj)
{
TfRefPtrTracker::GetInstance()._Unwatch(obj);
}
/// Add a trace for a new owner \p owner of object \p obj if \p obj
/// is being watched.
static void AddTrace(const void* owner, const TfRefBase* obj,
TfRefPtrTracker::TraceType type = TfRefPtrTracker::Add)
{
TfRefPtrTracker::GetInstance()._AddTrace(owner, obj, type);
}
/// Remove traces for owner \p owner.
static void RemoveTraces(const void* owner)
{
TfRefPtrTracker::GetInstance()._RemoveTraces(owner);
}
};
#define TF_DECLARE_REFPTR_TRACK(T) \
inline void Tf_RefPtrTracker_FirstRef(const void*, T* obj); \
inline void Tf_RefPtrTracker_LastRef(const void*, T* obj); \
inline void Tf_RefPtrTracker_New(const void* owner, T* obj); \
inline void Tf_RefPtrTracker_Delete(const void* owner, T* obj); \
inline void Tf_RefPtrTracker_Assign(const void* owner, T* obj, T* oldObj);
#define TF_DEFINE_REFPTR_TRACK(T, COND) \
inline void Tf_RefPtrTracker_FirstRef(const void*, T* obj) { \
if (obj && COND(obj)) Tf_RefPtrTrackerUtil::Watch(obj); \
} \
inline void Tf_RefPtrTracker_LastRef(const void*, T* obj) { \
Tf_RefPtrTrackerUtil::Unwatch(obj); \
} \
inline void Tf_RefPtrTracker_New(const void* owner, T* obj) { \
Tf_RefPtrTrackerUtil::AddTrace(owner, obj); \
} \
inline void Tf_RefPtrTracker_Delete(const void* owner, T* obj) { \
Tf_RefPtrTrackerUtil::RemoveTraces(owner); \
} \
inline void Tf_RefPtrTracker_Assign(const void* owner, T* obj, T* oldObj) { \
if (oldObj != obj) { \
Tf_RefPtrTrackerUtil::AddTrace(owner, obj, TfRefPtrTracker::Assign);\
} \
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+154
View File
@@ -0,0 +1,154 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_REG_TEST_H
#define PXR_BASE_TF_REG_TEST_H
/// \file tf/regTest.h
/// \ingroup group_tf_Internal
/// Support for simple regression tests.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/hashmap.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfRegTest
/// \ingroup group_tf_Internal
///
/// \c TfRegTest is a singleton class, which is used to register functions
/// with either type \c bool \c (*)(int, char*[]), or functions returning type
/// \c bool and taking no arguments.
///
/// Here is how \c TfRegTest is used to create tests in separate files, which
/// are then compiled into a single standalone executable (and not part of any
/// library):
///
/// // file: main.cpp
/// \include test/main.cpp
///
/// // file: hammer.cpp
/// \code
/// #include "pxr/base/tf/regTest.h"
///
/// static bool
/// Test_PtHammer()
/// {
/// bool success;
/// ...
/// return success;
/// }
/// TF_ADD_REGTEST(PtHammer);
/// \endcode
///
/// \code
/// // file: drill.cpp
/// static bool
/// Test_PtDrill(int argc, char *argv[])
/// {
/// bool success;
/// ...
/// return success;
/// }
/// TF_ADD_REGTEST(PtDrill);
/// \endcode
///
/// When \c main.cpp, \c drill.cpp and \c hammer.cpp are compiled into
/// an executable, then a test can be run by invoking the executable
/// with a first argument of either \p PtHammer or \p PtDrill.
/// Since \p PtHammer is a function without arguments, supplying additional
/// arguments is an error; but \p PtDrill takes arguments, so additional
/// command-line arguments specified are passed to the function.
/// (Most library test functions shouldn't need any arguments.)
///
class TfRegTest {
public:
/// Run a single regression test function, returning 0 if the function
/// succeeded and 1 otherwise.
///
/// This function is intended to be called as follows:
/// \code
/// int main(int argc, char *argv[]) {
/// return TfRegTest::Main(argc, argv);
/// }
/// \endcode
///
/// The first argument is the name of the test to be run. If the
/// registered test function run takes no arguments, then no arguments
/// other than the test name should be supplied. Otherwise, the \c Main()
/// passes \c argc-1 and \c argv+1 to the test function, and the test
/// function is responsible for argument checking.
static int Main(int argc, char *argv[]) {
return GetInstance()._Main(argc, argv);
}
TF_API
static TfRegTest& GetInstance();
/// Type of a function with no arguments.
typedef bool (*RegFunc)();
/// Type of a function with arguments.
///
/// When \c Main(argc,argv) is requested to run a function of type
/// \c RegFuncWithArgs, it invokes the function with arguments \c argc-1
/// and \c argv+1.
typedef bool (*RegFuncWithArgs)(int argc, char *argv[]);
TF_API
bool Register(const char* name, RegFunc);
TF_API
bool Register(const char* name, RegFuncWithArgs);
private:
friend class TfSingleton<TfRegTest>;
TF_API
int _Main(int argc, char *argv[]);
void _PrintTestNames();
typedef TfHashMap<std::string, RegFunc, TfHash> _Hash;
typedef TfHashMap<std::string, RegFuncWithArgs, TfHash> _HashWithArgs;
_Hash _functionTable;
_HashWithArgs _functionTableWithArgs;
};
TF_API_TEMPLATE_CLASS(TfSingleton<TfRegTest>);
/// Adds the function Test_\p name, under name \p name, as a runnable
/// regression test. Test_\p name must be of type \c RegFunc or
/// \c RegFuncWithArgs.
///
/// \ingroup group_tf_Internal
/// \hideinitializer
#define TF_ADD_REGTEST(name) \
bool Tf_RegTst##name = TfRegTest::GetInstance().Register(#name, Test_##name)
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+265
View File
@@ -0,0 +1,265 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_REGISTRY_MANAGER_H
#define PXR_BASE_TF_REGISTRY_MANAGER_H
/// \file tf/registryManager.h
/// \ingroup group_tf_Initialization
#include "pxr/pxr.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include "pxr/base/tf/api.h"
#include <functional>
#include <typeinfo>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfRegistryManager
/// \ingroup group_tf_Initialization
///
/// Manage initialization of registries.
///
/// See \ref page_tf_RegistryManager for a detailed description.
///
class TfRegistryManager {
TfRegistryManager(const TfRegistryManager&) = delete;
TfRegistryManager& operator=(const TfRegistryManager&) = delete;
public:
// The type of a registration function. The arguments are not used.
typedef void (*RegistrationFunctionType)(void*, void*);
typedef std::function<void ()> UnloadFunctionType;
/// Return the singleton \c TfRegistryManager instance.
TF_API static TfRegistryManager& GetInstance();
/// Request that any initialization for service \c T be performed.
///
/// Calling \c SubscribeTo<T>() causes all existing \c
/// TF_REGISTRY_FUNCTION() functions of type \c T to be run. Once
/// this call is made, when new code is dynamically loaded then any
/// \c TF_REGISTRY_FUNCTION() functions of type \c T in the new code
/// will automatically be run when the code is loaded.
template <class T>
void SubscribeTo() {
_SubscribeTo(typeid(T));
}
/// Cancel any previous subscriptions to service \c T.
///
/// After this call, newly added code will no longer have \c
/// TF_REGISTRY_FUNCTION() functions of type \c T run.
template <class T>
void UnsubscribeFrom() {
_UnsubscribeFrom(typeid(T));
}
/// Add an action to be performed at code unload time.
///
/// When a \c TF_REGISTRY_FUNCTION() is run, it often needs to register an
/// inverse action to be taken when the code containing that function is
/// unloaded. For example, a plugin that adds information to a registry
/// will typically want to remove that information when the registry is
/// unloaded.
///
/// Calling \c AddFunctionForUnload() requests that the given function be
/// run if the code from which the function is called is unloaded.
/// However, this is detectable only if this call is made from within the
/// call chain of some \c TF_REGISTRY_FUNCTION() function. In this case,
/// \c AddFunctionForUnload() returns true. Otherwise, false is returned
/// and the function is never run.
///
/// Note however that by default, no unload functions are run when code is
/// being unloaded because exit() has been called. This is an
/// optimization, because most registries don't need to be deconstructed
/// at exit time. This behavior can be changed by calling \c
/// RunUnloadersAtExit().
TF_API bool AddFunctionForUnload(const UnloadFunctionType&);
/// Run unload functions program exit time.
///
/// The functions added by \c AddFunctionForUnload() are normally not run
/// when a program exits. For debugging purposes (e.g. checking for
/// memory leaks) it may be desirable to run the functions even at program
/// exit time. This call will force functions to be run at program exit
/// time.
///
/// Note that this call does not cause construction of the singleton \c
/// TfRegistryManager object if it does not already exist.
TF_API static void RunUnloadersAtExit();
private:
TF_API TfRegistryManager();
TF_API ~TfRegistryManager();
TF_API void _SubscribeTo(const std::type_info&);
TF_API void _UnsubscribeFrom(const std::type_info&);
};
TF_API void Tf_RegistryInitCtor(char const *name);
TF_API void Tf_RegistryInitDtor(char const *name);
namespace {
struct Tf_RegistryStaticInit {
Tf_RegistryStaticInit() {
Tf_RegistryInitCtor(TF_PP_STRINGIZE(MFB_ALT_PACKAGE_NAME));
}
~Tf_RegistryStaticInit() {
Tf_RegistryInitDtor(TF_PP_STRINGIZE(MFB_ALT_PACKAGE_NAME));
}
};
}
// Private class used to indicate the library has finished registering
// functions, to indicate that the library is being unloaded and to
// add functions to the registry.
class Tf_RegistryInit {
public:
TF_API static void Add(const char* libName,
TfRegistryManager::RegistrationFunctionType func,
const char* typeName);
template <class T, class U>
static void Add(const char* libName,
void (*func)(T*, U*),
const char* typeName)
{
Add(libName,(TfRegistryManager::RegistrationFunctionType)func,typeName);
}
};
// The ARCH_CONSTRUCTOR priority for registering registry functions.
#define TF_REGISTRY_PRIORITY 100
//
// Macros for adding registry functions outside class templates.
//
// Define a registry function outside of a template. Follow the macro with
// the body of the function inside braces. KEY_TYPE and TAG must be types.
#define TF_REGISTRY_DEFINE_WITH_TYPE(KEY_TYPE, TAG) \
static void _Tf_RegistryFunction(KEY_TYPE*, TAG*); \
ARCH_CONSTRUCTOR(TF_PP_CAT(_Tf_RegistryAdd, __LINE__), \
TF_REGISTRY_PRIORITY, KEY_TYPE*, TAG*) \
{ \
Tf_RegistryInit::Add(TF_PP_STRINGIZE(MFB_ALT_PACKAGE_NAME), \
(void(*)(KEY_TYPE*, TAG*))_Tf_RegistryFunction, \
TF_PP_STRINGIZE(KEY_TYPE)); \
} \
_ARCH_ENSURE_PER_LIB_INIT(Tf_RegistryStaticInit, _tfRegistryInit); \
static void _Tf_RegistryFunction(KEY_TYPE*, TAG*)
// Define a registry function outside of a template. Follow the macro with
// the body of the function inside braces. KEY_TYPE must be a type and NAME
// must be a valid C++ name.
#define TF_REGISTRY_DEFINE(KEY_TYPE, NAME) \
static void TF_PP_CAT(_Tf_RegistryFunction, NAME)(KEY_TYPE*, void*); \
ARCH_CONSTRUCTOR(TF_PP_CAT(_Tf_RegistryAdd, NAME), \
TF_REGISTRY_PRIORITY, KEY_TYPE*) \
{ \
Tf_RegistryInit::Add(TF_PP_STRINGIZE(MFB_ALT_PACKAGE_NAME), \
(void(*)(KEY_TYPE*, void*)) \
TF_PP_CAT(_Tf_RegistryFunction, NAME), \
TF_PP_STRINGIZE(KEY_TYPE)); \
} \
_ARCH_ENSURE_PER_LIB_INIT(Tf_RegistryStaticInit, _tfRegistryInit); \
static void TF_PP_CAT(_Tf_RegistryFunction, NAME)(KEY_TYPE*, void*)
/// Define a function that is called on demand by \c TfRegistryManager.
///
/// This is a simpler form of TF_REGISTRY_FUNCTION_WITH_TAG() that provides
/// a tag for you, based on the MFB package, file name, and line number being
/// compiled. For most cases (private registry functions inside .cpp files)
/// this should do.
///
/// A very common use is to symbolically define enum names (see \c TfEnum):
/// \code
/// TF_REGISTRY_FUNCTION(TfEnum)
/// {
/// // Bit-depth types.
/// TF_ADD_ENUM_NAME(ELEM_BITDEPTH_8);
/// TF_ADD_ENUM_NAME(ELEM_BITDEPTH_10);
/// TF_ADD_ENUM_NAME(ELEM_BITDEPTH_32);
///
/// // Destination types.
/// TF_ADD_ENUM_NAME(ELEM_DESTINATION_DISKFARM);
/// TF_ADD_ENUM_NAME(ELEM_DESTINATION_JOBDIR);
///
/// // Renderer types.
/// TF_ADD_ENUM_NAME(ELEM_RENDERER_GRAIL);
/// TF_ADD_ENUM_NAME(ELEM_RENDERER_PRMAN);
/// }
/// \endcode
///
/// \hideinitializer
#define TF_REGISTRY_FUNCTION(KEY_TYPE) \
TF_REGISTRY_DEFINE(KEY_TYPE, __LINE__)
/// Define a function that is called on demand by \c TfRegistryManager.
///
/// Here is an example of using this macro:
/// \code
/// #include "pxr/base/tf/registryManager.h"
///
/// TF_REGISTRY_FUNCTION_WITH_TAG(XyzRegistry, MyTag)
/// {
/// // calls to, presumably, XyzRegistry:
/// ...
/// }
///\endcode
///
/// Given the above, a call to \c TfRegistryManager::SubscribeTo<XyzRegistry>()
/// will cause the above function to be immediately run. (If the above function
/// has not yet been loaded, but is loaded in the future, it will be run then.)
/// The second type, \c MyType, is unimportant, but cannot be repeated with the
/// first type (i.e. there can be at most one call to \c TF_REGISTRY_FUNCTION()
/// for a given pair of types).
///
/// In contrast to the typical static-constructor design, the code within a
/// TF_REGISTRY_FUNCTION() function is (usually) not run before main();
/// specifically, it is not run unless and until a call to SubscribeTo<T>()
/// occurs. This is important: if there are no subscribers, the code may never
/// be run.
///
/// Note two restrictions: the type-names \p KEY_TYPE and \c TAG passed
/// to this macro must be untemplated, and not qualified with a
/// namespace. (Translation: the name as given must consist solely of letters and
/// numbers: no "\<", "\>" or ":" characters are allowed.) KEY_TYPE may be inside
/// a namespace but must not be explicitly qualified; you must use 'using
/// namespace &lt;foo\>::KEY_TYPE' before calling this macro. Every use of \c
/// TF_REGISTRY_FUNCTION() must use a different pair for \c KEY_TYPE and \c
/// TAG or a multiply defined symbol will result at link time. Note
/// that this means the same KEY_TYPE in two or more namespaces may not be
/// registered in more than one namespace.
///
/// \hideinitializer
#define TF_REGISTRY_FUNCTION_WITH_TAG(KEY_TYPE, TAG) \
TF_REGISTRY_DEFINE(KEY_TYPE, TF_PP_CAT(TAG, __LINE__))
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_REGISTRY_MANAGER_H
+110
View File
@@ -0,0 +1,110 @@
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SAFE_OUTPUT_FILE_H
#define PXR_BASE_TF_SAFE_OUTPUT_FILE_H
/// \file tf/safeOutputFile.h
/// Safe file writer with FILE * interface.
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <cstdio>
#include <memory>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfSafeOutputFile
///
/// Opens a file for output, either for update "r+" or to completely replace
/// "w+". In the case of complete replacement, create a sibling temporary file
/// to write to instead. When writing is complete, rename the temporary file
/// over the target file. This provides some safety to other processes reading
/// the existing file (at least on unix-like OSs). They will continue to see
/// the existing contents of the old file. If we overwrote the file itself,
/// then those other processes would see undefined, possibly partially updated
/// content.
class TfSafeOutputFile
{
TfSafeOutputFile(TfSafeOutputFile const &) = delete;
TfSafeOutputFile &operator=(TfSafeOutputFile const &) = delete;
public:
TfSafeOutputFile() = default;
TfSafeOutputFile(TfSafeOutputFile &&other)
: _file(other._file)
, _targetFileName(std::move(other._targetFileName))
, _tempFileName(std::move(other._tempFileName))
{ other._file = nullptr; }
TfSafeOutputFile &operator=(TfSafeOutputFile &&other) {
_file = other._file;
_targetFileName = std::move(other._targetFileName);
_tempFileName = std::move(other._tempFileName);
other._file = nullptr;
return *this;
}
/// Destructor invokes Close().
TF_API ~TfSafeOutputFile();
/// Open \p fileName for update ("r+").
TF_API static TfSafeOutputFile Update(std::string const &fileName);
/// Arrange for \p fileName to be replaced. Create a sibling temporary file
/// and open that for writing. When Close() is called (or the destructor is
/// run) close the temporary file and rename it over \p fileName.
TF_API static TfSafeOutputFile Replace(std::string const &fileName);
/// Close the file. If the file was opened with Replace(), rename the
/// temporary file over the target file to replace it.
TF_API void Close();
/// Close the file. If the file was opened with Replace(), the temporary
/// file is removed and not renamed over the target file. It is an error
/// to call this for files opened for Update.
TF_API void Discard();
/// Return the opened FILE *.
FILE *Get() const { return _file; }
/// If the underlying file was opened by Update(), return it. The caller
/// takes responsibility for closing the file later. It is an error to call
/// this for files opened for Replace.
TF_API FILE *ReleaseUpdatedFile();
/// Return true if this TfSafeOutputFile was created by a call to Update(),
/// false otherwise.
TF_API bool IsOpenForUpdate() const;
private:
FILE *_file = nullptr;
std::string _targetFileName;
std::string _tempFileName;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SAFE_OUTPUT_FILE_H
+61
View File
@@ -0,0 +1,61 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SAFE_TYPE_COMPARE_H
#define PXR_BASE_TF_SAFE_TYPE_COMPARE_H
/// \file tf/safeTypeCompare.h
/// \ingroup group_tf_RuntimeTyping
/// Safely compare C++ RTTI type structures.
#include "pxr/pxr.h"
#include <typeinfo>
PXR_NAMESPACE_OPEN_SCOPE
/// Safely compare \c std::type_info structures.
///
/// Returns \c true if \p t1 and \p t2 denote the same type.
inline bool TfSafeTypeCompare(const std::type_info& t1, const std::type_info& t2) {
return t1 == t2;
}
/// Safely perform a dynamic cast.
///
/// Usage should mirror regular \c dynamic_cast:
/// \code
/// Derived* d = TfSafeDynamic_cast<Derived*>(basePtr);
/// \endcode
///
/// Note that this function also works with \c TfRefPtr and \c TfWeakPtr
/// managed objects.
template <typename TO, typename FROM>
TO
TfSafeDynamic_cast(FROM* ptr) {
return dynamic_cast<TO>(ptr);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SAFE_TYPE_COMPARE_H
+143
View File
@@ -0,0 +1,143 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SCOPE_DESCRIPTION_H
#define PXR_BASE_TF_SCOPE_DESCRIPTION_H
#include "pxr/pxr.h"
#include "pxr/base/tf/callContext.h"
#include "pxr/base/tf/preprocessorUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/api.h"
#include <boost/optional.hpp>
#include <boost/preprocessor/if.hpp>
#include <vector>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfScopeDescription
///
/// This class is used to provide high-level descriptions about scopes of
/// execution that could possibly block, or to provide relevant information
/// about high-level action that would be useful in a crash report.
///
/// This class is reasonably fast to use, especially if the message strings are
/// not dynamically created, however it should not be used in very highly
/// performance sensitive contexts. The cost to push & pop is essentially a TLS
/// lookup plus a couple of atomic operations.
class TfScopeDescription
{
TfScopeDescription() = delete;
TfScopeDescription(TfScopeDescription const &) = delete;
TfScopeDescription &operator=(TfScopeDescription const &) = delete;
public:
/// Construct with a description. Push \a description on the stack of
/// descriptions for this thread. Caller guarantees that the string
/// \p description lives at least as long as this TfScopeDescription object.
TF_API explicit
TfScopeDescription(std::string const &description,
TfCallContext const &context = TfCallContext());
/// Construct with a description. Push \a description on the stack of
/// descriptions for this thread. This object adopts ownership of the
/// rvalue \p description.
TF_API explicit
TfScopeDescription(std::string &&description,
TfCallContext const &context = TfCallContext());
/// Construct with a description. Push \a description on the stack of
/// descriptions for this thread. Caller guarantees that the string
/// \p description lives at least as long as this TfScopeDescription object.
TF_API explicit
TfScopeDescription(char const *description,
TfCallContext const &context = TfCallContext());
/// Destructor.
/// Pop the description stack in this thread.
TF_API ~TfScopeDescription();
/// Replace the description stack entry for this scope description. Caller
/// guarantees that the string \p description lives at least as long as this
/// TfScopeDescription object.
TF_API void SetDescription(std::string const &description);
/// Replace the description stack entry for this scope description. This
/// object adopts ownership of the rvalue \p description.
TF_API void SetDescription(std::string &&description);
/// Replace the description stack entry for this scope description. Caller
/// guarantees that the string \p description lives at least as long as this
/// TfScopeDescription object.
TF_API void SetDescription(char const *description);
private:
friend inline TfScopeDescription *
Tf_GetPreviousScopeDescription(TfScopeDescription *d) {
return d->_prev;
}
friend inline char const *
Tf_GetScopeDescriptionText(TfScopeDescription *d) {
return d->_description;
}
friend inline TfCallContext const &
Tf_GetScopeDescriptionContext(TfScopeDescription *d) {
return d->_context;
}
inline void _Push();
inline void _Pop() const;
boost::optional<std::string> _ownedString;
char const *_description;
TfCallContext _context;
void *_localStack;
TfScopeDescription *_prev; // link to parent scope.
};
/// Return a copy of the current description stack for the "main" thread as
/// identified by ArchGetMainThreadId() as a vector of strings. The most
/// recently pushed description is at back(), and the least recently pushed
/// description is at front().
TF_API std::vector<std::string>
TfGetCurrentScopeDescriptionStack();
/// Return a copy of the current description stack for the current thread of
/// execution as a vector of strings. The most recently pushed description is
/// at back(), and the least recently pushed description is at front().
TF_API std::vector<std::string>
TfGetThisThreadScopeDescriptionStack();
/// Macro that accepts either a single string, or printf-style arguments and
/// creates a scope description local variable with the resulting string.
#define TF_DESCRIBE_SCOPE(fmt, ...) \
TfScopeDescription __scope_description__ \
(BOOST_PP_IF(TF_NUM_ARGS(__VA_ARGS__), \
TfStringPrintf(fmt, __VA_ARGS__), fmt), TF_CALL_CONTEXT)
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SCOPE_DESCRIPTION_H
+212
View File
@@ -0,0 +1,212 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SCOPED_H
#define PXR_BASE_TF_SCOPED_H
#include "pxr/pxr.h"
#include <functional>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfScoped
/// \ingroup group_tf_Multithreading
///
/// Execute code on exiting scope.
///
/// A \c TfScoped executes code when destroyed. It's useful when cleanup code
/// should be executed when exiting the scope because it gets executed no
/// matter how the scope is exited (e.g. normal execution, return, exceptions,
/// etc).
///
/// \code
/// int func(bool x) {
/// TfScoped scope(cleanup);
/// return func2(x); // call cleanup after calling func2
/// }
/// \endcode
///
template <typename T = std::function<void ()> >
class TfScoped {
TfScoped(TfScoped const &) = delete;
TfScoped &operator=(TfScoped const &) = delete;
public:
/// The type of the function executed on destruction.
typedef T Procedure;
/// Execute \p leave when this object goes out of scope.
explicit TfScoped(const Procedure& leave) : _onExit(leave) { }
~TfScoped() { _onExit(); }
private:
// Can't put these on the heap. No implementation needed.
static void *operator new(::std::size_t size);
private:
Procedure _onExit;
};
// Specialization of TfScoped for member functions.
template <typename T>
class TfScoped<void (T::*)()> {
TfScoped(TfScoped const &) = delete;
TfScoped &operator=(TfScoped const &) = delete;
public:
/// The type of the function executed on destruction.
typedef void (T::*Procedure)();
/// Execute \p leave on \p obj when this object goes out of scope.
explicit TfScoped(T* obj, const Procedure& leave) :
_obj(obj), _onExit(leave) { }
~TfScoped() { (_obj->*_onExit)(); }
private:
// Can't put these on the heap. No implementation needed.
static void *operator new(::std::size_t size);
private:
T* _obj;
Procedure _onExit;
};
// Specialization of TfScoped for functions taking one pointer argument.
template <typename T>
class TfScoped<void (*)(T*)> {
TfScoped(TfScoped const &) = delete;
TfScoped &operator=(TfScoped const &) = delete;
public:
/// The type of the function executed on destruction.
typedef void (*Procedure)(T*);
/// Execute \p leave, passing \p obj, when this object goes out of scope.
explicit TfScoped(const Procedure& leave, T* obj) :
_obj(obj), _onExit(leave) { }
~TfScoped() { _onExit(_obj); }
private:
// Can't put these on the heap. No implementation needed.
static void *operator new(::std::size_t size);
private:
T* _obj;
Procedure _onExit;
};
/// \class TfScopedVar
///
/// Reset variable on exiting scope.
///
/// A \c TfScopedVar sets a variable to a value when created then restores its
/// original value when destroyed. For example:
///
/// \code
/// int func(bool x) {
/// TfScopedVar<bool> scope(x, true); // set x to true
/// return func2(x); // restore x after calling func2
/// }
/// \endcode
template <typename T>
class TfScopedVar {
TfScopedVar(TfScopedVar const &) = delete;
TfScopedVar &operator=(TfScopedVar const &) = delete;
public:
/// Set/reset variable
///
/// Sets \p x to \p val immediately and restores its old value when this
/// goes out of scope.
explicit TfScopedVar(T& x, const T& val) :
_x(&x),
_old(x)
{
x = val;
}
~TfScopedVar() { *_x = _old; }
private:
// Can't put these on the heap. No implementation needed.
static void *operator new(::std::size_t size);
private:
T* _x;
T _old;
};
/// \class TfScopedAutoVar
///
/// Reset variable on exiting scope.
///
/// A \c TfScopedAutoVar sets a variable to a value when created then restores
/// its original value when destroyed.
///
/// For example:
/// \code
/// int func(bool x) {
/// TfScopedAutoVar scope(x, true); // set x to true
/// return func2(x); // restore x after calling func2
/// }
/// \endcode
///
/// This differs from \c TfScopedVar in that it's not a template class, the
/// value type is deduced automatically and it allocates memory on the heap.
/// If performance is critical or memory must not be allocated then use \c
/// TfScopedVar instead.
///
/// \see TfScopedVar
class TfScopedAutoVar {
TfScopedAutoVar(TfScopedAutoVar const &) = delete;
TfScopedAutoVar &operator=(TfScopedAutoVar const &) = delete;
public:
/// Set/reset variable
///
/// Sets \p x to \p val immediately and restores its old value when this
/// goes out of scope.
template <typename T>
explicit TfScopedAutoVar(T& x, const T& val) :
_scope(std::bind(&TfScopedAutoVar::_Set<T>, &x, x))
{
x = val;
}
private:
// Restore value function
template <typename T>
static void _Set(T* x, const T& val)
{
*x = val;
}
// Can't put these on the heap. No implementation needed.
static void *operator new(::std::size_t size);
private:
TfScoped<> _scope;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SCOPED_H
+148
View File
@@ -0,0 +1,148 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SCRIPT_MODULE_LOADER_H
#define PXR_BASE_TF_SCRIPT_MODULE_LOADER_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/weakBase.h"
// XXX: This include is a hack to avoid build errors due to
// incompatible macro definitions in pyport.h on macOS.
#include <locale>
#include <boost/python/dict.hpp>
#include <deque>
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/hashset.h"
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfScriptModuleLoader
///
/// Provides low-level facilities for shared libraries with script bindings to
/// register themselves with their dependences, and provides a mechanism
/// whereby those script modules will be loaded when necessary. Currently,
/// this is when one of our script modules is loaded, when TfPyInitialize is
/// called, and when Plug opens shared libraries.
///
/// Generally, user code will not make use of this.
///
class TfScriptModuleLoader : public TfWeakBase {
public:
typedef TfScriptModuleLoader This;
/// Return the singleton instance.
TF_API static This &GetInstance() {
return TfSingleton<This>::GetInstance();
}
/// Register a library named \a name and with script module \a moduleName
/// and libraries which must be loaded first \a predecessors. The script
/// module will be loaded when necessary. This should generally not be
/// called by user code.
TF_API
void RegisterLibrary(TfToken const &name, TfToken const &moduleName,
std::vector<TfToken> const &predecessors);
/// Load all the script modules for any libraries registered using \a
/// RegisterLibrary if necessary. Loads the modules in dependency order as
/// defined in \a RegisterLibrary.
TF_API
void LoadModules();
/// Load all the script modules for any libraries registered using \a
/// RegisterLibrary that depend on library \a name.
TF_API
void LoadModulesForLibrary(TfToken const &name);
/// Return a list of all currently known modules in a valid dependency
/// order.
TF_API
std::vector<std::string> GetModuleNames() const;
/// Return a python dict containing all currently known modules under
/// their canonical names.
TF_API
boost::python::dict GetModulesDict() const;
/// Write a graphviz dot-file for the dependency graph of all. currently
/// known libraries/modules to \a file.
TF_API
void WriteDotFile(std::string const &file) const;
private:
struct _LibInfo {
_LibInfo() {}
std::vector<TfToken> predecessors, successors;
};
typedef TfHashMap<TfToken, _LibInfo, TfToken::HashFunctor>
_TokenToInfoMap;
typedef TfHashMap<TfToken, TfToken, TfToken::HashFunctor>
_TokenToTokenMap;
typedef TfHashSet<TfToken, TfToken::HashFunctor>
_TokenSet;
TfScriptModuleLoader();
virtual ~TfScriptModuleLoader();
friend class TfSingleton<This>;
void _AddSuccessor(TfToken const &lib, TfToken const &successor);
void _LoadModulesFor(TfToken const &name);
void _LoadUpTo(TfToken const &name);
void _GetOrderedDependenciesRecursive(TfToken const &lib,
TfToken::HashSet *seenLibs,
std::vector<TfToken> *result) const;
void _GetOrderedDependencies(std::vector<TfToken> const &input,
std::vector<TfToken> *result) const;
void _TopologicalSort(std::vector<TfToken> *result) const;
bool _HasTransitiveSuccessor(TfToken const &predecessor,
TfToken const &successor) const;
_TokenToInfoMap _libInfo;
_TokenToTokenMap _libsToModules;
_TokenSet _loadedSet;
// This is only used to handle reentrant loading requests.
std::deque<TfToken> _remainingLoadWork;
};
TF_API_TEMPLATE_CLASS(TfSingleton<TfScriptModuleLoader>);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SCRIPT_MODULE_LOADER_H
+70
View File
@@ -0,0 +1,70 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SETENV_H
#define PXR_BASE_TF_SETENV_H
/// \file tf/setenv.h
/// \ingroup group_tf_SystemsExt
/// Functions for setting and unsetting environment variables
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// Set an environment variable.
///
/// Sets an environment variable and ensures that it appears in the Python
/// environment if Python is initialized. If Python has not yet been
/// initialized, the variable \p envName is set to \p value in the environment
/// using \c setenv. Otherwise, it is set both in the environment and in
/// Python using \c TfPySetenv. The new value overwrites any existing value.
///
/// If the value cannot be set, false is returned and a warning is posted.
/// Otherwise, the return value is true.
///
/// \ingroup group_tf_SystemsExt
TF_API
bool TfSetenv(const std::string& envName, const std::string& value);
/// Unset an environment variable.
///
/// Unsets an environment variable and ensures that it is also removed from
/// the Python environment if Python is initialized. If Python has not yet
/// been initialized, the variable \p envName is unset in the environment
/// using \c unsetenv. Otherwise, it is unset both in the environment and in
/// Python using \c TfPyUnsetenv.
///
/// If the value cannot be unset, false is returned and a warning is posted.
/// Otherwise, the return value is true.
///
/// \ingroup group_tf_SystemsExt
TF_API
bool TfUnsetenv(const std::string& envName);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SETENV_H
+203
View File
@@ -0,0 +1,203 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SINGLETON_H
#define PXR_BASE_TF_SINGLETON_H
/// \file tf/singleton.h
/// \ingroup group_tf_ObjectCreation
/// Manage a single instance of an object.
///
/// Many classes (for example, registries) should have only a single, globally
/// available instance that is created as needed on demand. This is a classic
/// design pattern known as a \e singleton. Additionally, creation of this
/// class (though not access to it per se) must be made threadsafe.
///
/// There are two possibilities in creating a singleton: you can create a
/// class all of whose member functions and variables are static, and let
/// users access this class. Unfortunately, instantiating the static
/// variables of this class is prone to difficulty; more importantly, should
/// you change your mind and wish to allow multiple instances of the class,
/// much rewriting follows.
///
/// A better solution is to define the class with regular members and
/// variables, and then permit only a single instance of the class to exist.
/// This is the philosophy embodied by the \c TfSingleton template. It takes
/// care of both multithreaded initialization and initialization before main;
/// the cost of this is quite low (a single boolean comparison to access the
/// instanced object after initial creation). The \c TfSingleton template
/// works in conjunction with a macro in the source file
/// TF_INSTANTIATE_SINGLETON(), which is itself defined by including the file
/// "pxr/base/tf/instantiateSingleton.h".
///
/// \anchor TfSingleton_typicalUse
/// <B> Typical Use </B>
///
/// The typical use of \c TfSingleton is as follows:
/// \code
/// // file: registry.h
/// #include "pxr/base/tf/singleton.h"
/// #include <boost/noncopyable.hpp>
///
/// class Registry : boost::noncopyable {
/// public:
/// static Registry& GetInstance() {
/// return TfSingleton<Registry>::GetInstance();
/// }
///
/// ...
///
/// private:
/// Registry();
/// ~Registry();
///
/// friend class TfSingleton<Registry>;
/// };
///
/// // file: Registry.cpp
/// #include "common/astrology/registry.h"
/// #include "pxr/base/tf/instantiateSingleton.h"
///
/// TF_INSTANTIATE_SINGLETON(Registry);
///
///
/// // file: RandomCode.cpp
/// #include "common/astrology/registry.h"
///
/// void Code() {
/// Registry& r = Registry::GetInstance();
/// r.Lookup(...);
/// ...
/// }
/// \endcode
///
/// The constructor and destructor are declared private, and the singleton
/// object will typically derive off of \c boost::noncopyable to prevent
/// copying. Note that singleton objects quite commonly also make use of \c
/// TfRegistryManager to acquire the data they need throughout a program.
///
/// The friend class \c TfSingleton<Registry> is the only class allowed to
/// create an instance of a Registry. The helper function \c
/// Registry::GetInstance() is for convenience only; one can just as well call
/// the longer \c TfSingleton<Registry>::GetInstance() to obtain a reference
/// to the sole instance of the registry.
#include "pxr/pxr.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/arch/pragmas.h"
#include "pxr/base/tf/diagnosticLite.h"
#include <mutex>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfSingleton
/// \ingroup group_tf_ObjectCreation
///
/// Manage a single instance of an object (see
///
/// \ref TfSingleton_typicalUse "Typical Use" for a canonical example).
///
template <class T>
class TfSingleton {
public:
/// Return a reference to an object of type \c T, creating it if
/// necessary.
///
/// When \c GetInstance() is called for the first time, it creates an
/// object of type \c T, and returns a reference to it. The type in
/// question must have a default constructor (i.e. a constructor taking no
/// arguments).
///
/// Subsequent calls to \c GetInstance() return a reference to the same
/// object. This call is threadsafe; simultaneous attempts to create an
/// object result in only one object being created; locking beyond this
/// (for example, letting only one thread at a time call a member
/// function) are the responsibility of the class author.
inline static T& GetInstance() {
ARCH_PRAGMA_PUSH
// Suppress warnings from clang. TfSingletons are explicitly
// instantiated, so the warning around this usage is a false positive.
ARCH_PRAGMA_UNDEFINED_VAR_TEMPLATE
return ARCH_LIKELY(_instance) ? *_instance : _CreateInstance();
ARCH_PRAGMA_POP
}
/// Return whether or not the single object of type \c T is currently in
/// existence.
///
/// This call tests whether or not the singleton currently exists.
static bool CurrentlyExists() {
return _instance ? true : false;
}
/// Indicate that the sole instance object has already been created.
///
/// This function is public, but can only be called usefully from within
/// the class T itself. This function is used to allow the constructor of
/// T to indicate that the sole instance of T has been created, and that
/// future calls to \c GetInstance() can immediately return \p instance.
///
/// The need for this function occurs when the constructor of \c T
/// generates a call chain that leads to calling \c
/// TfSingleton<T>::GetInstance(). Until the constructor for \c T has
/// finished, however, \c TfSingleton<T>::GetInstance() is unable to
/// return a value. Calling \c SetInstanceConstructed() allows future
/// calls to \c TfSingleton<T>::GetInstance() to return before \c T's
/// constructor has finished.
///
/// Be sure that \c T has been constructed (enough) before calling this
/// function. Calling this function anyplace but within the call chain of
/// \c T's constructor will generate a fatal coding error.
static void SetInstanceConstructed(T& instance) {
if (_instance)
TF_FATAL_ERROR("this function may not be called after "
"GetInstance() has completed");
_instance = &instance;
}
/// Destroy the sole instance object of type \c T, if it exists.
///
/// A singleton can be destroyed by a call to \c DeleteInstance. This call
/// is threadsafe in the sense that competing simultaneous calls will not
/// result in double deletion; however, it is up to the user to ensure
/// that the instance is not being used in one thread during an attempt to
/// delete the instance from another thread. After being destroyed, a
/// call to \c GetInstance() will create a new instance.
static void DeleteInstance() {
if (_instance)
_DestroyInstance();
}
private:
static T& _CreateInstance();
static void _DestroyInstance();
static T* _instance;
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_NEEDS_EXPORT_INTERFACE
static std::mutex* _mutex;
ARCH_PRAGMA_POP
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+939
View File
@@ -0,0 +1,939 @@
//
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SMALL_VECTOR_H
#define PXR_BASE_TF_SMALL_VECTOR_H
///
/// \file
#include "pxr/pxr.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <memory>
#include <new>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
// Contains parts of the small vector implementation that do not depend on
// *all* of TfSmallVector's template parameters.
class TfSmallVectorBase
{
public:
using size_type = std::uint32_t;
using difference_type = std::int32_t;
// Returns the local capacity that may be used without increasing the size
// of the TfSmallVector. TfSmallVector<T, N> will never use more local
// capacity than is specified by N but clients that wish to maximize local
// occupancy in a generic way can compute N using this function.
template <typename U>
static constexpr size_type ComputeSerendipitousLocalCapacity() {
return (alignof(U) <= alignof(_Data<U, 0>))
? sizeof(_Data<U, 0>) / sizeof(U)
: 0;
}
protected:
// Invoke std::uninitialized_copy that either moves or copies entries,
// depending on whether the type is move constructible or not.
template <typename Iterator>
static Iterator _UninitializedMove(
Iterator first, Iterator last, Iterator dest) {
return std::uninitialized_copy(
std::make_move_iterator(first),
std::make_move_iterator(last),
dest);
}
// Invokes either the move or copy constructor (via placement new),
// depending on whether U is move constructible or not.
template <typename U>
static void _MoveConstruct(U *p, U *src) {
new (p) U(std::move(*src));
}
// The data storage, which is a union of both the local storage, as well
// as a pointer, holding the address to the remote storage on the heap, if
// used.
template < typename U, size_type M >
union _Data {
public:
U *GetLocalStorage() {
return reinterpret_cast<U *>(_local);
}
const U *GetLocalStorage() const {
return reinterpret_cast<const U *>(_local);
}
U *GetRemoteStorage() {
return _remote;
}
const U *GetRemoteStorage() const {
return _remote;
}
void SetRemoteStorage(U *p) {
_remote = p;
}
private:
alignas(U) char _local[sizeof(U)*M];
U* _remote;
};
// For N == 0 the _Data class has been specialized to elide the local
// storage completely. This way we don't have to rely on compiler-specific
// support for 0-sized arrays.
template < typename U >
union _Data<U, 0> {
public:
U *GetLocalStorage() {
// XXX: Could assert here. Introduce dependency on tf/diagnostic.h?
return nullptr;
}
const U *GetLocalStorage() const {
// XXX: Could assert here. Introduce dependency on tf/diagnostic.h?
return nullptr;
}
U *GetRemoteStorage() {
return _remote;
}
const U *GetRemoteStorage() const {
return _remote;
}
void SetRemoteStorage(U *p) {
_remote = p;
}
private:
U* _remote;
};
};
////////////////////////////////////////////////////////////////////////////////
///
/// \class TfSmallVector
///
/// This is a small-vector class with local storage optimization, the local
/// storage can be specified via a template parameter, and expresses the
/// number of entries the container can store locally.
///
/// In addition to the local storage optimization, this vector is also
/// optimized for storing a smaller number of entries on the heap: It features
/// a reduced memory footprint (minimum 16 bytes) by limiting max_size() to
/// 2^32, which should still be more than enough for most use cases where a
/// small-vector is advantageous.
///
/// TfSmallVector mimics the std::vector API, and can thus be easily used as a
/// drop-in replacement where appropriate. Note, however, that not all the
/// methods on std::vector are implemented here, and that TfSmallVector may
/// have methods in addition to those that you would find on std::vector.
///
/// Note that a TfSmallVector that has grown beyond its local storage, will
/// NOT move its entries back into the local storage once it shrinks back to N.
///
template < typename T, uint32_t N >
class TfSmallVector
: public TfSmallVectorBase
{
public:
/// XXX: Functionality currently missing, and which we would like to add as
/// needed:
/// - emplace
/// - shrink_to_fit
/// - shrink_to_local / shrink_to_internal (or similar, free standing
/// function)
/// \name Relevant Typedefs.
/// @{
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
/// }@
/// \name Iterator Support.
/// @{
using iterator = T*;
using const_iterator = const T*;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
/// }@
/// Default constructor.
///
TfSmallVector() : _size(0), _capacity(N) {}
/// Construct a vector holding \p n value-initialized elements.
///
explicit TfSmallVector(size_type n) :
_capacity(N) {
_InitStorage(n);
value_type *d = data();
for (size_type i = 0; i < n; ++i) {
new (d + i) value_type();
}
}
/// Construct a vector holding \p n copies of \p v.
///
TfSmallVector(size_type n, const value_type &v) :
_capacity(N) {
_InitStorage(n);
std::uninitialized_fill_n(data(), n, v);
}
/// Construct a vector holding \p n default-initialized elements.
///
enum DefaultInitTag { DefaultInit };
TfSmallVector(size_type n, DefaultInitTag) :
_capacity(N) {
_InitStorage(n);
value_type *d = data();
for (size_type i = 0; i < n; ++i) {
new (d + i) value_type;
}
}
/// Copy constructor.
///
TfSmallVector(const TfSmallVector &rhs) : _capacity(N) {
_InitStorage(rhs.size());
std::uninitialized_copy(rhs.begin(), rhs.end(), begin());
}
/// Move constructor.
///
TfSmallVector(TfSmallVector &&rhs) : _size(0), _capacity(N) {
// If rhs can not be stored locally, take rhs's remote storage and
// reset rhs to empty.
if (rhs.size() > N) {
_data.SetRemoteStorage(rhs._data.GetRemoteStorage());
std::swap(_capacity, rhs._capacity);
}
// If rhs is stored locally, it's faster to simply move the entries
// into this vector's storage, destruct the entries at rhs, and swap
// sizes. Note that capacities will be the same in this case, so no
// need to swap those.
else {
_UninitializedMove(rhs.begin(), rhs.end(), begin());
rhs._Destruct();
}
std::swap(_size, rhs._size);
}
/// Construct a new vector from initializer list
TfSmallVector(std::initializer_list<T> values)
: TfSmallVector(values.begin(), values.end()) {
}
template<typename _ForwardIterator>
using _EnableIfForwardIterator =
typename std::enable_if<
std::is_convertible<
typename std::iterator_traits<
_ForwardIterator>::iterator_category,
std::forward_iterator_tag
>::value
>::type;
/// Creates a new vector containing copies of the data between
/// \p first and \p last.
template<typename ForwardIterator,
typename = _EnableIfForwardIterator<ForwardIterator>>
TfSmallVector(ForwardIterator first, ForwardIterator last) : _capacity(N)
{
_InitStorage(std::distance(first, last));
std::uninitialized_copy(first, last, begin());
}
/// Destructor.
///
~TfSmallVector() {
_Destruct();
_FreeStorage();
}
/// Assignment operator.
///
TfSmallVector &operator=(const TfSmallVector &rhs) {
if (this != &rhs) {
assign(rhs.begin(), rhs.end());
}
return *this;
}
/// Move assignment operator.
///
TfSmallVector &operator=(TfSmallVector &&rhs) {
if (this != &rhs) {
swap(rhs);
}
return *this;
}
/// Replace existing contents with the contents of \p ilist.
///
TfSmallVector &operator=(std::initializer_list<T> ilist) {
assign(ilist.begin(), ilist.end());
return *this;
}
/// Swap two vector instances.
///
void swap(TfSmallVector &rhs) {
// Both this vector and rhs are stored locally.
if (_IsLocal() && rhs._IsLocal()) {
TfSmallVector *smaller = size() < rhs.size() ? this : &rhs;
TfSmallVector *larger = size() < rhs.size() ? &rhs : this;
// Swap all the entries up to the size of the smaller vector.
std::swap_ranges(smaller->begin(), smaller->end(), larger->begin());
// Move the tail end of the entries, and destruct them at the
// source vector.
for (size_type i = smaller->size(); i < larger->size(); ++i) {
_MoveConstruct(smaller->data() + i, &(*larger)[i]);
(*larger)[i].~value_type();
}
// Swap sizes. Capacities are already equal in this case.
std::swap(smaller->_size, larger->_size);
}
// Both this vector and rhs are stored remotely. Simply swap the
// pointers, as well as size and capacity.
else if (!_IsLocal() && !rhs._IsLocal()) {
value_type *tmp = _data.GetRemoteStorage();
_data.SetRemoteStorage(rhs._data.GetRemoteStorage());
rhs._data.SetRemoteStorage(tmp);
std::swap(_size, rhs._size);
std::swap(_capacity, rhs._capacity);
}
// Either this vector or rhs is stored remotely, whereas the other
// one is stored locally.
else {
TfSmallVector *remote = _IsLocal() ? &rhs : this;
TfSmallVector *local = _IsLocal() ? this : &rhs;
// Get a pointer to the remote storage. We'll be overwriting the
// pointer value below, so gotta retain it first.
value_type *remoteStorage = remote->_GetStorage();
// Move all the entries from the vector with the local storage, to
// the other vector's local storage. This will overwrite the pointer
// to the other vectors remote storage. Note that we will have to
// also destruct the elements at the source's local storage. The
// source will become the one with the remote storage, so those
// entries will be essentially freed.
for (size_type i = 0; i < local->size(); ++i) {
_MoveConstruct(
remote->_data.GetLocalStorage() + i, &(*local)[i]);
(*local)[i].~value_type();
}
// Swap the remote storage into the vector which previously had the
// local storage. It's been properly cleaned up now.
local->_data.SetRemoteStorage(remoteStorage);
// Swap sizes and capacities. Easy peasy.
std::swap(remote->_size, local->_size);
std::swap(remote->_capacity, local->_capacity);
}
}
/// Insert an rvalue-reference entry at the given iterator position.
///
iterator insert(const_iterator it, value_type &&v) {
return _Insert(it, std::move(v));
}
/// Insert an entry at the given iterator.
///
iterator insert(const_iterator it, const value_type &v) {
return _Insert(it, v);
}
/// Erase an entry at the given iterator.
///
iterator erase(const_iterator it) {
return erase(it, it + 1);
}
/// Erase entries between [ \p first, \p last ) from the vector.
///
iterator erase(const_iterator it, const_iterator last) {
value_type *p = const_cast<value_type *>(&*it);
value_type *q = const_cast<value_type *>(&*last);
// If we're not removing anything, bail out.
if (p == q) {
return iterator(p);
}
const size_type num = std::distance(p, q);
// Move entries starting at last, down a few slots to starting a it.
value_type *e = data() + size();
std::move(q, e, p);
// Destruct all the freed up slots at the end of the vector.
for (value_type *i = (e - num); i != e; ++i) {
i->~value_type();
}
// Bump down the size.
_size -= num;
// Return an iterator to the next entry.
return iterator(p);
}
/// Reserve storage for \p newCapacity entries.
///
void reserve(size_type newCapacity) {
// Only reserve storage if the new capacity would grow past the local
// storage, or the currently allocated storage. We'll grow to
// accommodate exactly newCapacity entries.
if (newCapacity > capacity()) {
_GrowStorage(newCapacity);
}
}
/// Resize the vector to \p newSize and insert copies of \v.
///
void resize(size_type newSize, const value_type &v = value_type()) {
// If the new size is smaller than the current size, let go of some
// entries at the tail.
if (newSize < size()) {
erase(const_iterator(data() + newSize),
const_iterator(data() + size()));
}
// Otherwise, lets grow and fill: Reserve some storage, fill the tail
// end with copies of v, and update the new size.
else if (newSize > size()) {
reserve(newSize);
std::uninitialized_fill(data() + size(), data() + newSize, v);
_size = newSize;
}
}
/// Clear the entries in the vector. Does not let go of the underpinning
/// storage.
///
void clear() {
_Destruct();
_size = 0;
}
/// Clears any previously held entries, and copies entries between
/// [ \p first, \p last ) to this vector.
///
template<typename ForwardIterator,
typename = _EnableIfForwardIterator<ForwardIterator>>
void assign(ForwardIterator first, ForwardIterator last) {
clear();
const size_type newSize = std::distance(first, last);
reserve(newSize);
std::uninitialized_copy(first, last, begin());
_size = newSize;
}
/// Replace existing contents with the contents of \p ilist.
///
void assign(std::initializer_list<T> ilist) {
assign(ilist.begin(), ilist.end());
}
/// Emplace an entry at the back of the vector.
///
template < typename... Args >
void emplace_back(Args&&... args) {
if (size() == capacity()) {
_GrowStorage(_NextCapacity());
}
new (data() + size()) value_type(std::forward<Args>(args)...);
_size += 1;
}
/// Copy an entry to the back of the vector,
///
void push_back(const value_type &v) {
emplace_back(v);
}
/// Move an entry to the back of the vector.
///
void push_back(value_type &&v) {
emplace_back(std::move(v));
}
/// Copy the range denoted by [\p first, \p last) into this vector
/// before \p pos.
///
template <typename ForwardIterator>
void insert(iterator pos, ForwardIterator first, ForwardIterator last)
{
static_assert(
std::is_convertible<
typename std::iterator_traits<ForwardIterator>::iterator_category,
std::forward_iterator_tag>::value,
"Input Iterators not supported.");
// Check for the insert-at-end special case as the very first thing so
// that we give the compiler the best possible opportunity to
// eliminate the general case code.
const bool insertAtEnd = pos == end();
const long numNewElems = std::distance(first, last);
const size_type neededCapacity = size() + numNewElems;
const size_type nextCapacity =
std::max(_NextCapacity(), neededCapacity);
// Insertions at the end would be handled correctly by the code below
// without this special case. However, insert(end(), f, l) is an
// extremely common operation so we provide this fast path both to
// avoid unneeded work and to make it easier for the compiler to
// eliminate dead code when pos == end().
if (insertAtEnd) {
// The reallocation here is not a simple reserve. We want to grow
// the storage only when there are too many new elements but the
// desired size is based on the growth factor.
if (neededCapacity > capacity()) {
_GrowStorage(nextCapacity);
}
std::uninitialized_copy(first, last, end());
_size += numNewElems;
return;
}
if (neededCapacity > capacity()) {
// Because we need to realloc, we can do the insertion by copying
// each range, [begin(), pos), [first, last), [pos, end()), into
// the new storage.
const size_type posI = std::distance(begin(), pos);
value_type *newStorage = _Allocate(nextCapacity);
iterator newPrefixBegin = iterator(newStorage);
iterator newPos = newPrefixBegin + posI;
iterator newSuffixBegin = newPos + numNewElems;
_UninitializedMove(begin(), pos, newPrefixBegin);
std::uninitialized_copy(first, last, newPos);
_UninitializedMove(pos, end(), newSuffixBegin);
// Destroy old data and set up this new buffer.
_Destruct();
_FreeStorage();
_data.SetRemoteStorage(newStorage);
_capacity = nextCapacity;
}
else {
// Insert in-place requires handling four ranges.
//
// For both the range-to-move [pos, end()) and the range-to-insert
// [first, last), there are two subranges: the subrange to copy
// and the subrange to uinitialized_copy. Note that only three of
// these ranges may be non-empty: either there is a non-empty
// prefix of [pos, end()) that needs to be copied over existing
// elements or there is a non-empty suffix of [first, last) that
// needs to be placed in uninitialized storage.
const long numMoveElems = std::distance(pos, end());
const long numUninitMoves = std::min(numNewElems, numMoveElems);
const long numInitMoves = numMoveElems - numUninitMoves;
const long numUninitNews = numNewElems - numUninitMoves;
const long numInitNews = numNewElems - numUninitNews;
// Move our existing elements out of the way of new elements.
iterator umSrc = pos + numInitMoves;
iterator umDst = end() + numUninitNews;
_UninitializedMove(umSrc, end(), umDst);
std::copy_backward(pos, umSrc, umDst);
// Copy new elements into place.
for (long i=0; i<numInitNews; ++i, ++first, ++pos) {
*pos = *first;
}
std::uninitialized_copy(first, last, end());
}
_size += numNewElems;
}
/// Insert elements from \p ilist starting at position \p pos.
///
void insert(iterator pos, std::initializer_list<T> ilist) {
insert(pos, ilist.begin(), ilist.end());
}
/// Remove the entry at the back of the vector.
///
void pop_back() {
back().~value_type();
_size -= 1;
}
/// Returns the current size of the vector.
///
size_type size() const {
return _size;
}
/// Returns the maximum size of this vector.
///
static constexpr size_type max_size() {
return std::numeric_limits<size_type>::max();
}
/// Returns \c true if this vector is empty.
///
bool empty() const {
return size() == 0;
}
/// Returns the current capacity of this vector. Note that if the returned
/// value is <= N, it does NOT mean the storage is local. A vector that has
/// previously grown beyond its local storage, will not move entries back to
/// the local storage once it shrinks to N.
///
size_type capacity() const {
return _capacity;
}
/// Returns the local storage capacity. The vector uses its local storage
/// if capacity() <= internal_capacity().
/// This method mimics the boost::container::small_vector interface.
///
static constexpr size_type internal_capacity() {
return N;
}
/// \name Returns an iterator to the beginning of the vector.
/// @{
iterator begin() {
return iterator(_GetStorage());
}
const_iterator begin() const {
return const_iterator(_GetStorage());
}
const_iterator cbegin() const {
return begin();
}
/// @}
/// \name Returns an iterator to the end of the vector.
/// @{
iterator end() {
return iterator(_GetStorage() + size());
}
const_iterator end() const {
return const_iterator(_GetStorage() + size());
}
const_iterator cend() const {
return end();
}
/// @}
/// \name Returns a reverse iterator to the beginning of the vector.
/// @{
reverse_iterator rbegin() {
return reverse_iterator(end());
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const {
return rbegin();
}
/// @}
/// \name Returns a reverse iterator to the end of the vector.
/// @{
reverse_iterator rend() {
return reverse_iterator(begin());
}
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const {
return rend();
}
/// @}
/// Returns the first element in the vector.
///
reference front() {
return *begin();
}
/// Returns the first element in the vector.
///
const_reference front() const {
return *begin();
}
/// Returns the last element in the vector.
///
reference back() {
return *(data() + size() - 1);
}
/// Returns the last elements in the vector.
///
const_reference back() const {
return *(data() + size() - 1);
}
/// Access the specified element.
///
reference operator[](size_type i) {
return *(data() + i);
}
/// Access the specified element.
///
const_reference operator[](size_type i) const {
return *(data() + i);
}
/// Direct access to the underlying array.
///
value_type *data() {
return _GetStorage();
}
/// Direct access to the underlying array.
///
const value_type *data() const {
return _GetStorage();
}
/// Lexicographically compares the elements in the vectors for equality.
///
bool operator==(const TfSmallVector &rhs) const {
return size() == rhs.size() && std::equal(begin(), end(), rhs.begin());
}
/// Lexicographically compares the elements in the vectors for inequality.
///
bool operator!=(const TfSmallVector &rhs) const {
return !operator==(rhs);
}
private:
// Returns true if the local storage is used.
bool _IsLocal() const {
return _capacity <= N;
}
// Return a pointer to the storage, which is either local or remote
// depending on the current capacity.
value_type *_GetStorage() {
return _IsLocal() ? _data.GetLocalStorage() : _data.GetRemoteStorage();
}
// Return a const pointer to the storage, which is either local or remote
// depending on the current capacity.
const value_type *_GetStorage() const {
return _IsLocal() ? _data.GetLocalStorage() : _data.GetRemoteStorage();
}
// Free the remotely allocated storage.
void _FreeStorage() {
if (!_IsLocal()) {
free(_data.GetRemoteStorage());
}
}
// Destructs all the elements stored in this vector.
void _Destruct() {
value_type *b = data();
value_type *e = b + size();
for (value_type *p = b; p != e; ++p) {
p->~value_type();
}
}
// Allocate a buffer on the heap.
static value_type *_Allocate(size_type size) {
return static_cast<value_type *>(malloc(sizeof(value_type) * size));
}
// Initialize the vector with new storage, updating the capacity and size.
void _InitStorage(size_type size) {
if (size > capacity()) {
_data.SetRemoteStorage(_Allocate(size));
_capacity = size;
}
_size = size;
}
// Grow the storage to be able to accommodate newCapacity entries. This
// always allocates remotes storage.
void _GrowStorage(const size_type newCapacity) {
value_type *newStorage = _Allocate(newCapacity);
_UninitializedMove(begin(), end(), iterator(newStorage));
_Destruct();
_FreeStorage();
_data.SetRemoteStorage(newStorage);
_capacity = newCapacity;
}
// Returns the next capacity to use for vector growth. The growth factor
// here is 1.5. A constant 1 is added so that we do not have to special
// case initial capacities of 0 and 1.
size_type _NextCapacity() const {
const size_type cap = capacity();
return cap + (cap / 2) + 1;
}
// Insert the value v at iterator it. We use this method that takes a
// universal reference to de-duplicate the logic required for the insert
// overloads, one taking an rvalue reference, and the other one taking a
// const reference. This way, we can take the most optimal code path (
// move, or copy without making redundant copies) based on whether v is
// a rvalue reference or const reference.
template < typename U >
iterator _Insert(const_iterator it, U &&v) {
value_type *newEntry;
// If the iterator points to the end, simply push back.
if (it == end()) {
push_back(std::forward<U>(v));
return end() - 1;
}
// Grow the remote storage, if we need to. This invalidates iterators,
// so special care must be taken in order to return a new, valid
// iterator.
else if (size() == capacity()) {
const size_type newCapacity = _NextCapacity();
value_type *newStorage = _Allocate(newCapacity);
value_type *i = const_cast<value_type *>(&*it);
value_type *curData = data();
newEntry = _UninitializedMove(curData, i, newStorage);
new (newEntry) value_type(std::forward<U>(v));
_UninitializedMove(i, curData + size(), newEntry + 1);
_Destruct();
_FreeStorage();
_data.SetRemoteStorage(newStorage);
_capacity = newCapacity;
}
// Our current capacity is big enough to allow us to simply shift
// elements up one slot and insert v at it.
else {
// Move all the elements after it up by one slot.
newEntry = const_cast<value_type *>(&*it);
value_type *last = const_cast<value_type *>(&back());
new (data() + size()) value_type(std::move(*last));
std::move_backward(newEntry, last, last + 1);
// Move v into the slot at the supplied iterator position.
newEntry->~value_type();
new (newEntry) value_type(std::forward<U>(v));
}
// Bump size and return an iterator to the newly inserted entry.
++_size;
return iterator(newEntry);
}
// The vector storage, which is a union of the local storage and a pointer
// to the heap memory, if allocated.
_Data<value_type, N> _data;
// The current size of the vector, i.e. how many entries it contains.
size_type _size;
// The current capacity of the vector, i.e. how big the currently allocated
// storage space is.
size_type _capacity;
};
////////////////////////////////////////////////////////////////////////////////
template < typename T, uint32_t N >
void swap(TfSmallVector<T, N> &a, TfSmallVector<T, N> &b)
{
a.swap(b);
}
////////////////////////////////////////////////////////////////////////////////
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+257
View File
@@ -0,0 +1,257 @@
//
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_SPAN_H
#define PXR_BASE_TF_SPAN_H
/// \file tf/span.h
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/diagnostic.h"
#include <cstddef>
#include <iterator>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfSpan
/// Represents a range of contiguous elements.
///
/// This simply pairs a pointer with a size, while adding a common
/// array interface.
///
/// A span allows ranges of elements to be referenced in a container-neutral
/// manner. While it is possible to achieve that effect by simply passing around
/// raw pointers, a span has the advantage of carrying around additional size
/// information, both enabling use of common array patterns, as well as
/// providing sufficient information to perform boundary tests.
///
/// A TfSpan is implicitly convertible from common array types,
/// as well as from other spans, but preserves const-ness:
///
/// \code
/// std::vector<int> data;
/// TfSpan<int> span(data); // Okay
///
/// VtIntArray data;
/// TfSpan<int> span = data; // Okay
/// TfSpan<const int> cspan = span; // Okay
///
/// const std::vector<int> data;
/// TfSpan<const int> span = data; // Okay
///
/// const std::vector<int> data;
/// TfSpan<int> span = data; // Error! Discards cv-qualifier.
/// \endcode
///
/// Helper methods TfMakeSpan and TfMakeConstSpan are also provided to enable
/// auto-typing when constructing spans:
/// \code
/// VtIntArray data;
/// auto readOnlySpan = TfMakeConstSpan(data); // TfSpan<const int>
/// auto readWriteSpan = TfMakeSpan(data); // TfSpan<int>
/// \endcode
///
/// Spans do not own the data they reference. It is up to the user of the span
/// to ensure that the underlying data is not destructed while the span is in
/// use.
///
/// This is modelled after std::span (C++20), but does not currently include
/// any specialization for static extents.
///
template <typename T>
class TfSpan
{
public:
using element_type = T;
using value_type = typename std::remove_cv<T>::type;
using pointer = T*;
using reference = T&;
using index_type = std::size_t;
using difference_type = std::ptrdiff_t;
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
TfSpan() noexcept = default;
/// Construct a span over the range of [ptr, ptr+count).
/// In debug builds, a runtime assertion will fail if \p count > 0 and
/// \p ptr is null. The behavior is otherwise undefined for invalid ranges.
TfSpan(pointer ptr, index_type count)
: _data(ptr), _size(count)
{
TF_DEV_AXIOM(count == 0 || ptr);
}
/// Construct a span over the range [first, last).
TfSpan(pointer first, pointer last)
: TfSpan(first, index_type(last-first))
{
TF_DEV_AXIOM(last >= first);
}
/// Construct a span from a container.
/// The resulting span has a range of
/// [cont.data(), cont.data()+cont.size())
template <class Container>
TfSpan(Container& cont,
typename std::enable_if<
!std::is_const<element_type>::value &&
std::is_same<typename Container::value_type, value_type
>::value, Container
>::type* = 0)
: _data(cont.data()), _size(cont.size())
{
TF_DEV_AXIOM(_size == 0 || _data);
}
/// Construct a span from a container.
/// The resulting span has a range of
/// [cont.data(), cont.data()+cont.size())
template <class Container>
TfSpan(const Container& cont,
typename std::enable_if<
std::is_same<typename Container::value_type, value_type
>::value, Container
>::type* = 0)
: _data(cont.data()), _size(cont.size())
{
TF_DEV_AXIOM(_size == 0 || _data);
}
/// Return a pointer to the first element of the span.
pointer data() const noexcept { return _data; }
/// Return the total number of elements in the span.
index_type size() const noexcept { return _size; }
/// Returns true if this span contains no elements, false otherwise.
bool empty() const noexcept { return _size == 0; }
/// Returns a reference to the \p idx'th element of the span.
/// In debug builds, a runtime assertion will fail if \p idx is out of
/// range. The behavior is otherwise undefined if \p idx is out of range.
reference operator[](index_type idx) const {
TF_DEV_AXIOM(idx < _size);
return _data[idx];
}
/// Return a reference to the first element in the span.
reference front() const {
TF_DEV_AXIOM(!empty());
return *begin();
}
/// Return a reference to the last element in the span.
reference back() const {
TF_DEV_AXIOM(!empty());
return *(end() - 1);
}
/// Returns a non-const iterator the start of the span.
iterator begin() const noexcept { return _data; }
/// Returns a cons iterator to the start of the span.
const_iterator cbegin() const noexcept { return _data; }
/// Returns a non-const iterator to the end of the span.
iterator end() const noexcept { return _data + _size; }
/// Returns a const iterator to the end of the span.
const_iterator cend() const noexcept { return _data + _size; }
/// Returns a non-const reverse iterator the start of the span.
reverse_iterator rbegin() const noexcept
{ return reverse_iterator(end()); }
/// Returns a cons reverse iterator to the start of the span.
const_reverse_iterator crbegin() const noexcept
{ return const_reverse_iterator(cend()); }
/// Returns a non-const reverse iterator to the end of the span.
reverse_iterator rend() const noexcept
{ return reverse_iterator(begin()); }
/// Returns a const reverse iterator to the end of the span.
const_reverse_iterator crend() const noexcept
{ return const_reverse_iterator(cbegin()); }
/// Returns a new span referencing a sub-range of this span.
/// If \p count == -1 (or std::dynamic_extent in C++20), the new span
/// has a range of [data()+offset, data()+size()). Otherwise, the new
/// span has range [data()+offset, data()+offset+count).
TfSpan<T> subspan(difference_type offset, difference_type count=-1) const {
TF_DEV_AXIOM(offset >= 0 && (index_type)offset < _size);
if (count == -1) {
return TfSpan<T>(_data + offset, _size - offset);
} else {
TF_DEV_AXIOM(count >= 0);
TF_DEV_AXIOM(((index_type)offset+(index_type)count) <= _size);
return TfSpan<T>(_data + offset, count);
}
}
/// Return a subspan consisting of the first \p count elements of this span.
TfSpan<T> first(size_t count) const {
return subspan(0, count);
}
/// Return a subspan consisting of the last \p count elements of this span.
TfSpan<T> last(size_t count) const {
TF_DEV_AXIOM(_size >= count);
return TfSpan<T>(end() - count, count);
}
private:
pointer _data = nullptr;
index_type _size = 0;
};
/// Helper for constructing a non-const TfSpan from a container.
template <typename Container>
TfSpan<typename Container::value_type>
TfMakeSpan(Container& cont)
{
return TfSpan<typename Container::value_type>(cont);
}
/// Helper for constructing a const TfSpan from a container.
template <typename Container>
TfSpan<const typename Container::value_type>
TfMakeConstSpan(const Container& cont)
{
return TfSpan<const typename Container::value_type>(cont);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_SPAN_H
+78
View File
@@ -0,0 +1,78 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STACK_TRACE_H
#define PXR_BASE_TF_STACK_TRACE_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include <cstdio>
#include <ctime>
#include <iosfwd>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
class TfCallContext;
/// Gets both the C++ and the python stack and returns it as a string.
TF_API std::string TfGetStackTrace();
/// Prints both the C++ and the python stack to the \c file provided
TF_API
void TfPrintStackTrace(FILE *file, const std::string &reason);
/// Prints both the C++ and the python stack to the \a stream provided
TF_API
void TfPrintStackTrace(std::ostream &out, std::string const &reason);
/// Logs both the C++ and the python stack to a file in /var/tmp
/// A message is printed to stderr reporting that a stack trace
/// has been taken and what file it has been written to. If \c
/// logtodb is true, then the stack trace will be added to the
/// stack_trace database table.
TF_API
void TfLogStackTrace(const std::string &reason, bool logtodb=false);
/// Creates a nicely formatted message describing a crash and writes it to a
/// temporary file.
///
/// \p reason is a very short descriptive title for the error (ie, FATAL_ERROR)
/// \p message further describes the crash (ie, Dereferenced an invalid MfHandle)
/// \p additionalInfo is secondary, possibly multi-line, information that should
/// be included in the report.
/// \p callContext describes the location of the crash
/// \p logToDB controls whether the stack will be added to the stack_trace db table.
TF_API
void TfLogCrash(const std::string &reason,
const std::string &message, const std::string &additionalInfo,
TfCallContext const &context, bool logToDB);
/// Returns the application's launch time.
TF_API
time_t TfGetAppLaunchTime();
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+254
View File
@@ -0,0 +1,254 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STACKED_H
#define PXR_BASE_TF_STACKED_H
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/arch/demangle.h"
#include <tbb/enumerable_thread_specific.h>
#include <atomic>
#include <type_traits>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfStackedAccess
///
/// Classes that derive \a TfStacked may befriend TfStackedAccess if they wish
/// to customize aspects \a TfStacked's behavior. See \a TfStacked
/// documentation for more details.
///
class TfStackedAccess {
public:
template <class Derived>
static void InitializeStack() {
return Derived::_InitializeStack();
}
};
// Detail for TfStacked storage types.
template <typename T, bool PerThread>
class Tf_StackedStorageType {
public:
typedef std::vector<T const *> Stack;
private:
/* This is a wrapper around Stack that makes sure we call InitializeStack */
/* once per stack instance. */
class _StackHolder {
public:
_StackHolder() : _initialized(false) { }
Stack &Get() {
if (!_initialized) {
_initialized = true;
TfStackedAccess::InitializeStack<T>();
}
return _stack;
}
private:
Stack _stack;
bool _initialized;
};
struct _PerThreadStackStorage {
tbb::enumerable_thread_specific<_StackHolder> stack;
Stack &Get() {
return stack.local().Get();
}
};
struct _GlobalStackStorage {
_StackHolder stack;
Stack &Get() {
return stack.Get();
}
};
public:
/* Choose the stack storage type based on thea PerThread argument. */
typedef typename std::conditional<
PerThread, _PerThreadStackStorage, _GlobalStackStorage
>::type Type;
};
// Detail for TfStacked storage. This exists so we can specialize it
// with exported storage.
template <typename T, bool PerThread>
struct Tf_ExportedStackedStorage { };
// Detail for TfStacked storage. This is for the case we don't need
// exported storage. This is the default when simply subclassing
// TfStacked without using TF_DEFINE_STACKED.
template <typename T, bool PerThread>
struct Tf_StackedStorage {
typedef typename Tf_StackedStorageType<T, PerThread>::Stack Stack;
typedef typename Tf_StackedStorageType<T, PerThread>::Type Type;
static std::atomic<Type*> value;
};
/// \class TfStacked
///
/// A TfStacked is used where a class needs to keep a stack of the objects
/// currently in existence. This class follows the CRTP and is a base class
/// that is parameterized on its derived classes.
///
/// TfStacked is thread-safe by default and each thread will get its own stack.
/// This behavior may be disabled by passing \a false for the \a PerThread
/// template parameter.
///
/// Derived classes must instantiate the stack themselves by putting
///
/// TF_INSTANTIATE_STACKED(YourStackedClass)
///
/// in a single .cpp file.
///
/// Note that \a Stacked objects that differ only by \a PerThread will not
/// share stacks.
///
template <class Derived, bool PerThread = true,
class Holder = Tf_StackedStorage<Derived, PerThread>>
class TfStacked {
TfStacked(TfStacked const &) = delete;
TfStacked& operator=(TfStacked const &) = delete;
typedef typename Holder::Type _StorageType;
public:
typedef Holder Storage;
typedef typename Storage::Stack Stack;
/// Pushes this stacked object onto the stack.
TfStacked() {
_Push(_AsDerived());
}
/// Pops this stacked object from the stack.
~TfStacked() {
_Pop(_AsDerived());
}
/// Returns the top of the stack. If the stack is empty, returns 0.
/// Derived classes can befriend TfStackedAccess and hide (override)
/// \a _InitializeStack() to pre-populate the stack if desired. This way,
/// a stack can be made never to be empty.
static Derived const *GetStackTop() {
Stack const &stack = GetStack();
return stack.empty() ? 0 : stack.back();
}
/// Returns the element under the top of the stack. If the stack contains
/// only one element, or is empty, returns 0. Derived classes can befriend
/// TfStackedAccess and hide (override) \a _InitializeStack() to
/// pre-populate the stack if desired. This way, a stack can be made never
/// to be empty.
static Derived const *GetStackPrevious() {
Stack const &stack = GetStack();
size_t size = stack.size();
return size <= 1 ? 0 : stack[size-2];
}
/// Returns a const reference to the entire stack.
static Stack const &GetStack() {
return _GetStack();
}
/// Returns true if \a p is the top of the stack.
static bool IsStackTop(Derived const *p) {
return GetStackTop() == p;
}
private:
friend class TfStackedAccess;
// This function may be hidden (overridden) by derived classes to initialize
// (pre-populate) the stack with some items. One way to do this is to
// allocate objects on the heap, never to be freed. By default, no
// initialization is performed.
static void _InitializeStack() {}
// Push p on the stack. Only the constructor should call this.
static void _Push(Derived const *p) {
_GetStack().push_back(p);
}
// Pop p off the stack. Only the destructor should call this.
static void _Pop(Derived const *p) {
// Make sure we pop in reverse order.
if (ARCH_LIKELY(IsStackTop(p))) {
_GetStack().pop_back();
} else {
// CODE_COVERAGE_OFF
TF_FATAL_ERROR("Destroyed %s out of stack order.",
ArchGetDemangled<Derived>().c_str());
// CODE_COVERAGE_ON
}
}
static Stack &_GetStack() {
// Technically unsafe double-checked lock to initialize the stack.
if (ARCH_UNLIKELY(Storage::value.load() == nullptr)) {
// Make a new stack and try to set it.
_StorageType *old = nullptr;
_StorageType *tmp = new _StorageType;
// Attempt to set the stack.
if (!Storage::value.compare_exchange_strong(old, tmp)) {
// Another caller won the race.
delete tmp;
}
}
return Storage::value.load(std::memory_order_relaxed)->Get();
}
Derived *_AsDerived() {
return static_cast<Derived *>(this);
}
Derived const *_AsDerived() const {
return static_cast<Derived const *>(this);
}
};
/// Define the class \p Derived that subclasses from TfStacked.
/// \p IsPerThread selected thread safety and \p eiAPI is used to export
/// the storage for the stack. Use \c TF_INSTANTIATE_DEFINED_STACKED
/// to define the storage.
#define TF_DEFINE_STACKED(Derived, IsPerThread, eiAPI) \
class Derived; \
template <> \
struct Tf_ExportedStackedStorage<Derived, IsPerThread> { \
typedef typename Tf_StackedStorageType<Derived, IsPerThread>::Stack Stack; \
typedef typename Tf_StackedStorageType<Derived, IsPerThread>::Type Type; \
static eiAPI std::atomic<Type*> value; \
}; \
class Derived : \
public TfStacked<Derived, IsPerThread, \
Tf_ExportedStackedStorage<Derived, IsPerThread>>
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_STACKED_H
+205
View File
@@ -0,0 +1,205 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STATIC_DATA_H
#define PXR_BASE_TF_STATIC_DATA_H
/// \file tf/staticData.h
/// \ingroup group_tf_Initialization
#include "pxr/pxr.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/preprocessorUtils.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include <atomic>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfStaticData
/// \ingroup group_tf_Initialization
///
/// Create or return a previously created object instance of global data.
///
/// Any form of global data that requires an constructor (even a default
/// constructor) is unsafe to declare as global data. By global data we mean
/// either a variable defined at file-scope (outside of a function) or a
/// static member of a class. This is because the initialization order of
/// globals is undefined across translation units.
///
/// The only exceptions are constexpr constructors and "plain old data" types
/// such as integral or float/double type and pointers. In contrast, \c
/// std::string requires construction, as do most \c STL types, and most
/// user-defined types as well. Note that static local variables in functions
/// are also safe and are initialized in a thread-safe manner the first time
/// they're encountered.
///
/// One way to handle this problem is to go the singleton route, which can be
/// done using the \c TfSingleton pattern. However, a fair amount of coding is
/// required for this, and at times, something more lightweight is appropriate.
/// For these few cases, the following construct may be employed:
///
/// \code
/// // source file:
///
/// #include <set>
/// #include <string>
///
/// static TfStaticData<set<string> > Xyz_nameSet;
///
/// void XyzAddName(string name) {
/// Xyz_nameSet->insert(name);
///
/// ...
/// }
/// \endcode
///
/// One uses a \c TfStaticData<T> as if it were a pointer; upon first use
/// however, the item is initialized to point at a new object of type \c T. Note
/// that the type \c T must have a default constructor; that is, the newly
/// created object is created by calling \c "new T".
///
/// If you have no need to access the data, but need to make sure it has been
/// initialized (for example, if the type's constructor will have some effect
/// that you need to be sure has happened), you can call the Touch() method.
///
/// Warning: the \c TfStaticData construct relies upon zero-initialization of
/// global data: therefore, you can only use this structure for static data
/// member of classes or variables declare at file-scope. Do \e not declare
/// a \c TfStaticData object as a local variable, as a member of a class or
/// structure, or as a function parameter. Use normal static local variable
/// initialization inside a function.
///
/// One can either call member functions using the "->" operator, or use the
/// dereference "*" operator:
///
/// \code
/// TfStaticData<string> Xyz_curName;
///
/// void Xyz_SetLastName(string s) {
/// *Xyz_curName = s;
///
/// vector<string> v;
/// v.push_back(*Xyz_curName);
/// }
/// \endcode
///
template <class T>
struct Tf_StaticDataDefaultFactory {
static T *New() { return new T; }
};
template <class T, class Factory = Tf_StaticDataDefaultFactory<T> >
class TfStaticData {
public:
/// Return a pointer to the underlying data object. It is created and
/// initialized if necessary.
inline T* operator-> () const { return Get(); }
/// Member lookup. The underlying data object is created and initialized
/// if necessary.
inline T& operator* () const { return *Get(); }
/// Return a pointer to the underlying object, creating and initializing
/// it if necessary.
inline T* Get() const {
T *p = _data;
return ARCH_LIKELY(p) ? p : _TryToCreateData();
}
/// Return true if the underlying data object is created and initialized.
/// Return false otherwise.
inline bool IsInitialized() const { return _data.load() != nullptr; }
private:
T *_TryToCreateData() const {
// Allocate an instance.
T *tmp = Factory::New();
// Try to atomically set the pointer from null to tmp.
T *n = nullptr;
if (ARCH_LIKELY(_data.compare_exchange_strong(n, tmp)))
return tmp;
// Another thread won the initialization race.
delete tmp;
return _data;
}
mutable std::atomic<T *> _data;
};
/// Create a static data object, initializing it with code.
///
/// The macro takes two arguments. The first is the type of static data, the
/// second is the name of the variable. The block of code following the macro
/// will be invoked to initialize the static data when it is first used. See
/// example usage:
///
/// \code
/// TF_MAKE_STATIC_DATA(string, myString) { *myString = "hello!"; }
///
/// TF_MAKE_STATIC_DATA(vector<string>, someNames) {
/// someNames->push_back("hello");
/// someNames->push_back("static");
/// someNames->push_back("world");
/// }
///
/// TF_MAKE_STATIC_DATA((map<int, int>), intMap) {
/// (*intMap)[1] = 11;
/// (*intMap)[2] = 22;
/// }
/// \endcode
///
/// If the type uses commas to separate template arguments you need to enclose
/// the type in parentheses as shown in the last example.
///
/// Note that this macro may only be used at namespace scope (not function
/// scope).
///
/// Also note that in multithreaded code, it is possible for the provided code
/// to be invoked more than once (with different target objects) for the same
/// static data instance. This is fine as long as the initialization code does
/// not have side-effects, but you should be aware of it.
///
/// \hideinitializer
#define TF_MAKE_STATIC_DATA(Type, Name) \
static void TF_PP_CAT(Name,_Tf_StaticDataFactoryImpl)( \
TF_PP_EAT_PARENS(Type) *); \
namespace { \
struct TF_PP_CAT(Name,_Tf_StaticDataFactory) { \
static TF_PP_EAT_PARENS(Type) *New() { \
auto *p = new TF_PP_EAT_PARENS(Type); \
TF_PP_CAT(Name,_Tf_StaticDataFactoryImpl)(p); \
return p; \
} \
}; \
} \
static TfStaticData< \
TF_PP_EAT_PARENS(Type), TF_PP_CAT(Name,_Tf_StaticDataFactory)> Name; \
static void TF_PP_CAT(Name,_Tf_StaticDataFactoryImpl)( \
TF_PP_EAT_PARENS(Type) *Name)
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+298
View File
@@ -0,0 +1,298 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
//todo: cleanup: TF_DEFINE_PRIVATE_TOKENS, should use the public versions
//todo: cleanup: document each macro extensivly
//todo: cleanup: order macros, so that it is easier to see the structure
//todo: simply syntax, we should get rid of braces for each array element and
// each element
#ifndef PXR_BASE_TF_STATIC_TOKENS_H
#define PXR_BASE_TF_STATIC_TOKENS_H
/// \file tf/staticTokens.h
///
/// This file defines some macros that are useful for declaring and using
/// static TfTokens. Typically, using static TfTokens is either cumbersome,
/// unsafe, or slow. These macros aim to solve many of the common problems.
///
/// The following is an example of how they can be used.
///
/// In header file:
///
/// \code
/// #define MF_TOKENS \. <--- please ignore '.'
/// (transform) \.
/// (moves) \.
///
/// // Syntax when string name differs from symbol.
/// ((foo, "bar"))
///
/// // Syntax when defining an array of tokens. Note that the tokens can
/// // be used either with amountTs[i] or directly as tx, ty, tz.
/// ((amountTs, ( (tx) (ty) (tz) )))
///
/// TF_DECLARE_PUBLIC_TOKENS(MfTokens, MF_TOKENS);
/// \endcode
///
/// In cpp file:
///
/// \code
/// TF_DEFINE_PUBLIC_TOKENS(MfTokens, MF_TOKENS);
/// \endcode
///
/// Access the token by using the key as though it were a pointer, like this:
///
/// \code
/// MfTokens->transform;
/// \endcode
///
/// An additional member, allTokens, is a std::vector<TfToken> populated
/// with all of the generated token members.
///
/// There are PUBLIC and PRIVATE versions of the macros. The PRIVATE ones are
/// intended to be used when the tokens will only be used in a single .cpp
/// file, in which case they can be made file static. In the case of the
/// PRIVATE, you only need to use the DEFINE macro.
#include "pxr/pxr.h"
#include "pxr/base/tf/preprocessorUtils.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/token.h"
#include <vector>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/control/expr_iif.hpp>
#include <boost/preprocessor/logical/and.hpp>
#include <boost/preprocessor/logical/not.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/seq/filter.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/seq/push_back.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
PXR_NAMESPACE_OPEN_SCOPE
// TF_DECLARE_PUBLIC_TOKENS use these macros to handle two or three arguments.
// The three argument version takes an export/import macro (e.g. TF_API)
// while the two argument version does not export the tokens.
#define _TF_DECLARE_PUBLIC_TOKENS3(key, eiapi, seq) \
_TF_DECLARE_TOKENS3(key, seq, eiapi) \
extern eiapi TfStaticData<_TF_TOKENS_STRUCT_NAME(key)> key
#define _TF_DECLARE_PUBLIC_TOKENS2(key, seq) \
_TF_DECLARE_TOKENS2(key, seq) \
extern TfStaticData<_TF_TOKENS_STRUCT_NAME(key)> key
#define _TF_DECLARE_PUBLIC_TOKENS(N) _TF_DECLARE_PUBLIC_TOKENS##N
#define _TF_DECLARE_PUBLIC_TOKENS_EVAL(N) _TF_DECLARE_PUBLIC_TOKENS(N)
#define _TF_DECLARE_PUBLIC_TOKENS_EXPAND(x) x
/// Macro to define public tokens. This declares a list of tokens that can be
/// used globally. Use in conjunction with TF_DEFINE_PUBLIC_TOKENS.
/// \hideinitializer
#define TF_DECLARE_PUBLIC_TOKENS(...) _TF_DECLARE_PUBLIC_TOKENS_EXPAND( _TF_DECLARE_PUBLIC_TOKENS_EVAL(_TF_DECLARE_PUBLIC_TOKENS_EXPAND( TF_NUM_ARGS(__VA_ARGS__) ))(__VA_ARGS__) )
/// Macro to define public tokens. Use in conjunction with
/// TF_DECLARE_PUBLIC_TOKENS.
/// \hideinitializer
#define TF_DEFINE_PUBLIC_TOKENS(key, seq) \
_TF_DEFINE_TOKENS(key, seq) \
TfStaticData<_TF_TOKENS_STRUCT_NAME(key)> key
/// Macro to define private tokens.
/// \hideinitializer
#define TF_DEFINE_PRIVATE_TOKENS(key, seq) \
namespace { \
struct _TF_TOKENS_STRUCT_NAME_PRIVATE(key) { \
_TF_TOKENS_STRUCT_NAME_PRIVATE(key)() : \
_TF_TOKENS_INITIALIZE_SEQ( \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_NOT_ARRAY, ~, seq) \
_TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq)) \
{ \
_TF_TOKENS_ASSIGN_ARRAY_SEQ( \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_ARRAY, ~, seq)) \
_TF_TOKENS_BUILD_ALLTOKENS_VECTOR( \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_NOT_ARRAY, ~, seq) \
_TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq)) \
} \
_TF_TOKENS_DECLARE_MEMBERS(seq) \
}; \
} \
static TfStaticData<_TF_TOKENS_STRUCT_NAME_PRIVATE(key)> key
///////////////////////////////////////////////////////////////////////////////
// Private Macros
// Private macro to generate struct name from key.
//
// Note that this needs to be a unique struct name for each translation unit.
//
#define _TF_TOKENS_STRUCT_NAME_PRIVATE(key) \
BOOST_PP_CAT(key, _PrivateStaticTokenType)
// Private macro to generate struct name from key. This version is used
// by the public token declarations, and so key must be unique for the entire
// namespace.
//
#define _TF_TOKENS_STRUCT_NAME(key) \
BOOST_PP_CAT(key, _StaticTokenType)
///////////////////////////////////////////////////////////////////////////////
// Declaration Macros
// Private macro used to generate TfToken member variables. elem can either
// be a tuple on the form (name, value) or just a name.
//
#define _TF_TOKENS_DECLARE_MEMBER(r, data, elem) \
TfToken BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
BOOST_PP_TUPLE_ELEM(2, 0, elem), elem) \
BOOST_PP_EXPR_IIF(TF_PP_IS_TUPLE(BOOST_PP_TUPLE_ELEM(2, 1, elem)), \
[BOOST_PP_SEQ_SIZE(BOOST_PP_TUPLE_ELEM(1, 0, \
BOOST_PP_TUPLE_ELEM(2, 1, elem)))]);
// Private macro used to declare the list of members as TfTokens
//
#define _TF_TOKENS_DECLARE_MEMBERS(seq) \
BOOST_PP_SEQ_FOR_EACH(_TF_TOKENS_DECLARE_MEMBER, ~, \
seq _TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq)) \
std::vector<TfToken> allTokens;
// Private macro that expands all array elements to make them members
// of the sequence.
//
#define _TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq) \
BOOST_PP_SEQ_FOR_EACH(_TF_TOKENS_APPEND_ARRAY_ELEMENTS, \
~, \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_ARRAY, ~, seq)) \
// Private macro used to generate a struct of TfTokens.
//
#define _TF_DECLARE_TOKENS3(key, seq, eiapi) \
struct _TF_TOKENS_STRUCT_NAME(key) { \
eiapi _TF_TOKENS_STRUCT_NAME(key)(); \
eiapi ~_TF_TOKENS_STRUCT_NAME(key)(); \
_TF_TOKENS_DECLARE_MEMBERS(seq) \
};
#define _TF_DECLARE_TOKENS2(key, seq) \
struct _TF_TOKENS_STRUCT_NAME(key) { \
_TF_TOKENS_STRUCT_NAME(key)(); \
~_TF_TOKENS_STRUCT_NAME(key)(); \
_TF_TOKENS_DECLARE_MEMBERS(seq) \
};
///////////////////////////////////////////////////////////////////////////////
// Definition Macros
// Private macros to define members in the tokens struct.
//
#define _TF_TOKENS_DEFINE_MEMBER(r, data, i, elem) \
BOOST_PP_COMMA_IF(i) \
BOOST_PP_TUPLE_ELEM(1, 0, BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
(_TF_TOKENS_INITIALIZE_MEMBER_TUPLE(elem)), \
(_TF_TOKENS_INITIALIZE_MEMBER(elem))))
#define _TF_TOKENS_INITIALIZE_MEMBER_TUPLE(elem) \
BOOST_PP_TUPLE_ELEM(2, 0, elem)(BOOST_PP_TUPLE_ELEM(2, 1, elem), \
TfToken::Immortal) \
#define _TF_TOKENS_INITIALIZE_MEMBER(elem) \
elem(TF_PP_STRINGIZE(elem), TfToken::Immortal)
#define _TF_TOKENS_DEFINE_ARRAY_MEMBER(r, data, i, elem) \
data[i] = BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
BOOST_PP_TUPLE_ELEM(2, 0, elem), elem);
// Private macros to append tokens to the allTokens vector.
//
#define _TF_TOKENS_APPEND_MEMBER(r, data, i, elem) \
BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
_TF_TOKENS_APPEND_MEMBER_BODY(~, ~, \
BOOST_PP_TUPLE_ELEM(2, 0, elem)), \
_TF_TOKENS_APPEND_MEMBER_BODY(~, ~, elem))
#define _TF_TOKENS_APPEND_MEMBER_BODY(r, data, elem) \
allTokens.push_back(elem);
#define _TF_TOKENS_BUILD_ALLTOKENS_VECTOR(seq) \
BOOST_PP_SEQ_FOR_EACH_I(_TF_TOKENS_APPEND_MEMBER, ~, seq)
// Private macros to generate the list of initialized members.
//
#define _TF_TOKENS_INITIALIZE_SEQ(seq) \
BOOST_PP_SEQ_FOR_EACH_I(_TF_TOKENS_DEFINE_MEMBER, ~, seq)
#define _TF_TOKENS_ASSIGN_ARRAY_SEQ(seq) \
BOOST_PP_SEQ_FOR_EACH(_TF_TOKENS_DEFINE_ARRAY_MEMBERS, ~, seq)
#define _TF_TOKENS_DEFINE_ARRAY_MEMBERS(r, data, elem) \
BOOST_PP_SEQ_FOR_EACH_I(_TF_TOKENS_DEFINE_ARRAY_MEMBER, \
BOOST_PP_TUPLE_ELEM(2, 0, elem), \
BOOST_PP_TUPLE_ELEM(1, 0, BOOST_PP_TUPLE_ELEM(2, 1, elem)))
// Private predicate macros to be used by SEQ_FILTER that determine if an
// element of a sequence is an array of tokens or not.
//
#define _TF_TOKENS_IS_ARRAY(s, data, elem) \
BOOST_PP_AND(TF_PP_IS_TUPLE(elem), \
TF_PP_IS_TUPLE(BOOST_PP_TUPLE_ELEM(2, 1, elem)))
#define _TF_TOKENS_IS_NOT_ARRAY(s, data, elem) \
BOOST_PP_NOT(_TF_TOKENS_IS_ARRAY(s, data, elem))
// Private macro to append all array elements to a sequence.
//
#define _TF_TOKENS_APPEND_ARRAY_ELEMENTS(r, data, elem) \
BOOST_PP_TUPLE_ELEM(1, 0, BOOST_PP_TUPLE_ELEM(2, 1, elem))
// Private macro to define the struct of tokens.
//
// This works by filtering the incoming seq in two ways. For the body of the
// constructor, only array tokens are passed through (because they can't be
// initialized via initializer lists). The initializer list's items are all
// non-array seq elements _plus_ all array members themshelves. This way,
// array tokens are also accessible without using [] which proved to be
// a neat shortcut.
//
#define _TF_DEFINE_TOKENS(key, seq) \
_TF_TOKENS_STRUCT_NAME(key)::~_TF_TOKENS_STRUCT_NAME(key)() = default; \
_TF_TOKENS_STRUCT_NAME(key)::_TF_TOKENS_STRUCT_NAME(key)() : \
_TF_TOKENS_INITIALIZE_SEQ( \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_NOT_ARRAY, ~, seq) \
_TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq)) \
{ \
_TF_TOKENS_ASSIGN_ARRAY_SEQ( \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_ARRAY, ~, seq)) \
_TF_TOKENS_BUILD_ALLTOKENS_VECTOR( \
BOOST_PP_SEQ_FILTER(_TF_TOKENS_IS_NOT_ARRAY, ~, seq) \
_TF_TOKENS_EXPAND_ARRAY_ELEMENTS(seq)) \
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_STATIC_TOKENS_H
+59
View File
@@ -0,0 +1,59 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STATUS_H
#define PXR_BASE_TF_STATUS_H
#include "pxr/pxr.h"
#include "pxr/base/tf/diagnosticBase.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfStatus
/// \ingroup group_tf_Diagnostic
///
/// Represents an object that contains information about a status message.
///
/// See \ref page_tf_Diagnostic in the C++ API reference for a detailed
/// description of the status message issuing API. For a example of how to
/// post a status message, see \c TF_STATUS(), also in the C++ API reference.
///
/// In the Python API, you can issue a status message with Tf.Status().
///
class TfStatus: public TfDiagnosticBase
{
private:
TfStatus(TfEnum statusCode, char const *statusCodeString,
TfCallContext const &context, const std::string& commentary,
TfDiagnosticInfo info, bool quiet)
: TfDiagnosticBase(statusCode, statusCodeString, context,
commentary, info, quiet)
{ }
friend class TfDiagnosticMgr;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_STATUS_H
+419
View File
@@ -0,0 +1,419 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STL_H
#define PXR_BASE_TF_STL_H
/// \file tf/stl.h
/// \ingroup group_tf_Stl
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/tf.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/hashset.h"
#include "pxr/base/tf/iterator.h"
#include <boost/call_traits.hpp>
#include <algorithm>
#include <iterator>
#include <map>
#include <set>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
// Helper for TfMapLookup(). Uses std::map API to get a value by key.
template <class T>
struct Tf_MapLookupHelper {
typedef T Container;
template <class Key, class Result>
static bool Lookup(Container const& map, Key const &key, Result* valuePtr)
{
typename Container::const_iterator i = map.find(key);
if (i == map.end()) {
return false;
}
else {
*valuePtr = i->second;
return true;
}
}
};
/// Checks if an item exists in a \c map or a \c TfHashMap.
///
/// If \p key exists in \p map, then this function returns \c true and the
/// value indexed by \p key is copied into \p *valuePtr. Otherwise,
/// \p *valuePtr is not modified, and \c false is returned.
///
/// Example:
/// \code
/// TfHashMap<string, int, TfHash> m = ...;
/// int value;
///
///
/// if (TfMapLookup(m, "someKey", &value))
/// printf("Value found: %d\n", value);
/// else
/// printf("Value not found\n");
/// ...
/// \endcode
///
/// \ingroup group_tf_Stl
template <class Container, class Key, class Result>
bool TfMapLookup(Container const &map, Key const &key, Result* valuePtr)
{
return Tf_MapLookupHelper<Container>::Lookup(map, key, valuePtr);
}
/// Checks if an item exists in a \c map or a \c TfHashMap.
///
/// If \p key exists in \p map, then this function returns the value index by
/// \p key. Otherwise, \p defaultValue is returned. Note that the result is
/// returned by value, so this is best used for types that are quick to copy.
///
/// Example:
/// \code
/// TfHashMap<string, int, TfHash> m;
/// m["foo"] = 1;
///
/// int value = TfMapLookupByValue(m, "someKey", -1);
/// TF_AXIOM(value == -1);
///
/// int value = TfMapLookupByValue(m, "foo", -1);
/// TF_AXIOM(value == 1);
///
/// \endcode
///
/// \ingroup group_tf_Stl
template <class Container, class Key, class Result>
const Result TfMapLookupByValue(Container const &map,
Key const &key, const Result &defaultValue)
{
typename Container::const_iterator i = map.find(key);
if (i == map.end()) {
return defaultValue;
} else {
return i->second;
}
}
/// Checks if an item exists in a \c map or \c TfHashMap, without copying it.
///
/// If \p key exists in the \p map, then this function returns a pointer to
/// the value indexed by \p key. Otherwise, NULL is returned.
///
/// Example:
/// \code
/// TfHashMap<string, BigData, TfHash> m = ...;
///
/// if (BigData* bigPtr = TfMapLookupPtr(m, "someKey"))
/// bigPtr->ModifyStuff();
/// else
/// printf("Value not found\n");
/// \endcode
///
/// \ingroup group_tf_Stl
template <class Container, class Key>
typename Container::mapped_type *
TfMapLookupPtr(Container &map, Key const &key)
{
typename Container::iterator i = map.find(key);
return (i != map.end()) ? &(i->second) : NULL;
}
template <class Container, class Key>
typename Container::mapped_type const *
TfMapLookupPtr(Container const &map, Key const &key)
{
typename Container::const_iterator i = map.find(key);
return (i != map.end()) ? &(i->second) : NULL;
}
/// Return an \c std::pair in sorted order.
///
/// This call is a useful helper for maps whose key is an unordered pair of
/// elements. One can either define a new data type such that (a,b) is deemed
/// equivalent to (b,a), or more simply, adopt the convention that a key is
/// always written (a,b) with a < b.
///
/// \ingroup group_tf_Stl
template <typename T>
inline std::pair<T,T>
TfOrderedPair(T a, T b) {
return (a < b) ? std::pair<T,T>(a,b) : std::pair<T,T>(b,a);
}
/// Reset \a obj to be an empty, space-optimized object.
///
/// This can be used to clear c++ containers and reclaim their memory. For
/// instance, std::vector::clear() will not reclaim any memory, even if the
/// vector previously had a large number of elements. Often, this is what you
/// want because the vector is later filled again. But sometimes you want to
/// reclaim the memory, and this function will do that.
///
/// As another example, gcc's hash_map and hash_set do not clear their bucket
/// lists when they themselves are cleared. This can lead to poor performance
/// due to ever-growing bucket lists for hashes that are repeatedly filled,
/// cleared, and filled again. TfReset will avoid this by effectively
/// clearing the bucket list.
///
/// This function requires that the expression T().swap(obj) where obj is of
/// type T& be valid. This is true for many classes, including the standard
/// containers.
template <class T>
inline void TfReset(T &obj) {
T().swap(obj);
}
TF_API size_t Tf_GetEmptyHashMapBucketCount();
/// Specialize for TfHashMap to make minimally sized hashes.
template <class Key, class Value, class Hash, class Equal, class Alloc>
inline void TfReset(TfHashMap<Key, Value, Hash, Equal, Alloc> &hash){
// If the implementation of the hash map allocates buckets when
// constructed asking for zero then only swap a constructed object
// if \p hash has more than that many buckets already, otherwise
// we just clear(). Note that this assumes that the number of
// buckets does not depend on the template parameter types which
// is reasonable.
static size_t emptyCount = Tf_GetEmptyHashMapBucketCount();
if (hash.bucket_count() > emptyCount)
TfHashMap<Key, Value, Hash, Equal, Alloc>(0).swap(hash);
else if (!hash.empty())
hash.clear();
}
TF_API size_t Tf_GetEmptyHashSetBucketCount();
/// Specialize for TfHashSet to make minimally sized hashes.
template <class Value, class Hash, class Equal, class Alloc>
inline void TfReset(TfHashSet<Value, Hash, Equal, Alloc> &hash) {
static size_t emptyCount = Tf_GetEmptyHashSetBucketCount();
// See comment above about issues with TfHashSet(0).
if (hash.bucket_count() > emptyCount)
TfHashSet<Value, Hash, Equal, Alloc>(0).swap(hash);
else if (!hash.empty())
hash.clear();
}
/// An unary function that represents the identity function; it takes a single
/// argument \a arg, and returns \a arg.
///
/// This is similar to the sgi extension std::identity<T>.
template <class T>
inline typename boost::call_traits<T>::param_type
TfIdentity(typename boost::call_traits<T>::param_type arg) {
return arg;
}
/// Produce a sequence consisting of the set difference of [\a first1, \a
/// last1) and [\a first2, \a last2), while maintaining the relative order of
/// the first sequence. No particular order is required for either range, but
/// elements must have a strict weak order provided by operator<.
///
/// If an element appears multiple times in either the first or second
/// sequence, the number of occurrences in the output is the difference
/// between the first sequence and the second (or zero if there are more
/// occurrences in the second sequence). For example, if the first sequence
/// is (1, 3, 3, 1) and the second sequence is (2, 3, 2), the result will be
/// (1, 3, 1).
template <class InputIterator1, class InputIterator2, class OutputIterator>
void
TfOrderedSetDifference(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result)
{
typedef std::multiset<typename InputIterator2::value_type> SetType;
SetType set2(first2, last2);
// Walk [first1, last1). If the element is in set2, skip it, and remove one
// of those elements from set2, otherwise output it.
for (InputIterator1 i = first1; i != last1; ++i) {
typename SetType::iterator j = set2.find(*i);
if (j != set2.end())
set2.erase(j);
else
*result++ = *i;
}
}
/// Produce a sequence consisting of the set difference of [\a first1, \a
/// last1) and [\a first2, \a last2), while maintaining the relative order of
/// the first sequence. No particular order is required for either range, but
/// elements must have a strict weak order provided by operator<.
///
/// If an element appears multiple times in either the first or second
/// sequence, the number of occurrences in the output is the difference
/// between the first sequence and the second (or zero if there are more
/// occurrences in the second sequence). For example, if the first sequence
/// is (1, 3, 3, 1) and the second sequence is (2, 3, 2), the result will be
/// (1, 3, 1).
template <class BackInsertionSequence,
class InputIterator1, class InputIterator2>
BackInsertionSequence
TfOrderedSetDifferenceToContainer(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2)
{
BackInsertionSequence result;
TfOrderedSetDifference(first1, last1, first2, last2,
std::back_inserter(result));
return result;
}
/// Produce a sequence consisting of the set difference of the unique elements
/// in [\a first1, \a last1) and [\a first2, \a last2), while maintaining the
/// relative order of the first sequence. No particular order is required for
/// either range, but elements must have a strict weak order provided by
/// operator<.
///
/// If an element appears multiple times in the first sequence, it appears
/// either zero or one times in the output. It appears zero times if it
/// appears in the second sequence, and one time if it does not. For example,
/// if the first sequence is (1, 3, 3, 1) and the second sequence is (2, 3,
/// 2), the result will be (1).
template <class InputIterator1, class InputIterator2, class OutputIterator>
void
TfOrderedUniquingSetDifference(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result)
{
typedef std::set<typename InputIterator1::value_type> Set1Type;
typedef std::set<typename InputIterator2::value_type> Set2Type;
Set1Type set1;
Set2Type set2(first2, last2);
// Walk [first1, last1). If the element is in set1, skip it. Else insert
// it into set1, and if the element is not in set2, output it.
for (InputIterator1 i = first1; i != last1; ++i)
if (set1.insert(*i).second && !set2.count(*i))
*result++ = *i;
}
/// Produce a sequence consisting of the set difference of the unique elements
/// in [\a first1, \a last1) and [\a first2, \a last2), while maintaining the
/// relative order of the first sequence. No particular order is required for
/// either range, but elements must have a strict weak order provided by
/// operator<.
///
/// If an element appears multiple times in the first sequence, it appears
/// either zero or one times in the output. It appears zero times if it
/// appears in the second sequence, and one time if it does not. For example,
/// if the first sequence is (1, 3, 3, 1) and the second sequence is (2, 3,
/// 2), the result will be (1).
template <class BackInsertionSequence,
class InputIterator1, class InputIterator2>
BackInsertionSequence
TfOrderedUniquingSetDifferenceToContainer(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
BackInsertionSequence result;
TfOrderedUniquingSetDifference(first1, last1, first2, last2,
std::back_inserter(result));
return result;
}
/// A version of binary search that finds the boundary in a partitioned
/// sequence. The Predicate pred should return true for objects on the
/// 'first' side (or left-hand) side of the boundary.
///
/// More precisely, given a range [first, last) and a Predicate pred for which
/// there is exactly one iterator called mid in that range such that pred(x)
/// is true for every x in [first, mid) and false for every x in [mid, last),
/// return mid.
template <class ForwardIterator, class Predicate>
static inline ForwardIterator
TfFindBoundary(ForwardIterator first, ForwardIterator last,
Predicate const &pred)
{
size_t len = std::distance(first, last);
size_t half;
ForwardIterator middle;
while (len > 0) {
half = len >> 1;
middle = first;
std::advance(middle, half);
if (pred(*middle)) {
first = middle;
++first;
len = len - half - 1;
}
else
len = half;
}
return first;
}
/// Function object for retrieving the N'th element of a std::pair
/// or std::tuple. This is similar to std::get<N>, but wrapped up in a
/// function object suitable for use with STL algorithms.
///
/// Example:
/// \code
/// const std::vector<std::pair<int, std::string>> pairs = { ... }
/// std::vector<int> intsOnly(pairs.size());
/// std::transform(pairs.begin(), pairs.end(), intsOnly.begin(), TfGet<0>());
/// \endcode
///
/// \ingroup group_tf_Stl
template <size_t N>
class TfGet
{
public:
template <class PairOrTuple>
using return_type = typename std::tuple_element<N, PairOrTuple>::type;
template <class PairOrTuple>
constexpr return_type<PairOrTuple>& operator()(PairOrTuple& p) const
{
return std::get<N>(p);
}
template <class PairOrTuple>
constexpr const return_type<PairOrTuple>& operator()(
const PairOrTuple& p) const
{
return std::get<N>(p);
}
template <class PairOrTuple>
constexpr return_type<PairOrTuple>&& operator()(PairOrTuple&& p) const
{
return std::get<N>(std::move(p));
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_STL_H
+154
View File
@@ -0,0 +1,154 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STOPWATCH_H
#define PXR_BASE_TF_STOPWATCH_H
/// \file tf/stopwatch.h
/// \ingroup group_tf_Performance
#include "pxr/pxr.h"
#include "pxr/base/arch/timing.h"
#include "pxr/base/tf/api.h"
#include <iosfwd>
PXR_NAMESPACE_OPEN_SCOPE
/// \class TfStopwatch
/// \ingroup group_tf_Performance
///
/// Low-cost, high-resolution timer datatype.
///
/// A \c TfStopwatch can be used to perform very precise timings at runtime,
/// even in very tight loops. The cost of "starting" or "stopping" a
/// \c TfStopwatch is very small: approximately 40 nanoseconds on a 900 Mhz
/// Pentium III Linux box, 300 nanoseconds on a 400 Mhz Sun, and 200
/// nanoseconds on a 250 Mhz SGI.
///
/// Note that this class is not thread-safe: if you need to take timings in a
/// multi-threaded region of a process, let each thread have its own
/// \c TfStopwatch and then combine results using the \c AddFrom() member
/// function.
///
class TfStopwatch
{
public:
/// Record the current time for use by the next \c Stop() call.
///
/// The \c Start() function records the current time. A subsequent call
/// to \c Start() before a call to \c Stop() simply records a later
/// current time, but does not change the accumulated time of the \c
/// TfStopwatch.
inline void Start() {
_startTick = ArchGetTickTime();
}
/// Increases the accumulated time stored in the \c TfStopwatch.
///
/// The \c Stop() function increases the accumulated time by the duration
/// between the current time and the last time recorded by a \c Start()
/// call. A subsequent call to \c Stop() before another call to \c
/// Start() will therefore double-count time and throw off the results.
///
/// A \c TfStopwatch also counts the number of samples it has taken. The
/// "sample count" is simply the number of times that \c Stop() has been
/// called.
inline void Stop() {
_nTicks += ArchGetTickTime() - _startTick;
_sampleCount++;
}
/// Resets the accumulated time and the sample count to zero.
void Reset() {
_nTicks = 0;
_sampleCount = 0;
}
/// Adds the accumulated time and sample count from \c t into the \c
/// TfStopwatch.
///
/// If you have several timers taking measurements, and you wish to
/// combine them together, you can add one timer's results into another;
/// for example, \c t2.AddFrom(t1) will add \c t1 's time and sample count
/// into \c t2.
void AddFrom(const TfStopwatch& t) {
_nTicks += t._nTicks;
_sampleCount += t._sampleCount;
}
/// Return the accumulated time in nanoseconds.
///
/// Note that this number can easily overflow a 32-bit counter, so take
/// care to save the result in an \c int64_t, and not a regular \c int or
/// \c long.
int64_t GetNanoseconds() const {
return ArchTicksToNanoseconds(_nTicks);
}
/// Return the accumulated time in microseconds
///
/// Note that 45 minutes will overflow a 32-bit counter, so take care to
/// save the result in an \c int64_t, and not a regular \c int or \c long.
int64_t GetMicroseconds() const {
return GetNanoseconds() / 1000;
}
/// Return the accumulated time in milliseconds.
int64_t GetMilliseconds() const {
return GetMicroseconds() / 1000;
}
/// Return the current sample count.
///
/// The sample count, which is simply the number of calls to \c Stop()
/// since creation or a call to \c Reset(), is useful for computing
/// average running times of a repeated task.
size_t GetSampleCount() const {
return _sampleCount;
}
/// Return the accumulated time in seconds as a \c double.
double GetSeconds() const {
return ArchTicksToSeconds(_nTicks);
}
private:
uint64_t _nTicks = 0;
uint64_t _startTick = 0;
size_t _sampleCount = 0;
};
/// Output a TfStopwatch, using the format seconds.
///
/// The elapsed time in the stopwatch is output in seconds. Note that the
/// timer need not be stopped.
///
/// \ingroup group_tf_DebuggingOutput
TF_API std::ostream& operator<<(std::ostream& out, const TfStopwatch& s);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_STOPWATCH_H
+703
View File
@@ -0,0 +1,703 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TF_STRING_UTILS_H
#define PXR_BASE_TF_STRING_UTILS_H
/// \file tf/stringUtils.h
/// \ingroup group_tf_String
/// Definitions of basic string utilities in tf.
#include "pxr/pxr.h"
#include "pxr/base/arch/attributes.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/tf/enum.h"
#include <cstdarg>
#include <cstring>
#include <list>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class TfToken;
/// \addtogroup group_tf_String
///@{
/// Returns a string formed by a printf()-like specification.
///
/// \c TfStringPrintf() is a memory-safe way of forming a string using
/// printf()-like formatting. For example,
/// \code
/// string formatMsg(const string& caller, int i, double val[])
/// {
/// return TfStringfPrintf("%s: val[%d] = %g\n", caller.c_str(), i, val[i]);
/// }
/// \endcode
///
/// The function is safe only to the extent that the arguments match the
/// formatting string. In particular, be careful to pass strings themselves
/// into \c TfStringPrintf() as in the above example (i.e. \c caller.c_str()
/// as opposed to just passing \c caller).
///
/// \note \c TfStringPrintf() is just a wrapper for \c ArchStringPrintf().
TF_API
std::string TfStringPrintf(const char *fmt, ...)
#ifndef doxygen
ARCH_PRINTF_FUNCTION(1, 2)
#endif /* doxygen */
;
/// Returns a string formed by a printf()-like specification.
///
/// \c TfVStringPrintf() is equivalent to \c TfStringPrintf() except that it
/// is called with a \c va_list instead of a variable number of arguments. \c
/// TfVStringPrintf() does not call the \c va_end macro. Consequently, the
/// value of \c ap is undefined after the call. A functions that calls \c
/// TfVStringPrintf() should call \c va_end(ap) itself afterwards.
///
/// \note \c TfVStringPrintf() is just a wrapper for \c ArchVStringPrintf().
TF_API
std::string TfVStringPrintf(const std::string& fmt, va_list ap);
/// Bloat-avoidance version of TfVStringPrintf()
TF_API
std::string TfVStringPrintf(const char *fmt, va_list ap)
#ifndef doxygen
ARCH_PRINTF_FUNCTION(1, 0)
#endif /* doxygen */
;
/// Safely create a std::string from a (possibly NULL) char*.
///
/// If \p ptr is NULL, the empty string is safely returned.
inline std::string TfSafeString(const char* ptr) {
return ptr ? std::string(ptr) : std::string();
}
/// Returns the given integer as a string.
inline std::string TfIntToString(int i) {
return TfStringPrintf("%d", i);
}
/// Converts text string to double
///
/// This method converts strings to floating point numbers. It is similar to
/// libc's atof(), but performs the conversion much more quickly.
///
/// It expects somewhat valid input: it will continue parsing the input until
/// it hits an unrecognized character, as described by the regexp below, and
/// at that point will return the results up to that point.
///
/// (-?[0-9]+(\.[0-9]*)?|-?\.[0-9]+)([eE][-+]?[0-9]+)?
///
/// It will not check to see if there is any input at all, or whitespace
/// after the digits. Ie:
/// TfStringToDouble("") == 0.0
/// TfStringToDouble("blah") == 0.0
/// TfStringToDouble("-") == -0.0
/// TfStringToDouble("1.2foo") == 1.2
///
/// \note \c TfStringToDouble is a wrapper around the extern-c TfStringToDouble
TF_API double TfStringToDouble(const std::string& txt);
/// \overload
TF_API double TfStringToDouble(const char *text);
/// Convert a sequence of digits in \p txt to a long int value. Caller is
/// responsible for ensuring that \p txt has content matching:
///
/// \code
/// -?[0-9]+
/// \endcode
///
/// If the digit sequence's value is out of range, set \p *outOfRange to true
/// (if \p outOfRange is not NULL) and return either
/// std::numeric_limits<long>::min() or max(), whichever is closest to the
/// true value.
TF_API
long TfStringToLong(const std::string &txt, bool *outOfRange=NULL);
/// \overload
TF_API
long TfStringToLong(const char *txt, bool *outOfRange=NULL);
/// Convert a sequence of digits in \p txt to an unsigned long value. Caller
/// is responsible for ensuring that \p txt has content matching:
///
/// \code
/// [0-9]+
/// \endcode
///
/// If the digit sequence's value is out of range, set \p *outOfRange to true
/// (if \p outOfRange is not NULL) and return std::numeric_limits<unsigned
/// long>::max().
TF_API
unsigned long TfStringToULong(const std::string &txt, bool *outOfRange=NULL);
/// \overload
TF_API
unsigned long TfStringToULong(const char *txt, bool *outOfRange=NULL);
/// Convert a sequence of digits in \p txt to an int64_t value. Caller must
/// ensure that \p txt has content matching:
///
/// \code
/// -?[0-9]+
/// \endcode
///
/// If the digit sequence's value is out of range, set \p *outOfRange to true
/// (if \p outOfRange is not NULL) and return either
/// std::numeric_limits<int64_t>::min() or max(), whichever is closest to the
/// true value.
TF_API
int64_t TfStringToInt64(const std::string &txt, bool *outOfRange=NULL);
/// \overload
TF_API
int64_t TfStringToInt64(const char *txt, bool *outOfRange=NULL);
/// Convert a sequence of digits in \p txt to a uint64_t value. Caller is
/// responsible for ensuring that \p txt has content matching:
///
/// \code
/// [0-9]+
/// \endcode
///
/// If the digit sequence's value is out of range, set \p *outOfRange to true
/// (if \p outOfRange is not NULL) and return std::numeric_limits<unsigned
/// long>::max().
TF_API
uint64_t TfStringToUInt64(const std::string &txt, bool *outOfRange=NULL);
/// \overload
TF_API
uint64_t TfStringToUInt64(const char *txt, bool *outOfRange=NULL);
inline bool
Tf_StringStartsWithImpl(char const *s, size_t slen,
char const *prefix, size_t prelen)
{
return slen >= prelen && strncmp(s, prefix, prelen) == 0;
}
/// Returns true if \p s starts with \p prefix.
inline bool
TfStringStartsWith(const std::string& s, const char *prefix)
{
return Tf_StringStartsWithImpl(
s.c_str(), s.length(), prefix, strlen(prefix));
}
/// \overload
inline bool
TfStringStartsWith(const std::string& s, const std::string& prefix) {
return TfStringStartsWith(s, prefix.c_str());
}
/// \overload
TF_API
bool TfStringStartsWith(const std::string &s, const TfToken& prefix);
inline bool
Tf_StringEndsWithImpl(char const *s, size_t slen,
char const *suffix, size_t suflen)
{
return slen >= suflen && strcmp(s + (slen - suflen), suffix) == 0;
}
/// Returns true if \p s ends with \p suffix.
inline bool TfStringEndsWith(const std::string& s, const char *suffix)
{
return Tf_StringEndsWithImpl(s.c_str(), s.length(),
suffix, strlen(suffix));
}
/// \overload
inline bool
TfStringEndsWith(const std::string& s, const std::string& suffix)
{
return TfStringEndsWith(s, suffix.c_str());
}
/// \overload
TF_API
bool TfStringEndsWith(const std::string &s, const TfToken& suffix);
/// Returns true if \p s contains \p substring.
// \ingroup group_tf_String
TF_API
bool TfStringContains(const std::string& s, const char *substring);
/// \overload
inline bool
TfStringContains(const std::string &s, const std::string &substring) {
return TfStringContains(s, substring.c_str());
}
/// \overload
TF_API
bool TfStringContains(const std::string &s, const TfToken& substring);
/// Makes all characters in \p source lowercase, and returns the result.
TF_API
std::string TfStringToLower(const std::string& source);
/// Makes all characters in \p source uppercase, and returns the result.
TF_API
std::string TfStringToUpper(const std::string& source);
/// Returns a copy of the \p source string with only its first character
/// capitalized. This emulates the behavior of Python's \c str.capitalize().
TF_API
std::string TfStringCapitalize(const std::string& source);
/// Trims characters (by default, whitespace) from the left.
///
/// Characters from the beginning of \p s are removed until a character not in
/// \p trimChars is found; the result is returned.
TF_API
std::string TfStringTrimLeft(const std::string& s,
const char* trimChars = " \n\t\r");
/// Trims characters (by default, whitespace) from the right.
///
/// Characters at the end of \p s are removed until a character not in \p
/// trimChars is found; the result is returned.
TF_API
std::string TfStringTrimRight(const std::string& s,
const char* trimChars = " \n\t\r");
/// Trims characters (by default, whitespace) from the beginning and end of
/// string.
///
/// Characters at the beginning and end of \p s are removed until a character
/// not in \p trimChars is found; the result is returned.
TF_API
std::string TfStringTrim(const std::string& s,
const char* trimChars = " \n\t\r");
/// Returns the common prefix of the input strings, if any.
///
/// Copies of the input strings are compared. Returns a new string which is
/// the longest prefix common to both input strings. If the strings have no
/// common prefix, an empty string is returned.
TF_API
std::string TfStringGetCommonPrefix(std::string a, std::string b);
/// Returns the suffix of a string
///
/// Returns characters after the final character \c delimiter (default ".") of
/// a string. Thus suffix of "abc.def" is "def" using "." as the delimiter.
/// If the delimiter does not occur, the empty string is returned.
TF_API
std::string TfStringGetSuffix(const std::string& name, char delimiter = '.');
/// Returns everything up to the suffix of a string
///
/// Returns characters before the final character \c delimiter (default ".")
/// of a string. Thus not-suffix of "abc.def" is "abc" using "." as the
/// delimiter. If the delimiter does not occur, the original string is
/// returned.
TF_API
std::string TfStringGetBeforeSuffix(const std::string& name, char delimiter = '.');
/// Returns the base name of a file (final component of the path).
TF_API
std::string TfGetBaseName(const std::string& fileName);
/// Returns the path component of a file (complement of TfGetBaseName()).
///
/// The returned string ends in a '/' (or possibly a '\' on Windows), unless
/// none was found in \c fileName, in which case the empty string is returned.
/// In particular, \c TfGetPathName(s)+TfGetBaseName(s) == \c s for any string
/// \c s (as long as \c s doesn't end with multiple adjacent slashes, which is
/// illegal).
TF_API
std::string TfGetPathName(const std::string& fileName);
/// Replaces all occurrences of string \p from with \p to in \p source
///
/// Returns a new string which is created by copying \p string and replacing
/// every occurrence of \p from with \p to. Correctly handles the case in which
/// \p to contains \p from.
TF_API
std::string TfStringReplace(const std::string& source, const std::string& from,
const std::string& to);
/// Concatenates the strings (\p begin, \p end), with default separator.
///
/// Returns the concatenation of the strings in the range \p begin to \p end,
/// with \p separator (by default, a space) added between each successive pair
/// of strings.
template <class ForwardIterator>
std::string TfStringJoin(
ForwardIterator begin, ForwardIterator end,
const char* separator = " ")
{
if (begin == end)
return std::string();
size_t distance = std::distance(begin, end);
if (distance == 1)
return *begin;
std::string retVal;
size_t sum = 0;
ForwardIterator i = begin;
for (i = begin; i != end; ++i)
sum += i->size();
retVal.reserve(sum + strlen(separator) * (distance - 1));
i = begin;
retVal.append(*i);
while (++i != end) {
retVal.append(separator);
retVal.append(*i);
}
return retVal;
}
/// Concatenates \p strings, with default separator.
///
/// Returns the concatenation of the strings in \p strings, with \p separator
/// (by default, a space) added between each successive pair of strings.
TF_API
std::string TfStringJoin(const std::vector<std::string>& strings,
const char* separator = " ");
/// Concatenates \p strings, with default separator.
///
/// Returns the concatenation of the strings in \p strings, with \p separator
/// (by default, a space) added between each successive pair of strings.
TF_API
std::string TfStringJoin(const std::set<std::string>& strings,
const char* separator = " ");
/// Breaks the given string apart, returning a vector of strings.
///
/// The string \p source is broken apart into individual words, where a word
/// is delimited by the string \p separator. This function behaves like
/// pythons string split method.
TF_API
std::vector<std::string> TfStringSplit(std::string const &src,
std::string const &separator);
/// Breaks the given string apart, returning a vector of strings.
///
/// The string \p source is broken apart into individual words, where a word
/// is delimited by the characters in \p delimiters. Delimiters default to
/// white space (space, tab, and newline).
///
/// No empty strings are returned: delimiters at the start or end are ignored,
/// consecutive delimiters are treated as though they were one, and an empty
/// input will result in an empty return vector.
TF_API
std::vector<std::string> TfStringTokenize(const std::string& source,
const char* delimiters = " \t\n");
/// Breaks the given string apart, returning a set of strings.
///
/// Same as TfStringTokenize, except this one returns a set.
TF_API
std::set<std::string> TfStringTokenizeToSet(const std::string& source,
const char* delimiters = " \t\n");
/// Breaks the given quoted string apart, returning a vector of strings.
///
/// The string \p source is broken apart into individual words, where a word
/// is delimited by the characters in \p delimiters. This function is similar
/// to \c TfStringTokenize, except it considers a quoted string as a single
/// word. The function will preserve quotes that are nested within other
/// quotes or are preceded by a backslash character. \p errors, if provided,
/// contains any error messages. Delimiters default to white space (space,
/// tab, and newline).
TF_API
std::vector<std::string>
TfQuotedStringTokenize(const std::string& source,
const char* delimiters = " \t\n",
std::string *errors = NULL);
/// Breaks the given string apart by matching delimiters.
///
/// The string \p source is broken apart into individual words, where a word
/// begins with \p openDelimiter and ends with a matching \p closeDelimiter.
/// Any delimiters within the matching delimiters become part of the word, and
/// anything outside matching delimiters gets dropped. For example, \c
/// TfMatchedStringTokenize("{a} string {to {be} split}", '{', '}') would
/// return a vector containing "a" and "to {be} split". If \p openDelimiter and
/// \p closeDelimiter cannot be the same. \p errors, if provided, contains any
/// error messages.
TF_API
std::vector<std::string>
TfMatchedStringTokenize(const std::string& source,
char openDelimiter,
char closeDelimiter,
char escapeCharacter = '\0',
std::string *errors = NULL);
/// This overloaded version of \c TfMatchedStringTokenize does not take an \c
/// escapeCharacter parameter but does take \param errors. It allows \c
/// TfMatchedStringTokenize to be called with or without an \c escapeCharacter
/// and with or without \c errors.
///
/// \overload
inline
std::vector<std::string>
TfMatchedStringTokenize(const std::string& source,
char openDelimiter,
char closeDelimiter,
std::string *errors)
{
return TfMatchedStringTokenize(source, openDelimiter,
closeDelimiter, '\0', errors);
}
/// \class TfDictionaryLessThan
///
/// Provides dictionary ordering binary predicate function on strings.
///
/// The \c TfDictionaryLessThan class is a functor as defined by the STL
/// standard. It compares strings using "dictionary" order: for example, the
/// following strings are in dictionary order:
/// ["abacus", "Albert", "albert", "baby", "Bert", "file01", "file001", "file2",
/// "file10"]
///
/// Note that capitalization matters only if the strings differ by
/// capitalization alone.
///
/// Characters whose ASCII value are inbetween upper- and lowercase letters,
/// such as underscore, are sorted to come after all letters.
///
struct TfDictionaryLessThan {
/// Return true if \p lhs is less than \p rhs in dictionary order.
///
/// Normally this functor is used to supply an ordering functor for STL
/// containers: for example,
/// \code
/// map<string, DataType, TfDictionaryLessThan> table;
/// \endcode
///
/// If you simply need to compare two strings, you can do so as follows:
/// \code
/// bool aIsFirst = TfDictionaryLessThan()(aString, bString);
/// \endcode
TF_API bool operator()(const std::string &lhs, const std::string &rhs) const;
};
/// Convert an arbitrary type into a string
///
/// Use the type's stream output operator to convert it into a string. You are
/// free to use the stream operators in ostreamMethods.h, but are not required
/// to do so.
template <typename T>
typename std::enable_if<!std::is_enum<T>::value, std::string>::type
TfStringify(const T& v)
{
std::ostringstream stream;
stream << v;
return stream.str();
}
/// \overload
template <typename T>
typename std::enable_if<std::is_enum<T>::value, std::string>::type
TfStringify(const T& v)
{
return TfEnum::GetName(v);
}
/// \overload
TF_API std::string TfStringify(bool v);
/// \overload
TF_API std::string TfStringify(std::string const&);
/// \overload
TF_API std::string TfStringify(float);
/// \overload
TF_API std::string TfStringify(double);
/// Writes the string representation of \c d to \c buffer of length \c len.
/// If \c emitTrailingZero is true, the string representation will end with .0
/// in the case where d is an integer otherwise it will be omitted.
/// The buffer length must be at least 25 in order to ensure that all doubles
/// values can be represented.
/// Returns whether the conversion was successful.
TF_API bool TfDoubleToString(
double d, char* buffer, int len, bool emitTrailingZero);
/// \struct TfStreamFloat
///
/// A type which offers streaming for floats in a canonical
/// format that can safely roundtrip with the minimal number of digits.
struct TfStreamFloat {
explicit TfStreamFloat(float f) : value(f) {}
float value;
};
TF_API std::ostream& operator<<(std::ostream& o, TfStreamFloat t);
/// \struct TfStreamDouble
///
/// A type which offers streaming for doubles in a canonical
/// format that can safely roundtrip with the minimal number of digits.
struct TfStreamDouble {
explicit TfStreamDouble(double d) : value(d) {}
double value;
};
TF_API std::ostream& operator<<(std::ostream& o, TfStreamDouble t);
/// Convert a string to an arbitrary type
///
/// Use the type's stream input operator to get it from a string. If \p status
/// is non-NULL and \p instring cannot be converted to a \c T, \p *status is
/// set to \c false; otherwise, \p *status is not modified.
template <typename T>
T
TfUnstringify(const std::string &instring, bool* status = NULL)
{
T v = T();
std::istringstream stream(instring);
stream >> v;
if (status && !stream)
*status = false;
return v;
}
/// \overload
template <>
TF_API
bool TfUnstringify(const std::string &instring, bool* status);
/// \overload
template <>
TF_API
std::string TfUnstringify(const std::string &instring, bool* status);
/// Returns a string with glob characters converted to their regular
/// expression equivalents.
///
/// Currently, this transforms strings by replacing all instances of '.' with
/// '\.', '*' with '.*', and '?' with '.', in that order.
TF_API
std::string TfStringGlobToRegex(const std::string& s);
/// Process escape sequences in ANSI C string constants.
///
/// The following escape sequences are accepted:
///
/// \li \\\\: backslash
/// \li \\a: ring the bell
/// \li \\b: backspace
/// \li \\f: form feed
/// \li \\n: new line
/// \li \\r: carriage return
/// \li \\t: tab
/// \li \\v: vertical tab
/// \li \\xdd: hex constant
/// \li \\ddd: octal constant
///
/// So, if the two-character sequence "\\n" appears in the string, it is
/// replaced by an actual newline. Each hex and octal constant translates into
/// one character in the output string. Hex constants can be up to 2 digits,
/// octal constants can be up to 3 digits. Both are terminated by a character
/// that is not a valid constant. Note that it is good practice to encode hex
/// and octal constants with maximum width (2 and 3 digits, respectively) using
/// leading zeroes if necessary. This avoids problems where characters after
/// the hex/octal constant that shouldn't be part of the constant get
/// interpreted as part of it. For example, the sequence "\x2defaced" will
/// produce the characters "-efaced" when what was probably intended was the
/// character 0x02 (STX) followed by "defaced".
//
/// Illegal escape sequences are replaced by the character following the
/// backslash, so the two character sequence "\\c" would become "c". Processing
/// continues until the input hits a NUL character in the input string -
/// anything appearing after the NUL will be ignored.
TF_API std::string TfEscapeString(const std::string &in);
TF_API void TfEscapeStringReplaceChar(const char** in, char** out);
/// Concatenate two strings containing '/' and '..' tokens like a file path or
/// scope name.
///
/// Tokenize the input strings using a '/' delimiter. Look for '..' tokens in
/// the suffix and construct the appropriate result.
///
/// Examples:
///
/// \li TfStringCatPaths( "foo/bar", "jive" ) => "foo/bar/jive"
/// \li TfStringCatPaths( "foo/bar", "../jive" ) => "foo/jive"
TF_API
std::string TfStringCatPaths( const std::string &prefix,
const std::string &suffix );
/// Test whether \a identifier is valid.
///
/// An identifier is valid if it follows the C/Python identifier convention;
/// that is, it must be at least one character long, must start with a letter
/// or underscore, and must contain only letters, underscores, and numerals.
inline bool
TfIsValidIdentifier(std::string const &identifier)
{
char const *p = identifier.c_str();
auto letter = [](unsigned c) { return ((c-'A') < 26) || ((c-'a') < 26); };
auto number = [](unsigned c) { return (c-'0') < 10; };
auto under = [](unsigned c) { return c == '_'; };
unsigned x = *p;
if (!x || number(x)) {
return false;
}
while (letter(x) || number(x) || under(x)) {
x = *p++;
};
return x == 0;
}
/// Produce a valid identifier (see TfIsValidIdentifier) from \p in by
/// replacing invalid characters with '_'. If \p in is empty, return "_".
TF_API
std::string
TfMakeValidIdentifier(const std::string &in);
/// Escapes characters in \a in so that they are valid XML.
///
/// Returns the name with special characters (&, <, >, ", ') replaced with the
/// corresponding escape sequences.
TF_API
std::string TfGetXmlEscapedString(const std::string &in);
///@}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TF_STRING_UTILS_H
Loaded 100 of 15684 files, more files were not shown because too many files have changed in this diff. Show more