repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/macros.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_MACROS_H__ #define GOOGLE_PROTOBUF_MACROS_H__ #include <google/protobuf/stubs/port.h> namespace google { namespace protobuf { #undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS #define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #undef GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS #define GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ TypeName(); \ TypeName(const TypeName&); \ void operator=(const TypeName&) // =================================================================== // from google3/base/basictypes.h // The GOOGLE_ARRAYSIZE(arr) macro returns the # of elements in an array arr. // The expression is a compile-time constant, and therefore can be // used in defining new arrays, for example. // // GOOGLE_ARRAYSIZE catches a few type errors. If you see a compiler error // // "warning: division by zero in ..." // // when using GOOGLE_ARRAYSIZE, you are (wrongfully) giving it a pointer. // You should only use GOOGLE_ARRAYSIZE on statically allocated arrays. // // The following comments are on the implementation details, and can // be ignored by the users. // // ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in // the array) and sizeof(*(arr)) (the # of bytes in one array // element). If the former is divisible by the latter, perhaps arr is // indeed an array, in which case the division result is the # of // elements in the array. Otherwise, arr cannot possibly be an array, // and we generate a compiler error to prevent the code from // compiling. // // Since the size of bool is implementation-defined, we need to cast // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final // result has type size_t. // // This macro is not perfect as it wrongfully accepts certain // pointers, namely where the pointer size is divisible by the pointee // size. Since all our code has to go through a 32-bit compiler, // where a pointer is 4 bytes, this means all pointers to a type whose // size is 3 or greater than 4 will be (righteously) rejected. // // Kudos to Jorg Brown for this simple and elegant implementation. #undef GOOGLE_ARRAYSIZE #define GOOGLE_ARRAYSIZE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) // The COMPILE_ASSERT macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, // content_type_names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. namespace internal { template <bool> struct CompileAssert { }; } // namespace internal #define GOOGLE_COMPILE_ASSERT(expr, msg) static_assert(expr, #msg) } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_MACROS_H__
4,903
39.528926
77
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/mutex.h
// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_ #define GOOGLE_PROTOBUF_STUBS_MUTEX_H_ #include <mutex> #ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP #include <windows.h> // GetMessage conflicts with GeneratedMessageReflection::GetMessage(). #ifdef GetMessage #undef GetMessage #endif #endif #include <google/protobuf/stubs/macros.h> // Define thread-safety annotations for use below, if we are building with // Clang. #if defined(__clang__) && !defined(SWIG) #define GOOGLE_PROTOBUF_ACQUIRE(...) \ __attribute__((acquire_capability(__VA_ARGS__))) #define GOOGLE_PROTOBUF_RELEASE(...) \ __attribute__((release_capability(__VA_ARGS__))) #define GOOGLE_PROTOBUF_CAPABILITY(x) __attribute__((capability(x))) #else #define GOOGLE_PROTOBUF_ACQUIRE(...) #define GOOGLE_PROTOBUF_RELEASE(...) #define GOOGLE_PROTOBUF_CAPABILITY(x) #endif #include <google/protobuf/port_def.inc> // =================================================================== // emulates google3/base/mutex.h namespace google { namespace protobuf { namespace internal { #define GOOGLE_PROTOBUF_LINKER_INITIALIZED #ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP // This class is a lightweight replacement for std::mutex on Windows platforms. // std::mutex does not work on Windows XP SP2 with the latest VC++ libraries, // because it utilizes the Concurrency Runtime that is only supported on Windows // XP SP3 and above. class PROTOBUF_EXPORT CriticalSectionLock { public: CriticalSectionLock() { InitializeCriticalSection(&critical_section_); } ~CriticalSectionLock() { DeleteCriticalSection(&critical_section_); } void lock() { EnterCriticalSection(&critical_section_); } void unlock() { LeaveCriticalSection(&critical_section_); } private: CRITICAL_SECTION critical_section_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CriticalSectionLock); }; #endif // Mutex is a natural type to wrap. As both google and other organization have // specialized mutexes. gRPC also provides an injection mechanism for custom // mutexes. class GOOGLE_PROTOBUF_CAPABILITY("mutex") PROTOBUF_EXPORT WrappedMutex { public: WrappedMutex() = default; void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); } void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); } // Crash if this Mutex is not held exclusively by this thread. // May fail to crash when it should; will never crash when it should not. void AssertHeld() const {} private: #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP std::mutex mu_; #else // ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP CriticalSectionLock mu_; #endif // #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP }; using Mutex = WrappedMutex; // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class PROTOBUF_EXPORT MutexLock { public: explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); } ~MutexLock() { this->mu_->Unlock(); } private: Mutex *const mu_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock); }; // TODO(kenton): Implement these? Hard to implement portably. typedef MutexLock ReaderMutexLock; typedef MutexLock WriterMutexLock; // MutexLockMaybe is like MutexLock, but is a no-op when mu is nullptr. class PROTOBUF_EXPORT MutexLockMaybe { public: explicit MutexLockMaybe(Mutex *mu) : mu_(mu) { if (this->mu_ != nullptr) { this->mu_->Lock(); } } ~MutexLockMaybe() { if (this->mu_ != nullptr) { this->mu_->Unlock(); } } private: Mutex *const mu_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe); }; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) template<typename T> class ThreadLocalStorage { public: ThreadLocalStorage() { pthread_key_create(&key_, &ThreadLocalStorage::Delete); } ~ThreadLocalStorage() { pthread_key_delete(key_); } T* Get() { T* result = static_cast<T*>(pthread_getspecific(key_)); if (result == nullptr) { result = new T(); pthread_setspecific(key_, result); } return result; } private: static void Delete(void* value) { delete static_cast<T*>(value); } pthread_key_t key_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ThreadLocalStorage); }; #endif } // namespace internal // We made these internal so that they would show up as such in the docs, // but we don't want to stick "internal::" in front of them everywhere. using internal::Mutex; using internal::MutexLock; using internal::ReaderMutexLock; using internal::WriterMutexLock; using internal::MutexLockMaybe; } // namespace protobuf } // namespace google #undef GOOGLE_PROTOBUF_ACQUIRE #undef GOOGLE_PROTOBUF_RELEASE #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_
6,157
31.930481
80
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/once.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__ #define GOOGLE_PROTOBUF_STUBS_ONCE_H__ #include <mutex> #include <utility> #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { namespace internal { using once_flag = std::once_flag; template <typename... Args> void call_once(Args&&... args ) { std::call_once(std::forward<Args>(args)...); } } // namespace internal } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_ONCE_H__
2,184
38.017857
73
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/platform_macros.h
// Protocol Buffers - Google's data interchange format // Copyright 2012 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_PLATFORM_MACROS_H_ #define GOOGLE_PROTOBUF_PLATFORM_MACROS_H_ #define GOOGLE_PROTOBUF_PLATFORM_ERROR \ #error "Host platform was not detected as supported by protobuf" // Processor architecture detection. For more info on what's defined, see: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx // http://www.agner.org/optimize/calling_conventions.pdf // or with gcc, run: "echo | gcc -E -dM -" #if defined(_M_X64) || defined(__x86_64__) #define GOOGLE_PROTOBUF_ARCH_X64 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #elif defined(_M_IX86) || defined(__i386__) #define GOOGLE_PROTOBUF_ARCH_IA32 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #elif defined(__QNX__) #define GOOGLE_PROTOBUF_ARCH_ARM_QNX 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #elif defined(_M_ARM) || defined(__ARMEL__) #define GOOGLE_PROTOBUF_ARCH_ARM 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #elif defined(_M_ARM64) #define GOOGLE_PROTOBUF_ARCH_ARM 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #elif defined(__aarch64__) #define GOOGLE_PROTOBUF_ARCH_AARCH64 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #elif defined(__mips__) #if defined(__LP64__) #define GOOGLE_PROTOBUF_ARCH_MIPS64 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #else #define GOOGLE_PROTOBUF_ARCH_MIPS 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #endif #elif defined(__pnacl__) #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #elif defined(sparc) #define GOOGLE_PROTOBUF_ARCH_SPARC 1 #if defined(__sparc_v9__) || defined(__sparcv9) || defined(__arch64__) #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #else #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #endif #elif defined(_POWER) || defined(__powerpc64__) || defined(__PPC64__) #define GOOGLE_PROTOBUF_ARCH_POWER 1 #define GOOGLE_PROTOBUF_ARCH_64_BIT 1 #elif defined(__PPC__) #define GOOGLE_PROTOBUF_ARCH_PPC 1 #define GOOGLE_PROTOBUF_ARCH_32_BIT 1 #elif defined(__GNUC__) # if (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4)) // We fallback to the generic Clang/GCC >= 4.7 implementation in atomicops.h # elif defined(__clang__) # if !__has_extension(c_atomic) GOOGLE_PROTOBUF_PLATFORM_ERROR # endif // We fallback to the generic Clang/GCC >= 4.7 implementation in atomicops.h # endif # if __LP64__ # define GOOGLE_PROTOBUF_ARCH_64_BIT 1 # else # define GOOGLE_PROTOBUF_ARCH_32_BIT 1 # endif #else GOOGLE_PROTOBUF_PLATFORM_ERROR #endif #if defined(__APPLE__) #define GOOGLE_PROTOBUF_OS_APPLE #include <Availability.h> #include <TargetConditionals.h> #if TARGET_OS_IPHONE #define GOOGLE_PROTOBUF_OS_IPHONE #endif #elif defined(__EMSCRIPTEN__) #define GOOGLE_PROTOBUF_OS_EMSCRIPTEN #elif defined(__native_client__) #define GOOGLE_PROTOBUF_OS_NACL #elif defined(sun) #define GOOGLE_PROTOBUF_OS_SOLARIS #elif defined(_AIX) #define GOOGLE_PROTOBUF_OS_AIX #elif defined(__ANDROID__) #define GOOGLE_PROTOBUF_OS_ANDROID #endif #undef GOOGLE_PROTOBUF_PLATFORM_ERROR #if defined(GOOGLE_PROTOBUF_OS_ANDROID) || defined(GOOGLE_PROTOBUF_OS_IPHONE) || defined(__OpenBSD__) // Android ndk does not support the __thread keyword very well yet. Here // we use pthread_key_create()/pthread_getspecific()/... methods for // TLS support on android. // iOS and OpenBSD also do not support the __thread keyword. #define GOOGLE_PROTOBUF_NO_THREADLOCAL #endif #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 1070 // __thread keyword requires at least 10.7 #define GOOGLE_PROTOBUF_NO_THREADLOCAL #endif #endif // GOOGLE_PROTOBUF_PLATFORM_MACROS_H_
5,108
36.844444
101
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/port.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_STUBS_PORT_H_ #define GOOGLE_PROTOBUF_STUBS_PORT_H_ #include <assert.h> #include <cstdint> #include <stdlib.h> #include <cstddef> #include <string> #include <string.h> #include <google/protobuf/stubs/platform_macros.h> #include <google/protobuf/port_def.inc> #undef PROTOBUF_LITTLE_ENDIAN #ifdef _WIN32 // Assuming windows is always little-endian. // TODO(xiaofeng): The PROTOBUF_LITTLE_ENDIAN is not only used for // optimization but also for correctness. We should define an // different macro to test the big-endian code path in coded_stream. #if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) #define PROTOBUF_LITTLE_ENDIAN 1 #endif #if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER) // If MSVC has "/RTCc" set, it will complain about truncating casts at // runtime. This file contains some intentional truncating casts. #pragma runtime_checks("c", off) #endif #else #include <sys/param.h> // __BYTE_ORDER #if defined(__OpenBSD__) #include <endian.h> #endif #if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN) || \ (defined(BYTE_ORDER) && BYTE_ORDER == LITTLE_ENDIAN)) && \ !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) #define PROTOBUF_LITTLE_ENDIAN 1 #endif #endif // These #includes are for the byte swap functions declared later on. #ifdef _MSC_VER #include <stdlib.h> // NOLINT(build/include) #include <intrin.h> #elif defined(__APPLE__) #include <libkern/OSByteOrder.h> #elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__) #include <byteswap.h> // IWYU pragma: export #endif // Legacy: some users reference these (internal-only) macros even though we // don't need them any more. #if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS) #ifdef LIBPROTOBUF_EXPORTS #define LIBPROTOBUF_EXPORT __declspec(dllexport) #else #define LIBPROTOBUF_EXPORT __declspec(dllimport) #endif #ifdef LIBPROTOC_EXPORTS #define LIBPROTOC_EXPORT __declspec(dllexport) #else #define LIBPROTOC_EXPORT __declspec(dllimport) #endif #else #define LIBPROTOBUF_EXPORT #define LIBPROTOC_EXPORT #endif #define PROTOBUF_RUNTIME_DEPRECATED(message) PROTOBUF_DEPRECATED_MSG(message) #define GOOGLE_PROTOBUF_RUNTIME_DEPRECATED(message) \ PROTOBUF_DEPRECATED_MSG(message) // =================================================================== // from google3/base/port.h #if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \ (defined(_MSC_VER) && _MSC_VER >= 1900)) // Define this to 1 if the code is compiled in C++11 mode; leave it // undefined otherwise. Do NOT define it to 0 -- that causes // '#ifdef LANG_CXX11' to behave differently from '#if LANG_CXX11'. #define LANG_CXX11 1 #else #error "Protobuf requires at least C++11." #endif namespace google { namespace protobuf { using ConstStringParam = const std::string &; typedef unsigned int uint; typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; static const int32 kint32max = 0x7FFFFFFF; static const int32 kint32min = -kint32max - 1; static const int64 kint64max = PROTOBUF_LONGLONG(0x7FFFFFFFFFFFFFFF); static const int64 kint64min = -kint64max - 1; static const uint32 kuint32max = 0xFFFFFFFFu; static const uint64 kuint64max = PROTOBUF_ULONGLONG(0xFFFFFFFFFFFFFFFF); #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) ||\ defined(MEMORY_SANITIZER) #ifdef __cplusplus extern "C" { #endif // __cplusplus uint16_t __sanitizer_unaligned_load16(const void *p); uint32_t __sanitizer_unaligned_load32(const void *p); uint64_t __sanitizer_unaligned_load64(const void *p); void __sanitizer_unaligned_store16(void *p, uint16_t v); void __sanitizer_unaligned_store32(void *p, uint32_t v); void __sanitizer_unaligned_store64(void *p, uint64_t v); #ifdef __cplusplus } // extern "C" #endif // __cplusplus inline uint16 GOOGLE_UNALIGNED_LOAD16(const void *p) { return __sanitizer_unaligned_load16(p); } inline uint32 GOOGLE_UNALIGNED_LOAD32(const void *p) { return __sanitizer_unaligned_load32(p); } inline uint64 GOOGLE_UNALIGNED_LOAD64(const void *p) { return __sanitizer_unaligned_load64(p); } inline void GOOGLE_UNALIGNED_STORE16(void *p, uint16 v) { __sanitizer_unaligned_store16(p, v); } inline void GOOGLE_UNALIGNED_STORE32(void *p, uint32 v) { __sanitizer_unaligned_store32(p, v); } inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { __sanitizer_unaligned_store64(p, v); } #elif defined(GOOGLE_PROTOBUF_USE_UNALIGNED) && GOOGLE_PROTOBUF_USE_UNALIGNED #define GOOGLE_UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p)) #define GOOGLE_UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p)) #define GOOGLE_UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p)) #define GOOGLE_UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val)) #define GOOGLE_UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val)) #define GOOGLE_UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val)) #else inline uint16 GOOGLE_UNALIGNED_LOAD16(const void *p) { uint16 t; memcpy(&t, p, sizeof t); return t; } inline uint32 GOOGLE_UNALIGNED_LOAD32(const void *p) { uint32 t; memcpy(&t, p, sizeof t); return t; } inline uint64 GOOGLE_UNALIGNED_LOAD64(const void *p) { uint64 t; memcpy(&t, p, sizeof t); return t; } inline void GOOGLE_UNALIGNED_STORE16(void *p, uint16 v) { memcpy(p, &v, sizeof v); } inline void GOOGLE_UNALIGNED_STORE32(void *p, uint32 v) { memcpy(p, &v, sizeof v); } inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { memcpy(p, &v, sizeof v); } #endif #if defined(GOOGLE_PROTOBUF_OS_NACL) \ || (defined(__ANDROID__) && defined(__clang__) \ && (__clang_major__ == 3 && __clang_minor__ == 8) \ && (__clang_patchlevel__ < 275480)) # define GOOGLE_PROTOBUF_USE_PORTABLE_LOG2 #endif // The following guarantees declaration of the byte swap functions. #ifdef _MSC_VER #define bswap_16(x) _byteswap_ushort(x) #define bswap_32(x) _byteswap_ulong(x) #define bswap_64(x) _byteswap_uint64(x) #elif defined(__APPLE__) // Mac OS X / Darwin features #define bswap_16(x) OSSwapInt16(x) #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) #elif !defined(__GLIBC__) && !defined(__BIONIC__) && !defined(__CYGWIN__) #ifndef bswap_16 static inline uint16 bswap_16(uint16 x) { return static_cast<uint16>(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8)); } #define bswap_16(x) bswap_16(x) #endif #ifndef bswap_32 static inline uint32 bswap_32(uint32 x) { return (((x & 0xFF) << 24) | ((x & 0xFF00) << 8) | ((x & 0xFF0000) >> 8) | ((x & 0xFF000000) >> 24)); } #define bswap_32(x) bswap_32(x) #endif #ifndef bswap_64 static inline uint64 bswap_64(uint64 x) { return (((x & PROTOBUF_ULONGLONG(0xFF)) << 56) | ((x & PROTOBUF_ULONGLONG(0xFF00)) << 40) | ((x & PROTOBUF_ULONGLONG(0xFF0000)) << 24) | ((x & PROTOBUF_ULONGLONG(0xFF000000)) << 8) | ((x & PROTOBUF_ULONGLONG(0xFF00000000)) >> 8) | ((x & PROTOBUF_ULONGLONG(0xFF0000000000)) >> 24) | ((x & PROTOBUF_ULONGLONG(0xFF000000000000)) >> 40) | ((x & PROTOBUF_ULONGLONG(0xFF00000000000000)) >> 56)); } #define bswap_64(x) bswap_64(x) #endif #endif // =================================================================== // from google3/util/bits/bits.h class Bits { public: static uint32 Log2FloorNonZero(uint32 n) { #if defined(__GNUC__) return 31 ^ static_cast<uint32>(__builtin_clz(n)); #elif defined(_MSC_VER) unsigned long where; _BitScanReverse(&where, n); return where; #else return Log2FloorNonZero_Portable(n); #endif } static uint32 Log2FloorNonZero64(uint64 n) { // Older versions of clang run into an instruction-selection failure when // it encounters __builtin_clzll: // https://bugs.chromium.org/p/nativeclient/issues/detail?id=4395 // This includes arm-nacl-clang and clang in older Android NDK versions. // To work around this, when we build with those we use the portable // implementation instead. #if defined(__GNUC__) && !defined(GOOGLE_PROTOBUF_USE_PORTABLE_LOG2) return 63 ^ static_cast<uint32>(__builtin_clzll(n)); #elif defined(_MSC_VER) && defined(_M_X64) unsigned long where; _BitScanReverse64(&where, n); return where; #else return Log2FloorNonZero64_Portable(n); #endif } private: static int Log2FloorNonZero_Portable(uint32 n) { if (n == 0) return -1; int log = 0; uint32 value = n; for (int i = 4; i >= 0; --i) { int shift = (1 << i); uint32 x = value >> shift; if (x != 0) { value = x; log += shift; } } assert(value == 1); return log; } static int Log2FloorNonZero64_Portable(uint64 n) { const uint32 topbits = static_cast<uint32>(n >> 32); if (topbits == 0) { // Top bits are zero, so scan in bottom bits return static_cast<int>(Log2FloorNonZero(static_cast<uint32>(n))); } else { return 32 + static_cast<int>(Log2FloorNonZero(topbits)); } } }; // =================================================================== // from google3/util/endian/endian.h PROTOBUF_EXPORT uint32 ghtonl(uint32 x); class BigEndian { public: #ifdef PROTOBUF_LITTLE_ENDIAN static uint16 FromHost16(uint16 x) { return bswap_16(x); } static uint16 ToHost16(uint16 x) { return bswap_16(x); } static uint32 FromHost32(uint32 x) { return bswap_32(x); } static uint32 ToHost32(uint32 x) { return bswap_32(x); } static uint64 FromHost64(uint64 x) { return bswap_64(x); } static uint64 ToHost64(uint64 x) { return bswap_64(x); } static bool IsLittleEndian() { return true; } #else static uint16 FromHost16(uint16 x) { return x; } static uint16 ToHost16(uint16 x) { return x; } static uint32 FromHost32(uint32 x) { return x; } static uint32 ToHost32(uint32 x) { return x; } static uint64 FromHost64(uint64 x) { return x; } static uint64 ToHost64(uint64 x) { return x; } static bool IsLittleEndian() { return false; } #endif /* ENDIAN */ // Functions to do unaligned loads and stores in big-endian order. static uint16 Load16(const void *p) { return ToHost16(GOOGLE_UNALIGNED_LOAD16(p)); } static void Store16(void *p, uint16 v) { GOOGLE_UNALIGNED_STORE16(p, FromHost16(v)); } static uint32 Load32(const void *p) { return ToHost32(GOOGLE_UNALIGNED_LOAD32(p)); } static void Store32(void *p, uint32 v) { GOOGLE_UNALIGNED_STORE32(p, FromHost32(v)); } static uint64 Load64(const void *p) { return ToHost64(GOOGLE_UNALIGNED_LOAD64(p)); } static void Store64(void *p, uint64 v) { GOOGLE_UNALIGNED_STORE64(p, FromHost64(v)); } }; } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_PORT_H_
12,765
30.44335
85
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/status.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_STUBS_STATUS_H_ #define GOOGLE_PROTOBUF_STUBS_STATUS_H_ #include <iosfwd> #include <string> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/stringpiece.h> #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { namespace util { namespace error { // These values must match error codes defined in google/rpc/code.proto. enum Code { OK = 0, CANCELLED = 1, UNKNOWN = 2, INVALID_ARGUMENT = 3, DEADLINE_EXCEEDED = 4, NOT_FOUND = 5, ALREADY_EXISTS = 6, PERMISSION_DENIED = 7, UNAUTHENTICATED = 16, RESOURCE_EXHAUSTED = 8, FAILED_PRECONDITION = 9, ABORTED = 10, OUT_OF_RANGE = 11, UNIMPLEMENTED = 12, INTERNAL = 13, UNAVAILABLE = 14, DATA_LOSS = 15, }; } // namespace error class PROTOBUF_EXPORT Status { public: // Creates a "successful" status. Status(); // Create a status in the canonical error space with the specified // code, and error message. If "code == 0", error_message is // ignored and a Status object identical to Status::OK is // constructed. Status(error::Code error_code, StringPiece error_message); Status(const Status&); Status& operator=(const Status& x); ~Status() {} // Some pre-defined Status objects static const Status OK; // Identical to 0-arg constructor static const Status CANCELLED; static const Status UNKNOWN; // Accessor bool ok() const { return error_code_ == error::OK; } int error_code() const { return error_code_; } error::Code code() const { return error_code_; } StringPiece error_message() const { return error_message_; } StringPiece message() const { return error_message_; } bool operator==(const Status& x) const; bool operator!=(const Status& x) const { return !operator==(x); } // Return a combination of the error code name and message. std::string ToString() const; private: error::Code error_code_; std::string error_message_; }; // Prints a human-readable representation of 'x' to 'os'. PROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x); } // namespace util } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_STATUS_H_
3,949
30.349206
76
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/statusor.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // StatusOr<T> is the union of a Status object and a T // object. StatusOr models the concept of an object that is either a // usable value, or an error Status explaining why such a value is // not present. To this end, StatusOr<T> does not allow its Status // value to be Status::OK. Further, StatusOr<T*> does not allow the // contained pointer to be nullptr. // // The primary use-case for StatusOr<T> is as the return value of a // function which may fail. // // Example client usage for a StatusOr<T>, where T is not a pointer: // // StatusOr<float> result = DoBigCalculationThatCouldFail(); // if (result.ok()) { // float answer = result.ValueOrDie(); // printf("Big calculation yielded: %f", answer); // } else { // LOG(ERROR) << result.status(); // } // // Example client usage for a StatusOr<T*>: // // StatusOr<Foo*> result = FooFactory::MakeNewFoo(arg); // if (result.ok()) { // std::unique_ptr<Foo> foo(result.ValueOrDie()); // foo->DoSomethingCool(); // } else { // LOG(ERROR) << result.status(); // } // // Example client usage for a StatusOr<std::unique_ptr<T>>: // // StatusOr<std::unique_ptr<Foo>> result = FooFactory::MakeNewFoo(arg); // if (result.ok()) { // std::unique_ptr<Foo> foo = result.ConsumeValueOrDie(); // foo->DoSomethingCool(); // } else { // LOG(ERROR) << result.status(); // } // // Example factory implementation returning StatusOr<T*>: // // StatusOr<Foo*> FooFactory::MakeNewFoo(int arg) { // if (arg <= 0) { // return ::util::Status(::util::error::INVALID_ARGUMENT, // "Arg must be positive"); // } else { // return new Foo(arg); // } // } // #ifndef GOOGLE_PROTOBUF_STUBS_STATUSOR_H_ #define GOOGLE_PROTOBUF_STUBS_STATUSOR_H_ #include <new> #include <string> #include <utility> #include <google/protobuf/stubs/status.h> #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { namespace util { template<typename T> class StatusOr { template<typename U> friend class StatusOr; public: // Construct a new StatusOr with Status::UNKNOWN status StatusOr(); // Construct a new StatusOr with the given non-ok status. After calling // this constructor, calls to ValueOrDie() will CHECK-fail. // // NOTE: Not explicit - we want to use StatusOr<T> as a return // value, so it is convenient and sensible to be able to do 'return // Status()' when the return type is StatusOr<T>. // // REQUIRES: status != Status::OK. This requirement is DCHECKed. // In optimized builds, passing Status::OK here will have the effect // of passing PosixErrorSpace::EINVAL as a fallback. StatusOr(const Status& status); // NOLINT // Construct a new StatusOr with the given value. If T is a plain pointer, // value must not be nullptr. After calling this constructor, calls to // ValueOrDie() will succeed, and calls to status() will return OK. // // NOTE: Not explicit - we want to use StatusOr<T> as a return type // so it is convenient and sensible to be able to do 'return T()' // when when the return type is StatusOr<T>. // // REQUIRES: if T is a plain pointer, value != nullptr. This requirement is // DCHECKed. In optimized builds, passing a null pointer here will have // the effect of passing PosixErrorSpace::EINVAL as a fallback. StatusOr(const T& value); // NOLINT // Copy constructor. StatusOr(const StatusOr& other); // Conversion copy constructor, T must be copy constructible from U template<typename U> StatusOr(const StatusOr<U>& other); // Assignment operator. StatusOr& operator=(const StatusOr& other); // Conversion assignment operator, T must be assignable from U template<typename U> StatusOr& operator=(const StatusOr<U>& other); // Returns a reference to our status. If this contains a T, then // returns Status::OK. const Status& status() const; // Returns this->status().ok() bool ok() const; // Returns a reference to our current value, or CHECK-fails if !this->ok(). // If you need to initialize a T object from the stored value, // ConsumeValueOrDie() may be more efficient. const T& ValueOrDie() const; const T& value () const; private: Status status_; T value_; }; //////////////////////////////////////////////////////////////////////////////// // Implementation details for StatusOr<T> namespace internal { class PROTOBUF_EXPORT StatusOrHelper { public: // Move type-agnostic error handling to the .cc. static void Crash(const util::Status& status); // Customized behavior for StatusOr<T> vs. StatusOr<T*> template<typename T> struct Specialize; }; template<typename T> struct StatusOrHelper::Specialize { // For non-pointer T, a reference can never be nullptr. static inline bool IsValueNull(const T& t) { return false; } }; template<typename T> struct StatusOrHelper::Specialize<T*> { static inline bool IsValueNull(const T* t) { return t == nullptr; } }; } // namespace internal template<typename T> inline StatusOr<T>::StatusOr() : status_(util::Status::UNKNOWN) { } template<typename T> inline StatusOr<T>::StatusOr(const Status& status) { if (status.ok()) { status_ = Status(error::INTERNAL, "Status::OK is not a valid argument."); } else { status_ = status; } } template<typename T> inline StatusOr<T>::StatusOr(const T& value) { if (internal::StatusOrHelper::Specialize<T>::IsValueNull(value)) { status_ = Status(error::INTERNAL, "nullptr is not a valid argument."); } else { status_ = Status::OK; value_ = value; } } template<typename T> inline StatusOr<T>::StatusOr(const StatusOr<T>& other) : status_(other.status_), value_(other.value_) { } template<typename T> inline StatusOr<T>& StatusOr<T>::operator=(const StatusOr<T>& other) { status_ = other.status_; value_ = other.value_; return *this; } template<typename T> template<typename U> inline StatusOr<T>::StatusOr(const StatusOr<U>& other) : status_(other.status_), value_(other.status_.ok() ? other.value_ : T()) { } template<typename T> template<typename U> inline StatusOr<T>& StatusOr<T>::operator=(const StatusOr<U>& other) { status_ = other.status_; if (status_.ok()) value_ = other.value_; return *this; } template<typename T> inline const Status& StatusOr<T>::status() const { return status_; } template<typename T> inline bool StatusOr<T>::ok() const { return status().ok(); } template<typename T> inline const T& StatusOr<T>::ValueOrDie() const { if (!status_.ok()) { internal::StatusOrHelper::Crash(status_); } return value_; } template<typename T> inline const T& StatusOr<T>::value() const { if (!status_.ok()) { internal::StatusOrHelper::Crash(status_); } return value_; } } // namespace util } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_STATUSOR_H_
8,558
30.351648
80
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/stl_util.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // from google3/util/gtl/stl_util.h #ifndef GOOGLE_PROTOBUF_STUBS_STL_UTIL_H__ #define GOOGLE_PROTOBUF_STUBS_STL_UTIL_H__ #include <google/protobuf/stubs/common.h> namespace google { namespace protobuf { // Inside Google, this function implements a horrible, disgusting hack in which // we reach into the string's private implementation and resize it without // initializing the new bytes. In some cases doing this can significantly // improve performance. However, since it's totally non-portable it has no // place in open source code. Feel free to fill this function in with your // own disgusting hack if you want the perf boost. inline void STLStringResizeUninitialized(std::string* s, size_t new_size) { s->resize(new_size); } // Return a mutable char* pointing to a string's internal buffer, // which may not be null-terminated. Writing through this pointer will // modify the string. // // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the // next call to a string method that invalidates iterators. // // As of 2006-04, there is no standard-blessed way of getting a // mutable reference to a string's internal buffer. However, issue 530 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530) // proposes this as the method. According to Matt Austern, this should // already work on all current implementations. inline char* string_as_array(std::string* str) { // DO NOT USE const_cast<char*>(str->data())! See the unittest for why. return str->empty() ? nullptr : &*str->begin(); } } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_STUBS_STL_UTIL_H__
3,293
44.75
79
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/stringpiece.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A StringPiece points to part or all of a string, Cord, double-quoted string // literal, or other string-like object. A StringPiece does *not* own the // string to which it points. A StringPiece is not null-terminated. // // You can use StringPiece as a function or method parameter. A StringPiece // parameter can receive a double-quoted string literal argument, a "const // char*" argument, a string argument, or a StringPiece argument with no data // copying. Systematic use of StringPiece for arguments reduces data // copies and strlen() calls. // // Prefer passing StringPieces by value: // void MyFunction(StringPiece arg); // If circumstances require, you may also pass by const reference: // void MyFunction(const StringPiece& arg); // not preferred // Both of these have the same lifetime semantics. Passing by value // generates slightly smaller code. For more discussion, see the thread // go/stringpiecebyvalue on c-users. // // StringPiece is also suitable for local variables if you know that // the lifetime of the underlying object is longer than the lifetime // of your StringPiece variable. // // Beware of binding a StringPiece to a temporary: // StringPiece sp = obj.MethodReturningString(); // BAD: lifetime problem // // This code is okay: // string str = obj.MethodReturningString(); // str owns its contents // StringPiece sp(str); // GOOD, because str outlives sp // // StringPiece is sometimes a poor choice for a return value and usually a poor // choice for a data member. If you do use a StringPiece this way, it is your // responsibility to ensure that the object pointed to by the StringPiece // outlives the StringPiece. // // A StringPiece may represent just part of a string; thus the name "Piece". // For example, when splitting a string, vector<StringPiece> is a natural data // type for the output. For another example, a Cord is a non-contiguous, // potentially very long string-like object. The Cord class has an interface // that iteratively provides StringPiece objects that point to the // successive pieces of a Cord object. // // A StringPiece is not null-terminated. If you write code that scans a // StringPiece, you must check its length before reading any characters. // Common idioms that work on null-terminated strings do not work on // StringPiece objects. // // There are several ways to create a null StringPiece: // StringPiece() // StringPiece(nullptr) // StringPiece(nullptr, 0) // For all of the above, sp.data() == nullptr, sp.length() == 0, // and sp.empty() == true. Also, if you create a StringPiece with // a non-null pointer then sp.data() != nullptr. Once created, // sp.data() will stay either nullptr or not-nullptr, except if you call // sp.clear() or sp.set(). // // Thus, you can use StringPiece(nullptr) to signal an out-of-band value // that is different from other StringPiece values. This is similar // to the way that const char* p1 = nullptr; is different from // const char* p2 = "";. // // There are many ways to create an empty StringPiece: // StringPiece() // StringPiece(nullptr) // StringPiece(nullptr, 0) // StringPiece("") // StringPiece("", 0) // StringPiece("abcdef", 0) // StringPiece("abcdef"+6, 0) // For all of the above, sp.length() will be 0 and sp.empty() will be true. // For some empty StringPiece values, sp.data() will be nullptr. // For some empty StringPiece values, sp.data() will not be nullptr. // // Be careful not to confuse: null StringPiece and empty StringPiece. // The set of empty StringPieces properly includes the set of null StringPieces. // That is, every null StringPiece is an empty StringPiece, // but some non-null StringPieces are empty Stringpieces too. // // All empty StringPiece values compare equal to each other. // Even a null StringPieces compares equal to a non-null empty StringPiece: // StringPiece() == StringPiece("", 0) // StringPiece(nullptr) == StringPiece("abc", 0) // StringPiece(nullptr, 0) == StringPiece("abcdef"+6, 0) // // Look carefully at this example: // StringPiece("") == nullptr // True or false? TRUE, because StringPiece::operator== converts // the right-hand side from nullptr to StringPiece(nullptr), // and then compares two zero-length spans of characters. // However, we are working to make this example produce a compile error. // // Suppose you want to write: // bool TestWhat?(StringPiece sp) { return sp == nullptr; } // BAD // Do not do that. Write one of these instead: // bool TestNull(StringPiece sp) { return sp.data() == nullptr; } // bool TestEmpty(StringPiece sp) { return sp.empty(); } // The intent of TestWhat? is unclear. Did you mean TestNull or TestEmpty? // Right now, TestWhat? behaves likes TestEmpty. // We are working to make TestWhat? produce a compile error. // TestNull is good to test for an out-of-band signal. // TestEmpty is good to test for an empty StringPiece. // // Caveats (again): // (1) The lifetime of the pointed-to string (or piece of a string) // must be longer than the lifetime of the StringPiece. // (2) There may or may not be a '\0' character after the end of // StringPiece data. // (3) A null StringPiece is empty. // An empty StringPiece may or may not be a null StringPiece. #ifndef GOOGLE_PROTOBUF_STUBS_STRINGPIECE_H_ #define GOOGLE_PROTOBUF_STUBS_STRINGPIECE_H_ #include <assert.h> #include <stddef.h> #include <string.h> #include <iosfwd> #include <limits> #include <string> #include <google/protobuf/stubs/hash.h> #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { // StringPiece has *two* size types. // StringPiece::size_type // is unsigned // is 32 bits in LP32, 64 bits in LP64, 64 bits in LLP64 // no future changes intended // stringpiece_ssize_type // is signed // is 32 bits in LP32, 64 bits in LP64, 64 bits in LLP64 // future changes intended: http://go/64BitStringPiece // typedef std::string::difference_type stringpiece_ssize_type; // STRINGPIECE_CHECK_SIZE protects us from 32-bit overflows. // TODO(mec): delete this after stringpiece_ssize_type goes 64 bit. #if !defined(NDEBUG) #define STRINGPIECE_CHECK_SIZE 1 #elif defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0 #define STRINGPIECE_CHECK_SIZE 1 #else #define STRINGPIECE_CHECK_SIZE 0 #endif class PROTOBUF_EXPORT StringPiece { private: const char* ptr_; stringpiece_ssize_type length_; // Prevent overflow in debug mode or fortified mode. // sizeof(stringpiece_ssize_type) may be smaller than sizeof(size_t). static stringpiece_ssize_type CheckedSsizeTFromSizeT(size_t size) { #if STRINGPIECE_CHECK_SIZE > 0 #ifdef max #undef max #endif if (size > static_cast<size_t>( std::numeric_limits<stringpiece_ssize_type>::max())) { // Some people grep for this message in logs // so take care if you ever change it. LogFatalSizeTooBig(size, "size_t to int conversion"); } #endif return static_cast<stringpiece_ssize_type>(size); } // Out-of-line error path. static void LogFatalSizeTooBig(size_t size, const char* details); public: // We provide non-explicit singleton constructors so users can pass // in a "const char*" or a "string" wherever a "StringPiece" is // expected. // // Style guide exception granted: // http://goto/style-guide-exception-20978288 StringPiece() : ptr_(nullptr), length_(0) {} StringPiece(const char* str) // NOLINT(runtime/explicit) : ptr_(str), length_(0) { if (str != nullptr) { length_ = CheckedSsizeTFromSizeT(strlen(str)); } } template <class Allocator> StringPiece( // NOLINT(runtime/explicit) const std::basic_string<char, std::char_traits<char>, Allocator>& str) : ptr_(str.data()), length_(0) { length_ = CheckedSsizeTFromSizeT(str.size()); } StringPiece(const char* offset, stringpiece_ssize_type len) : ptr_(offset), length_(len) { assert(len >= 0); } // Substring of another StringPiece. // pos must be non-negative and <= x.length(). StringPiece(StringPiece x, stringpiece_ssize_type pos); // Substring of another StringPiece. // pos must be non-negative and <= x.length(). // len must be non-negative and will be pinned to at most x.length() - pos. StringPiece(StringPiece x, stringpiece_ssize_type pos, stringpiece_ssize_type len); // data() may return a pointer to a buffer with embedded NULs, and the // returned buffer may or may not be null terminated. Therefore it is // typically a mistake to pass data() to a routine that expects a NUL // terminated string. const char* data() const { return ptr_; } stringpiece_ssize_type size() const { return length_; } stringpiece_ssize_type length() const { return length_; } bool empty() const { return length_ == 0; } void clear() { ptr_ = nullptr; length_ = 0; } void set(const char* data, stringpiece_ssize_type len) { assert(len >= 0); ptr_ = data; length_ = len; } void set(const char* str) { ptr_ = str; if (str != nullptr) length_ = CheckedSsizeTFromSizeT(strlen(str)); else length_ = 0; } void set(const void* data, stringpiece_ssize_type len) { ptr_ = reinterpret_cast<const char*>(data); length_ = len; } char operator[](stringpiece_ssize_type i) const { assert(0 <= i); assert(i < length_); return ptr_[i]; } void remove_prefix(stringpiece_ssize_type n) { assert(length_ >= n); ptr_ += n; length_ -= n; } void remove_suffix(stringpiece_ssize_type n) { assert(length_ >= n); length_ -= n; } // returns {-1, 0, 1} int compare(StringPiece x) const { const stringpiece_ssize_type min_size = length_ < x.length_ ? length_ : x.length_; int r = memcmp(ptr_, x.ptr_, static_cast<size_t>(min_size)); if (r < 0) return -1; if (r > 0) return 1; if (length_ < x.length_) return -1; if (length_ > x.length_) return 1; return 0; } std::string as_string() const { return ToString(); } // We also define ToString() here, since many other string-like // interfaces name the routine that converts to a C++ string // "ToString", and it's confusing to have the method that does that // for a StringPiece be called "as_string()". We also leave the // "as_string()" method defined here for existing code. std::string ToString() const { if (ptr_ == nullptr) return ""; return std::string(data(), static_cast<size_type>(size())); } explicit operator std::string() const { return ToString(); } void CopyToString(std::string* target) const; void AppendToString(std::string* target) const; bool starts_with(StringPiece x) const { return (length_ >= x.length_) && (memcmp(ptr_, x.ptr_, static_cast<size_t>(x.length_)) == 0); } bool ends_with(StringPiece x) const { return ((length_ >= x.length_) && (memcmp(ptr_ + (length_-x.length_), x.ptr_, static_cast<size_t>(x.length_)) == 0)); } // Checks whether StringPiece starts with x and if so advances the beginning // of it to past the match. It's basically a shortcut for starts_with // followed by remove_prefix. bool Consume(StringPiece x); // Like above but for the end of the string. bool ConsumeFromEnd(StringPiece x); // standard STL container boilerplate typedef char value_type; typedef const char* pointer; typedef const char& reference; typedef const char& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; static const size_type npos; typedef const char* const_iterator; typedef const char* iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; iterator begin() const { return ptr_; } iterator end() const { return ptr_ + length_; } const_reverse_iterator rbegin() const { return const_reverse_iterator(ptr_ + length_); } const_reverse_iterator rend() const { return const_reverse_iterator(ptr_); } stringpiece_ssize_type max_size() const { return length_; } stringpiece_ssize_type capacity() const { return length_; } // cpplint.py emits a false positive [build/include_what_you_use] stringpiece_ssize_type copy(char* buf, size_type n, size_type pos = 0) const; // NOLINT bool contains(StringPiece s) const; stringpiece_ssize_type find(StringPiece s, size_type pos = 0) const; stringpiece_ssize_type find(char c, size_type pos = 0) const; stringpiece_ssize_type rfind(StringPiece s, size_type pos = npos) const; stringpiece_ssize_type rfind(char c, size_type pos = npos) const; stringpiece_ssize_type find_first_of(StringPiece s, size_type pos = 0) const; stringpiece_ssize_type find_first_of(char c, size_type pos = 0) const { return find(c, pos); } stringpiece_ssize_type find_first_not_of(StringPiece s, size_type pos = 0) const; stringpiece_ssize_type find_first_not_of(char c, size_type pos = 0) const; stringpiece_ssize_type find_last_of(StringPiece s, size_type pos = npos) const; stringpiece_ssize_type find_last_of(char c, size_type pos = npos) const { return rfind(c, pos); } stringpiece_ssize_type find_last_not_of(StringPiece s, size_type pos = npos) const; stringpiece_ssize_type find_last_not_of(char c, size_type pos = npos) const; StringPiece substr(size_type pos, size_type n = npos) const; }; // This large function is defined inline so that in a fairly common case where // one of the arguments is a literal, the compiler can elide a lot of the // following comparisons. inline bool operator==(StringPiece x, StringPiece y) { stringpiece_ssize_type len = x.size(); if (len != y.size()) { return false; } return x.data() == y.data() || len <= 0 || memcmp(x.data(), y.data(), static_cast<size_t>(len)) == 0; } inline bool operator!=(StringPiece x, StringPiece y) { return !(x == y); } inline bool operator<(StringPiece x, StringPiece y) { const stringpiece_ssize_type min_size = x.size() < y.size() ? x.size() : y.size(); const int r = memcmp(x.data(), y.data(), static_cast<size_t>(min_size)); return (r < 0) || (r == 0 && x.size() < y.size()); } inline bool operator>(StringPiece x, StringPiece y) { return y < x; } inline bool operator<=(StringPiece x, StringPiece y) { return !(x > y); } inline bool operator>=(StringPiece x, StringPiece y) { return !(x < y); } // allow StringPiece to be logged extern std::ostream& operator<<(std::ostream& o, StringPiece piece); namespace internal { // StringPiece is not a POD and can not be used in an union (pre C++11). We // need a POD version of it. struct StringPiecePod { // Create from a StringPiece. static StringPiecePod CreateFromStringPiece(StringPiece str) { StringPiecePod pod; pod.data_ = str.data(); pod.size_ = str.size(); return pod; } // Cast to StringPiece. operator StringPiece() const { return StringPiece(data_, size_); } bool operator==(const char* value) const { return StringPiece(data_, size_) == StringPiece(value); } char operator[](stringpiece_ssize_type i) const { assert(0 <= i); assert(i < size_); return data_[i]; } const char* data() const { return data_; } stringpiece_ssize_type size() const { return size_; } std::string ToString() const { return std::string(data_, static_cast<size_t>(size_)); } explicit operator std::string() const { return ToString(); } private: const char* data_; stringpiece_ssize_type size_; }; } // namespace internal } // namespace protobuf } // namespace google GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START template<> struct hash<StringPiece> { size_t operator()(const StringPiece& s) const { size_t result = 0; for (const char *str = s.data(), *end = str + s.size(); str < end; str++) { result = 5 * result + static_cast<size_t>(*str); } return result; } }; GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END #include <google/protobuf/port_undef.inc> #endif // STRINGS_STRINGPIECE_H_
17,861
35.453061
90
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/stringprintf.h
// Protocol Buffers - Google's data interchange format // Copyright 2012 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // from google3/base/stringprintf.h // // Printf variants that place their output in a C++ string. // // Usage: // string result = StringPrintf("%d %s\n", 10, "hello"); // SStringPrintf(&result, "%d %s\n", 10, "hello"); // StringAppendF(&result, "%d %s\n", 20, "there"); #ifndef GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H #define GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H #include <stdarg.h> #include <string> #include <vector> #include <google/protobuf/stubs/common.h> #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { // Return a C++ string PROTOBUF_EXPORT extern std::string StringPrintf(const char* format, ...); // Store result into a supplied string and return it PROTOBUF_EXPORT extern const std::string& SStringPrintf(std::string* dst, const char* format, ...); // Append result to a supplied string PROTOBUF_EXPORT extern void StringAppendF(std::string* dst, const char* format, ...); // Lower-level routine that takes a va_list and appends to a specified // string. All other routines are just convenience wrappers around it. PROTOBUF_EXPORT extern void StringAppendV(std::string* dst, const char* format, va_list ap); // The max arguments supported by StringPrintfVector PROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs; // You can use this version when all your arguments are strings, but // you don't know how many arguments you'll have at compile time. // StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs PROTOBUF_EXPORT extern std::string StringPrintfVector( const char* format, const std::vector<std::string>& v); } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H
3,615
41.046512
79
h
sentencepiece
sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/time.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_STUBS_TIME_H_ #define GOOGLE_PROTOBUF_STUBS_TIME_H_ #include <google/protobuf/stubs/common.h> #include <google/protobuf/port_def.inc> namespace google { namespace protobuf { namespace internal { struct DateTime { int year; int month; int day; int hour; int minute; int second; }; // Converts a timestamp (seconds elapsed since 1970-01-01T00:00:00, could be // negative to represent time before 1970-01-01) to DateTime. Returns false // if the timestamp is not in the range between 0001-01-01T00:00:00 and // 9999-12-31T23:59:59. bool PROTOBUF_EXPORT SecondsToDateTime(int64 seconds, DateTime* time); // Converts DateTime to a timestamp (seconds since 1970-01-01T00:00:00). // Returns false if the DateTime is not valid or is not in the valid range. bool PROTOBUF_EXPORT DateTimeToSeconds(const DateTime& time, int64* seconds); void PROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos); // Formats a time string in RFC3339 format. // // For example, "2015-05-20T13:29:35.120Z". For nanos, 0, 3, 6 or 9 fractional // digits will be used depending on how many are required to represent the exact // value. // // Note that "nanos" must in the range of [0, 999999999]. std::string PROTOBUF_EXPORT FormatTime(int64 seconds, int32 nanos); // Parses a time string. This method accepts RFC3339 date/time string with UTC // offset. For example, "2015-05-20T13:29:35.120-08:00". bool PROTOBUF_EXPORT ParseTime(const std::string& value, int64* seconds, int32* nanos); } // namespace internal } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_STUBS_TIME_H_
3,356
40.444444
80
h
ARES
ARES-master/sn_rejt_estimator.h
/* * File: sn_rejt_estimator.h * Author: sousasag * * Created on December 20, 2012, 3:50 PM */ #ifndef SN_REJT_ESTIMATOR_H #define SN_REJT_ESTIMATOR_H #ifdef __cplusplus extern "C" { #endif #include <string.h> #include <stdio.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_interp.h> #include "filesio.h" #define SMOOTH_NOISE 8 double avg(double* array, long nelem); double median(double* array, long nelem); double stddev(double* array, long nelem); void remove_outlier(double* arrayin, long nin,double* arrayout,long* nout, double out_sigma); double compute_sn_range(double li,double lf,double* lambda, double* flux, long np); double get_rejt(char* tree, double* lambda, double* flux, long np, char* filerejt); double get_rejt_from_sn(double sn); double get_rejt_lambda_file(double lambda, char* filerejt); double get_rejt_lambda_file(double lambda, char*filerejt){ double *lambdavec, *rejtvec; double cdelta1mean=0; double crval1=0; long npoints=0; read_ascii_file(filerejt, &npoints, &rejtvec, &lambdavec, &cdelta1mean, &crval1); /* int i; for (i=0; i<npoints;i++){ printf("%d - %f - %f\n", i,lambdavec [i], rejtvec[i]); } */ gsl_interp *interpolation = gsl_interp_alloc (gsl_interp_linear,npoints); gsl_interp_init(interpolation, lambdavec, rejtvec, npoints); gsl_interp_accel * accelerator = gsl_interp_accel_alloc(); double rejt_lambda = gsl_interp_eval(interpolation,lambdavec, rejtvec, lambda, accelerator); // printf("%f - %f \n",lambda,rejt_lambda); gsl_interp_free (interpolation); gsl_interp_accel_free (accelerator); free(lambdavec); free(rejtvec); return rejt_lambda; } double get_rejt_from_sn(double sn){ return 1.-(1./sn); } double get_rejt(char* tree, double* lambda, double* flux, long np, char* filerejt){ double rejt=0; char* pch; int i; if (strchr(tree, ';') == NULL){ // do stuff rejt=atof(tree); if (rejt >= 1) rejt=get_rejt_from_sn((double)rejt); printf("Computed rejt: %f \n", rejt); } else { char temp[200]; strcpy(temp, tree); printf("Tree: %s\n",temp); pch = strtok (temp,";"); int nranges=atoi(pch); if ( nranges == -2 ) { printf("Using specific file for rejt dependence on wavelength.\n"); pch = strtok (NULL,"' "); strcpy(filerejt, pch); pch = strtok (NULL, "' "); return nranges; } printf("Computing rejt for spectrum..."); printf("Nranges: %d\n", nranges); double snvec[nranges]; double snmax=0; for (i=0;i<nranges;i++){ pch = strtok (NULL,","); double li=atof(pch); pch = strtok (NULL,","); double lf=atof(pch); // printf("Range %d: [%f - %f]\n",i,li,lf); snvec[i]=compute_sn_range(li,lf,lambda,flux,np); printf("Range %d: [%f - %f] : SN: %f\n",i,li,lf,snvec[i]); if (snvec[i] > snmax) snmax=snvec[i]; } int ranges_valid=0; for (i=0; i<nranges; i++){ snvec[ranges_valid]=snvec[i]; if (snvec[ranges_valid] > 0) ranges_valid++; } // printf("Ranges Valid: %d\n",ranges_valid); double mediansn=median(snvec,ranges_valid); printf("Median SN: %f\n", mediansn); // printf("Max SN: %f\n", snmax); rejt=get_rejt_from_sn(mediansn); } return rejt; } double compute_sn_range(double li,double lf,double* lambda, double* flux, long np){ double sn=-1.0; if ( lambda[0] < li && lf < lambda[np-1]){ long pi=find_pixel_line(lambda, np, li); long pf=find_pixel_line(lambda, np, lf); long npr=pf-pi; double fluxrange[npr],lambdarange[npr],fluxrangesmooth[npr],noise[npr],temp[npr],noise_clean[npr]; arraysubcp(fluxrange,flux,pi,pf); arraysubcp(lambdarange,lambda,pi,pf); smooth(fluxrange,npr,SMOOTH_NOISE,fluxrangesmooth); double average=avg(fluxrange,npr); int i; for (i=0;i<npr;i++) noise[i]=fluxrange[i]-fluxrangesmooth[i]+average; long n_clean=0; average=avg(noise,npr); double sigma=stddev(noise,npr); // printf("Average: %f , Stddev: %f , SN: %f \n",average, sigma, average/sigma); // remove_outlier(noise,npr,noise_clean,&n_clean,2.0); // average=avg(noise_clean,n_clean); // sigma=stddev(noise_clean,n_clean); // printf("Average: %f , Stddev: %f , SN: %f \n",average, sigma, average/sigma); sn=average/sigma; } else { sn=-1.0; } return sn; } double avg(double* array, long nelem) { return gsl_stats_mean(array, 1, nelem); } double median(double* array, long nelem){ gsl_sort(array, 1, nelem); return gsl_stats_median_from_sorted_data(array,1,nelem); } double stddev(double* array, long nelem){ return sqrt(gsl_stats_variance(array, 1,nelem)); } void remove_outlier(double* arrayin, long nin,double* arrayout,long* nout, double out_sigma){ double meanvec=avg(arrayin,nin); double sigmavec=stddev(arrayin,nin); long i; long ind=0; double out=out_sigma*sigmavec; for (i=0; i<nin; i++){ if ( fabs(arrayin[i]-meanvec) <= out) { arrayout[ind]=arrayin[i]; ind++; } } // printf("Total Points: %ld Pontos in: %ld Pontos out: %ld\n",nin, ind, nin-ind); *nout=ind; } #ifdef __cplusplus } #endif #endif /* SN_REJT_ESTIMATOR_H */
5,565
28.924731
106
h
LargeVis
LargeVis-master/Linux/ANNOY/annoylib.h
// Copyright (c) 2013 Spotify AB // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #ifndef ANNOYLIB_H #define ANNOYLIB_H #include <stdio.h> #include <string> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <stddef.h> #include <stdint.h> //#include "mman.h" //#include <Windows.h> #include <sys/mman.h> #include <string.h> #include <math.h> #include <vector> #include <algorithm> #include <queue> #include <limits> // This allows others to supply their own logger / error printer without // requiring Annoy to import their headers. See RcppAnnoy for a use case. #ifndef __ERROR_PRINTER_OVERRIDE__ #define showUpdate(...) { fprintf(stderr, __VA_ARGS__ ); } #else #define showUpdate(...) { __ERROR_PRINTER_OVERRIDE__( __VA_ARGS__ ); } #endif #ifndef ANNOY_NODE_ATTRIBUTE #define ANNOY_NODE_ATTRIBUTE __attribute__((__packed__)) // TODO: this is turned on by default, but may not work for all architectures! Need to investigate. #endif using std::vector; using std::string; using std::pair; using std::numeric_limits; using std::make_pair; struct RandRandom { // Default implementation of annoy-specific random number generator that uses rand() from standard library. // Owned by the AnnoyIndex, passed around to the distance metrics inline int flip() { // Draw random 0 or 1 return rand() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return rand() % n; } }; template<typename T> inline T get_norm(T* v, int f) { T sq_norm = 0; for (int z = 0; z < f; z++) sq_norm += v[z] * v[z]; return sqrt(sq_norm); } template<typename T> inline void normalize(T* v, int f) { T norm = get_norm(v, f); for (int z = 0; z < f; z++) v[z] /= norm; } template<typename S, typename T, class Random> struct Angular { struct /*ANNOY_NODE_ATTRIBUTE*/ Node { /* * We store a binary tree where each node has two things * - A vector associated with it * - Two children * All nodes occupy the same amount of memory * All nodes with n_descendants == 1 are leaf nodes. * A memory optimization is that for nodes with 2 <= n_descendants <= K, * we skip the vector. Instead we store a list of all descendants. K is * determined by the number of items that fits in the space of the vector. * For nodes with n_descendants == 1 the vector is a data point. * For nodes with n_descendants > K the vector is the normal of the split plane. * Note that we can't really do sizeof(node<T>) because we cheat and allocate * more memory to be able to fit the vector outside */ S n_descendants; S children[2]; // Will possibly store more than 2 T v[1]; // We let this one overflow intentionally. Need to allocate at least 1 to make GCC happy }; static inline T distance(const T* x, const T* y, int f) { // want to calculate (a/|a| - b/|b|)^2 // = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b| // = 2 - 2cos T pp = 0, qq = 0, pq = 0; for (int z = 0; z < f; z++, x++, y++) { pp += (*x) * (*x); qq += (*y) * (*y); pq += (*x) * (*y); } T ppqq = pp * qq; if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq); else return 2.0; // cos is 0 } static inline T margin(const Node* n, const T* y, int f) { T dot = 0; for (int z = 0; z < f; z++) dot += n->v[z] * y[z]; return dot; } static inline bool side(const Node* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } static inline void create_split(const vector<Node*>& nodes, int f, Random& random, Node* n) { // Sample two random points from the set of nodes // Calculate the hyperplane equidistant from them size_t count = nodes.size(); size_t i = random.index(count); size_t j = random.index(count-1); j += (j >= i); // ensure that i != j T* iv = nodes[i]->v; T* jv = nodes[j]->v; T i_norm = get_norm(iv, f); T j_norm = get_norm(jv, f); for (int z = 0; z < f; z++) n->v[z] = iv[z] / i_norm - jv[z] / j_norm; normalize(n->v, f); } static inline T normalized_distance(T distance) { // Used when requesting distances from Python layer return sqrt(distance); } }; template<typename S, typename T, class Random> struct Euclidean { struct /*ANNOY_NODE_ATTRIBUTE*/ Node { S n_descendants; T a; // need an extra constant term to determine the offset of the plane S children[2]; T v[1]; }; static inline T distance(const T* x, const T* y, int f) { T d = 0.0; for (int i = 0; i < f; i++, x++, y++) d += ((*x) - (*y)) * ((*x) - (*y)); return d; } static inline T margin(const Node* n, const T* y, int f) { T dot = n->a; for (int z = 0; z < f; z++) dot += n->v[z] * y[z]; return dot; } static inline bool side(const Node* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } static inline void create_split(const vector<Node*>& nodes, int f, Random& random, Node* n) { // Same as Angular version, but no normalization and has to compute the offset too size_t count = nodes.size(); size_t i = random.index(count); size_t j = random.index(count-1); j += (j >= i); // ensure that i != j T* iv = nodes[i]->v; T* jv = nodes[j]->v; n->a = 0.0; for (int z = 0; z < f; z++) { n->v[z] = iv[z] - jv[z]; n->a += -n->v[z] * (iv[z] + jv[z]) / 2; } } static inline T normalized_distance(T distance) { return sqrt(distance); } }; template<typename S, typename T> class AnnoyIndexInterface { public: virtual ~AnnoyIndexInterface() {}; virtual void add_item(S item, const T* w) = 0; virtual void build(int q) = 0; virtual bool save(const char* filename) = 0; virtual void reinitialize() = 0; virtual void unload() = 0; virtual bool load(const char* filename) = 0; virtual T get_distance(S i, S j) = 0; virtual void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) = 0; virtual void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) = 0; virtual S get_n_items() = 0; virtual void verbose(bool v) = 0; virtual void get_item(S item, vector<T>* v) = 0; }; template<typename S, typename T, template<typename, typename, typename> class Distance, class Random> class AnnoyIndex : public AnnoyIndexInterface<S, T> { /* * We use random projection to build a forest of binary trees of all items. * Basically just split the hyperspace into two sides by a hyperplane, * then recursively split each of those subtrees etc. * We create a tree like this q times. The default q is determined automatically * in such a way that we at most use 2x as much memory as the vectors take. */ protected: typedef Distance<S, T, Random> D; typedef typename D::Node Node; int _f; size_t _s; S _n_items; Random _random; void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate S _n_nodes; S _nodes_size; vector<S> _roots; S _K; bool _loaded; bool _verbose; public: AnnoyIndex(int f) : _random() { _f = f; _s = offsetof(Node, v) + f * sizeof(T); // Size of each node _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _loaded = false; _verbose = false; _K = (_s - offsetof(Node, children)) / sizeof(S); // Max number of descendants to fit into node } ~AnnoyIndex() { if (_loaded) { unload(); } else if(_nodes) { free(_nodes); } } void add_item(S item, const T* w) { _allocate_size(item + 1); Node* n = _get(item); n->children[0] = 0; n->children[1] = 0; n->n_descendants = 1; for (int z = 0; z < _f; z++) n->v[z] = w[z]; if (item >= _n_items) _n_items = item + 1; } void build(int q) { _n_nodes = _n_items; while (1) { if (q == -1 && _n_nodes >= _n_items * 2) break; if (q != -1 && _roots.size() >= (size_t)q) break; if (_verbose) showUpdate("pass %zd...\n", _roots.size()); vector<S> indices; for (S i = 0; i < _n_items; i++) indices.push_back(i); _roots.push_back(_make_tree(indices)); } // Also, copy the roots into the last segment of the array // This way we can load them faster without reading the whole file _allocate_size(_n_nodes + (S)_roots.size()); for (size_t i = 0; i < _roots.size(); i++) memcpy(_get(_n_nodes + (S)i), _get(_roots[i]), _s); _n_nodes += _roots.size(); if (_verbose) showUpdate("has %d nodes\n", _n_nodes); } bool save(const char* filename) { FILE *f = fopen(filename, "wb"); if (f == NULL) return false; //fwrite(_nodes, _s, _n_nodes, f); for (long long i = 0; i < _n_nodes; ++i) fwrite((void*)((char*)_nodes + i * _s), _s, 1, f); fclose(f); free(_nodes); _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _roots.clear(); return load(filename); } void reinitialize() { _nodes = NULL; _loaded = false; _n_items = 0; _n_nodes = 0; _nodes_size = 0; _roots.clear(); } void unload() { off_t size = _n_nodes * _s; munmap(_nodes, size); reinitialize(); if (_verbose) showUpdate("unloaded\n"); } bool load(const char* filename) { int fd = open(filename, O_RDONLY, (int)0400); if (fd == -1) return false; long long size = lseek64(fd, 0, SEEK_END); // printf("File size %lld\n", size); #ifdef MAP_POPULATE _nodes = (Node*)mmap( 0, size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0); #else _nodes = (Node*)mmap( 0, size, PROT_READ, MAP_SHARED, fd, 0); #endif _n_nodes = (S)(size / _s); // Find the roots by scanning the end of the file and taking the nodes with most descendants S m = -1; for (S i = _n_nodes - 1; i >= 0; i--) { S k = _get(i)->n_descendants; if (m == -1 || k == m) { _roots.push_back(i); m = k; } else { break; } } _loaded = true; _n_items = m; if (_verbose) showUpdate("found %lu roots with degree %d\n", _roots.size(), m); return true; } T get_distance(S i, S j) { const T* x = _get(i)->v; const T* y = _get(j)->v; return D::distance(x, y, _f); } void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) { const Node* m = _get(item); _get_all_nns(m->v, n, search_k, result, distances); } void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) { _get_all_nns(w, n, search_k, result, distances); } S get_n_items() { return _n_items; } void verbose(bool v) { _verbose = v; } void get_item(S item, vector<T>* v) { Node* m = _get(item); for (int z = 0; z < _f; z++) v->push_back(m->v[z]); } protected: void _allocate_size(S n) { if (n > _nodes_size) { S new_nodes_size = (_nodes_size + 1) * 2; if (n > new_nodes_size) new_nodes_size = n; _nodes = realloc(_nodes, _s * new_nodes_size); memset((char *)_nodes + (_nodes_size * _s)/sizeof(char), 0, (new_nodes_size - _nodes_size) * _s); _nodes_size = new_nodes_size; } } inline Node* _get(S i) { return (Node*)((uint8_t *)_nodes + (_s * i)); } S _make_tree(const vector<S >& indices) { if (indices.size() == 1) return indices[0]; if (indices.size() <= (size_t)_K) { _allocate_size(_n_nodes + 1); S item = _n_nodes++; Node* m = _get(item); m->n_descendants = (S)indices.size(); // Using std::copy instead of a loop seems to resolve issues #3 and #13, // probably because gcc 4.8 goes overboard with optimizations. copy(indices.begin(), indices.end(), m->children); return item; } Node* m = (Node*)malloc(_s); // TODO: avoid vector<S> children_indices[2]; for (int attempt = 0; attempt < 20; attempt ++) { /* * Create a random hyperplane. * If all points end up on the same time, we try again. * We could in principle *construct* a plane so that we split * all items evenly, but I think that could violate the guarantees * given by just picking a hyperplane at random */ vector<Node*> children; for (size_t i = 0; i < indices.size(); i++) { // TODO: this loop isn't needed for the angular distance, because // we can just split by a random vector and it's fine. For Euclidean // distance we need it to calculate the offset S j = indices[i]; Node* n = _get(j); if (n) children.push_back(n); } D::create_split(children, _f, _random, m); children_indices[0].clear(); children_indices[1].clear(); for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; Node* n = _get(j); if (n) { bool side = D::side(m, n->v, _f, _random); children_indices[side].push_back(j); } } if (children_indices[0].size() > 0 && children_indices[1].size() > 0) { break; } } while (children_indices[0].size() == 0 || children_indices[1].size() == 0) { // If we didn't find a hyperplane, just randomize sides as a last option if (_verbose && indices.size() > 100000) showUpdate("Failed splitting %lu items\n", indices.size()); children_indices[0].clear(); children_indices[1].clear(); // Set the vector to 0.0 for (int z = 0; z < _f; z++) m->v[z] = 0.0; for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; // Just randomize... children_indices[_random.flip()].push_back(j); } } int flip = (children_indices[0].size() > children_indices[1].size()); m->n_descendants = (S)indices.size(); for (int side = 0; side < 2; side++) // run _make_tree for the smallest child first (for cache locality) m->children[side^flip] = _make_tree(children_indices[side^flip]); _allocate_size(_n_nodes + 1); S item = _n_nodes++; memcpy(_get(item), m, _s); free(m); return item; } void _get_all_nns(const T* v, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) { std::priority_queue<pair<T, S> > q; if (search_k == (size_t)-1) search_k = n * _roots.size(); // slightly arbitrary default value for (size_t i = 0; i < _roots.size(); i++) { q.push(make_pair(numeric_limits<T>::infinity(), _roots[i])); } vector<S> nns; while (nns.size() < search_k && !q.empty()) { const pair<T, S>& top = q.top(); T d = top.first; S i = top.second; Node* nd = _get(i); q.pop(); if (nd->n_descendants == 1) { nns.push_back(i); } else if (nd->n_descendants <= _K) { const S* dst = nd->children; nns.insert(nns.end(), dst, &dst[nd->n_descendants]); } else { T margin = D::margin(nd, v, _f); q.push(make_pair((std::min)(d, +margin), nd->children[1])); q.push(make_pair((std::min)(d, -margin), nd->children[0])); } } // Get distances for all items // To avoid calculating distance multiple times for any items, sort by id sort(nns.begin(), nns.end()); vector<pair<T, S> > nns_dist; S last = -1; for (size_t i = 0; i < nns.size(); i++) { S j = nns[i]; if (j == last) continue; last = j; nns_dist.push_back(make_pair(D::distance(v, _get(j)->v, _f), j)); } size_t m = nns_dist.size(); size_t p = n < m ? n : m; // Return this many items std::partial_sort(&nns_dist[0], &nns_dist[p], &nns_dist[m]); for (size_t i = 0; i < p; i++) { if (distances) distances->push_back(D::normalized_distance(nns_dist[i].first)); result->push_back(nns_dist[i].second); } } }; #endif // vim: tabstop=2 shiftwidth=2
16,783
28.65371
117
h
LargeVis
LargeVis-master/Linux/ANNOY/kissrandom.h
#ifndef KISSRANDOM_H #define KISSRANDOM_H #include <stdint.h> // KISS = "keep it simple, stupid", but high quality random number generator // http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf -> "Use a good RNG and build it into your code" // http://mathforum.org/kb/message.jspa?messageID=6627731 // https://de.wikipedia.org/wiki/KISS_(Zufallszahlengenerator) // 32 bit KISS struct Kiss32Random { uint32_t x; uint32_t y; uint32_t z; uint32_t c; // seed must be != 0 Kiss32Random(uint32_t seed = 123456789) { x = seed; y = 362436000; z = 521288629; c = 7654321; } uint32_t kiss() { // Linear congruence generator x = 69069 * x + 12345; // Xor shift y ^= y << 13; y ^= y >> 17; y ^= y << 5; // Multiply-with-carry uint64_t t = 698769069ULL * z + c; c = t >> 32; z = (uint32_t) t; return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } }; // 64 bit KISS. Use this if you have more than about 2^24 data points ("big data" ;) ) struct Kiss64Random { uint64_t x; uint64_t y; uint64_t z; uint64_t c; // seed must be != 0 Kiss64Random(uint64_t seed = 1234567890987654321ULL) { x = seed; y = 362436362436362436ULL; z = 1066149217761810ULL; c = 123456123456123456ULL; } uint64_t kiss() { // Linear congruence generator z = 6906969069LL*z+1234567; // Xor shift y ^= (y<<13); y ^= (y>>17); y ^= (y<<43); // Multiply-with-carry (uint128_t t = (2^58 + 1) * x + c; c = t >> 64; x = (uint64_t) t) uint64_t t = (x<<58)+c; c = (x>>6); x += t; c += (x<t); return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } }; #endif // vim: tabstop=2 shiftwidth=2
2,118
21.072917
109
h
LargeVis
LargeVis-master/Windows/ANNOY/annoylib.h
// Copyright (c) 2013 Spotify AB // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #ifndef ANNOYLIB_H #define ANNOYLIB_H #include <stdio.h> #include <string> #include <sys/stat.h> //#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <stddef.h> #include <stdint.h> #include "mman.h" #include <Windows.h> #include <string.h> #include <math.h> #include <vector> #include <algorithm> #include <queue> #include <limits> // This allows others to supply their own logger / error printer without // requiring Annoy to import their headers. See RcppAnnoy for a use case. #ifndef __ERROR_PRINTER_OVERRIDE__ #define showUpdate(...) { fprintf(stderr, __VA_ARGS__ ); } #else #define showUpdate(...) { __ERROR_PRINTER_OVERRIDE__( __VA_ARGS__ ); } #endif #ifndef ANNOY_NODE_ATTRIBUTE #define ANNOY_NODE_ATTRIBUTE __attribute__((__packed__)) // TODO: this is turned on by default, but may not work for all architectures! Need to investigate. #endif using std::vector; using std::string; using std::pair; using std::numeric_limits; using std::make_pair; struct RandRandom { // Default implementation of annoy-specific random number generator that uses rand() from standard library. // Owned by the AnnoyIndex, passed around to the distance metrics inline int flip() { // Draw random 0 or 1 return rand() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return rand() % n; } }; template<typename T> inline T get_norm(T* v, int f) { T sq_norm = 0; for (int z = 0; z < f; z++) sq_norm += v[z] * v[z]; return sqrt(sq_norm); } template<typename T> inline void normalize(T* v, int f) { T norm = get_norm(v, f); for (int z = 0; z < f; z++) v[z] /= norm; } template<typename S, typename T, class Random> struct Angular { struct /*ANNOY_NODE_ATTRIBUTE*/ Node { /* * We store a binary tree where each node has two things * - A vector associated with it * - Two children * All nodes occupy the same amount of memory * All nodes with n_descendants == 1 are leaf nodes. * A memory optimization is that for nodes with 2 <= n_descendants <= K, * we skip the vector. Instead we store a list of all descendants. K is * determined by the number of items that fits in the space of the vector. * For nodes with n_descendants == 1 the vector is a data point. * For nodes with n_descendants > K the vector is the normal of the split plane. * Note that we can't really do sizeof(node<T>) because we cheat and allocate * more memory to be able to fit the vector outside */ S n_descendants; S children[2]; // Will possibly store more than 2 T v[1]; // We let this one overflow intentionally. Need to allocate at least 1 to make GCC happy }; static inline T distance(const T* x, const T* y, int f) { // want to calculate (a/|a| - b/|b|)^2 // = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b| // = 2 - 2cos T pp = 0, qq = 0, pq = 0; for (int z = 0; z < f; z++, x++, y++) { pp += (*x) * (*x); qq += (*y) * (*y); pq += (*x) * (*y); } T ppqq = pp * qq; if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq); else return 2.0; // cos is 0 } static inline T margin(const Node* n, const T* y, int f) { T dot = 0; for (int z = 0; z < f; z++) dot += n->v[z] * y[z]; return dot; } static inline bool side(const Node* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } static inline void create_split(const vector<Node*>& nodes, int f, Random& random, Node* n) { // Sample two random points from the set of nodes // Calculate the hyperplane equidistant from them size_t count = nodes.size(); size_t i = random.index(count); size_t j = random.index(count-1); j += (j >= i); // ensure that i != j T* iv = nodes[i]->v; T* jv = nodes[j]->v; T i_norm = get_norm(iv, f); T j_norm = get_norm(jv, f); for (int z = 0; z < f; z++) n->v[z] = iv[z] / i_norm - jv[z] / j_norm; normalize(n->v, f); } static inline T normalized_distance(T distance) { // Used when requesting distances from Python layer return sqrt(distance); } }; template<typename S, typename T, class Random> struct Euclidean { struct /*ANNOY_NODE_ATTRIBUTE*/ Node { S n_descendants; T a; // need an extra constant term to determine the offset of the plane S children[2]; T v[1]; }; static inline T distance(const T* x, const T* y, int f) { T d = 0.0; for (int i = 0; i < f; i++, x++, y++) d += ((*x) - (*y)) * ((*x) - (*y)); return d; } static inline T margin(const Node* n, const T* y, int f) { T dot = n->a; for (int z = 0; z < f; z++) dot += n->v[z] * y[z]; return dot; } static inline bool side(const Node* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } static inline void create_split(const vector<Node*>& nodes, int f, Random& random, Node* n) { // Same as Angular version, but no normalization and has to compute the offset too size_t count = nodes.size(); size_t i = random.index(count); size_t j = random.index(count-1); j += (j >= i); // ensure that i != j T* iv = nodes[i]->v; T* jv = nodes[j]->v; n->a = 0.0; for (int z = 0; z < f; z++) { n->v[z] = iv[z] - jv[z]; n->a += -n->v[z] * (iv[z] + jv[z]) / 2; } } static inline T normalized_distance(T distance) { return sqrt(distance); } }; template<typename S, typename T> class AnnoyIndexInterface { public: virtual ~AnnoyIndexInterface() {}; virtual void add_item(S item, const T* w) = 0; virtual void build(int q) = 0; virtual bool save(const char* filename) = 0; virtual void reinitialize() = 0; virtual void unload() = 0; virtual bool load(const char* filename) = 0; virtual T get_distance(S i, S j) = 0; virtual void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) = 0; virtual void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) = 0; virtual S get_n_items() = 0; virtual void verbose(bool v) = 0; virtual void get_item(S item, vector<T>* v) = 0; }; template<typename S, typename T, template<typename, typename, typename> class Distance, class Random> class AnnoyIndex : public AnnoyIndexInterface<S, T> { /* * We use random projection to build a forest of binary trees of all items. * Basically just split the hyperspace into two sides by a hyperplane, * then recursively split each of those subtrees etc. * We create a tree like this q times. The default q is determined automatically * in such a way that we at most use 2x as much memory as the vectors take. */ protected: typedef Distance<S, T, Random> D; typedef typename D::Node Node; int _f; size_t _s; S _n_items; Random _random; void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate S _n_nodes; S _nodes_size; vector<S> _roots; S _K; bool _loaded; bool _verbose; public: AnnoyIndex(int f) : _random() { _f = f; _s = offsetof(Node, v) + f * sizeof(T); // Size of each node _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _loaded = false; _verbose = false; _K = (_s - offsetof(Node, children)) / sizeof(S); // Max number of descendants to fit into node } ~AnnoyIndex() { if (_loaded) { unload(); } else if(_nodes) { free(_nodes); } } void add_item(S item, const T* w) { _allocate_size(item + 1); Node* n = _get(item); n->children[0] = 0; n->children[1] = 0; n->n_descendants = 1; for (int z = 0; z < _f; z++) n->v[z] = w[z]; if (item >= _n_items) _n_items = item + 1; } void build(int q) { _n_nodes = _n_items; while (1) { if (q == -1 && _n_nodes >= _n_items * 2) break; if (q != -1 && _roots.size() >= (size_t)q) break; if (_verbose) showUpdate("pass %zd...\n", _roots.size()); vector<S> indices; for (S i = 0; i < _n_items; i++) indices.push_back(i); _roots.push_back(_make_tree(indices)); } // Also, copy the roots into the last segment of the array // This way we can load them faster without reading the whole file _allocate_size(_n_nodes + (S)_roots.size()); for (size_t i = 0; i < _roots.size(); i++) memcpy(_get(_n_nodes + (S)i), _get(_roots[i]), _s); _n_nodes += _roots.size(); if (_verbose) showUpdate("has %d nodes\n", _n_nodes); } bool save(const char* filename) { FILE *f = fopen(filename, "wb"); if (f == NULL) return false; //fwrite(_nodes, _s, _n_nodes, f); for (long long i = 0; i < _n_nodes; ++i) fwrite((void*)((char*)_nodes + i * _s), _s, 1, f); fclose(f); free(_nodes); _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _roots.clear(); return load(filename); } void reinitialize() { _nodes = NULL; _loaded = false; _n_items = 0; _n_nodes = 0; _nodes_size = 0; _roots.clear(); } void unload() { off_t size = _n_nodes * _s; munmap(_nodes, size); reinitialize(); if (_verbose) showUpdate("unloaded\n"); } bool load(const char* filename) { int fd = _open(filename, O_RDONLY, (int)0400); if (fd == -1) return false; long long size = _lseeki64(fd, 0, SEEK_END); // printf("File size %lld\n", size); #ifdef MAP_POPULATE _nodes = (Node*)mmap( 0, size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0); #else _nodes = (Node*)mmap( 0, size, PROT_READ, MAP_SHARED, fd, 0); #endif _n_nodes = (S)(size / _s); // Find the roots by scanning the end of the file and taking the nodes with most descendants S m = -1; for (S i = _n_nodes - 1; i >= 0; i--) { S k = _get(i)->n_descendants; if (m == -1 || k == m) { _roots.push_back(i); m = k; } else { break; } } _loaded = true; _n_items = m; if (_verbose) showUpdate("found %lu roots with degree %d\n", _roots.size(), m); return true; } T get_distance(S i, S j) { const T* x = _get(i)->v; const T* y = _get(j)->v; return D::distance(x, y, _f); } void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) { const Node* m = _get(item); _get_all_nns(m->v, n, search_k, result, distances); } void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) { _get_all_nns(w, n, search_k, result, distances); } S get_n_items() { return _n_items; } void verbose(bool v) { _verbose = v; } void get_item(S item, vector<T>* v) { Node* m = _get(item); for (int z = 0; z < _f; z++) v->push_back(m->v[z]); } protected: void _allocate_size(S n) { if (n > _nodes_size) { S new_nodes_size = (_nodes_size + 1) * 2; if (n > new_nodes_size) new_nodes_size = n; _nodes = realloc(_nodes, _s * new_nodes_size); memset((char *)_nodes + (_nodes_size * _s)/sizeof(char), 0, (new_nodes_size - _nodes_size) * _s); _nodes_size = new_nodes_size; } } inline Node* _get(S i) { return (Node*)((uint8_t *)_nodes + (_s * i)); } S _make_tree(const vector<S >& indices) { if (indices.size() == 1) return indices[0]; if (indices.size() <= (size_t)_K) { _allocate_size(_n_nodes + 1); S item = _n_nodes++; Node* m = _get(item); m->n_descendants = (S)indices.size(); // Using std::copy instead of a loop seems to resolve issues #3 and #13, // probably because gcc 4.8 goes overboard with optimizations. copy(indices.begin(), indices.end(), m->children); return item; } Node* m = (Node*)malloc(_s); // TODO: avoid vector<S> children_indices[2]; for (int attempt = 0; attempt < 20; attempt ++) { /* * Create a random hyperplane. * If all points end up on the same time, we try again. * We could in principle *construct* a plane so that we split * all items evenly, but I think that could violate the guarantees * given by just picking a hyperplane at random */ vector<Node*> children; for (size_t i = 0; i < indices.size(); i++) { // TODO: this loop isn't needed for the angular distance, because // we can just split by a random vector and it's fine. For Euclidean // distance we need it to calculate the offset S j = indices[i]; Node* n = _get(j); if (n) children.push_back(n); } D::create_split(children, _f, _random, m); children_indices[0].clear(); children_indices[1].clear(); for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; Node* n = _get(j); if (n) { bool side = D::side(m, n->v, _f, _random); children_indices[side].push_back(j); } } if (children_indices[0].size() > 0 && children_indices[1].size() > 0) { break; } } while (children_indices[0].size() == 0 || children_indices[1].size() == 0) { // If we didn't find a hyperplane, just randomize sides as a last option if (_verbose && indices.size() > 100000) showUpdate("Failed splitting %lu items\n", indices.size()); children_indices[0].clear(); children_indices[1].clear(); // Set the vector to 0.0 for (int z = 0; z < _f; z++) m->v[z] = 0.0; for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; // Just randomize... children_indices[_random.flip()].push_back(j); } } int flip = (children_indices[0].size() > children_indices[1].size()); m->n_descendants = (S)indices.size(); for (int side = 0; side < 2; side++) // run _make_tree for the smallest child first (for cache locality) m->children[side^flip] = _make_tree(children_indices[side^flip]); _allocate_size(_n_nodes + 1); S item = _n_nodes++; memcpy(_get(item), m, _s); free(m); return item; } void _get_all_nns(const T* v, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) { std::priority_queue<pair<T, S> > q; if (search_k == (size_t)-1) search_k = n * _roots.size(); // slightly arbitrary default value for (size_t i = 0; i < _roots.size(); i++) { q.push(make_pair(numeric_limits<T>::infinity(), _roots[i])); } vector<S> nns; while (nns.size() < search_k && !q.empty()) { const pair<T, S>& top = q.top(); T d = top.first; S i = top.second; Node* nd = _get(i); q.pop(); if (nd->n_descendants == 1) { nns.push_back(i); } else if (nd->n_descendants <= _K) { const S* dst = nd->children; nns.insert(nns.end(), dst, &dst[nd->n_descendants]); } else { T margin = D::margin(nd, v, _f); q.push(make_pair((std::min)(d, +margin), nd->children[1])); q.push(make_pair((std::min)(d, -margin), nd->children[0])); } } // Get distances for all items // To avoid calculating distance multiple times for any items, sort by id sort(nns.begin(), nns.end()); vector<pair<T, S> > nns_dist; S last = -1; for (size_t i = 0; i < nns.size(); i++) { S j = nns[i]; if (j == last) continue; last = j; nns_dist.push_back(make_pair(D::distance(v, _get(j)->v, _f), j)); } size_t m = nns_dist.size(); size_t p = n < m ? n : m; // Return this many items std::partial_sort(&nns_dist[0], &nns_dist[p], &nns_dist[m]); for (size_t i = 0; i < p; i++) { if (distances) distances->push_back(D::normalized_distance(nns_dist[i].first)); result->push_back(nns_dist[i].second); } } }; #endif // vim: tabstop=2 shiftwidth=2
16,762
28.669027
117
h
LargeVis
LargeVis-master/Windows/ANNOY/kissrandom.h
#ifndef KISSRANDOM_H #define KISSRANDOM_H #include <stdint.h> // KISS = "keep it simple, stupid", but high quality random number generator // http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf -> "Use a good RNG and build it into your code" // http://mathforum.org/kb/message.jspa?messageID=6627731 // https://de.wikipedia.org/wiki/KISS_(Zufallszahlengenerator) // 32 bit KISS struct Kiss32Random { uint32_t x; uint32_t y; uint32_t z; uint32_t c; // seed must be != 0 Kiss32Random(uint32_t seed = 123456789) { x = seed; y = 362436000; z = 521288629; c = 7654321; } uint32_t kiss() { // Linear congruence generator x = 69069 * x + 12345; // Xor shift y ^= y << 13; y ^= y >> 17; y ^= y << 5; // Multiply-with-carry uint64_t t = 698769069ULL * z + c; c = t >> 32; z = (uint32_t) t; return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } }; // 64 bit KISS. Use this if you have more than about 2^24 data points ("big data" ;) ) struct Kiss64Random { uint64_t x; uint64_t y; uint64_t z; uint64_t c; // seed must be != 0 Kiss64Random(uint64_t seed = 1234567890987654321ULL) { x = seed; y = 362436362436362436ULL; z = 1066149217761810ULL; c = 123456123456123456ULL; } uint64_t kiss() { // Linear congruence generator z = 6906969069LL*z+1234567; // Xor shift y ^= (y<<13); y ^= (y>>17); y ^= (y<<43); // Multiply-with-carry (uint128_t t = (2^58 + 1) * x + c; c = t >> 64; x = (uint64_t) t) uint64_t t = (x<<58)+c; c = (x>>6); x += t; c += (x<t); return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } }; #endif // vim: tabstop=2 shiftwidth=2
2,118
21.072917
109
h
LargeVis
LargeVis-master/Windows/ANNOY/mman.h
// This is from https://code.google.com/p/mman-win32/ // // Licensed under MIT #ifndef _MMAN_WIN32_H #define _MMAN_WIN32_H #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #include <sys/types.h> #include <windows.h> #include <errno.h> #include <io.h> #define PROT_NONE 0 #define PROT_READ 1 #define PROT_WRITE 2 #define PROT_EXEC 4 #define MAP_FILE 0 #define MAP_SHARED 1 #define MAP_PRIVATE 2 #define MAP_TYPE 0xf #define MAP_FIXED 0x10 #define MAP_ANONYMOUS 0x20 #define MAP_ANON MAP_ANONYMOUS #define MAP_FAILED ((void *)-1) /* Flags for msync. */ #define MS_ASYNC 1 #define MS_SYNC 2 #define MS_INVALIDATE 4 #ifndef FILE_MAP_EXECUTE #define FILE_MAP_EXECUTE 0x0020 #endif static int __map_mman_error(const DWORD err, const int deferr); static DWORD __map_mmap_prot_page(const int prot); static DWORD __map_mmap_prot_file(const int prot); void* mmap(void *addr, size_t len, int prot, int flags, int fildes, long long off); int munmap(void *addr, size_t len); int mprotect(void *addr, size_t len, int prot); int msync(void *addr, size_t len, int flags); int mlock(const void *addr, size_t len); int munlock(const void *addr, size_t len); #endif
1,412
26.173077
104
h
null
qiskit-aer-main/contrib/runtime/aer_runtime_api.h
/** * This code is part of Qiskit. * * (C) Copyright IBM 2022. * * This code is licensed under the Apache License, Version 2.0. You may * obtain a copy of this license in the LICENSE.txt file in the root directory * of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. * * Any modifications or derivative works of this code must retain this * copyright notice, and modified files need to carry a notice indicating * that they have been altered from the originals. */ #include <complex.h> #include <stdint.h> typedef uint_fast64_t uint_t; // construct an aer state void* aer_state(); // initialize aer state void* aer_state_initialize(); // finalize state void aer_state_finalize(void* state); // configure state void aer_state_configure(void* state, char* key, char* value); // allocate qubits and return the first qubit index. // following qubits are indexed with incremented indices. uint_t aer_allocate_qubits(void* state, uint_t num_qubits); // measure qubits uint_t aer_apply_measure(void* state, uint_t* qubits, size_t num_qubits); // return probability of a specific bitstring double aer_probability(void* state, uint_t outcome); // return probability amplitude of a specific bitstring double complex aer_amplitude(void* state, uint_t outcome); // return probability amplitudes // returned pointer must be freed in the caller double complex* aer_release_statevector(void* state); // phase gate void aer_apply_p(void* state, uint_t qubit, double lambda); // Pauli gate: bit-flip or NOT gate void aer_apply_x(void* state, uint_t qubit); // Pauli gate: bit and phase flip void aer_apply_y(void* state, uint_t qubit); // Pauli gate: phase flip void aer_apply_z(void* state, uint_t qubit); // Clifford gate: Hadamard void aer_apply_h(void* state, uint_t qubit); // Clifford gate: sqrt(Z) or S gate void aer_apply_s(void* state, uint_t qubit); // Clifford gate: inverse of sqrt(Z) void aer_apply_sdg(void* state, uint_t qubit); // sqrt(S) or T gate void aer_apply_t(void* state, uint_t qubit); // inverse of sqrt(S) void aer_apply_tdg(void* state, uint_t qubit); // sqrt(NOT) gate void aer_apply_sx(void* state, uint_t qubit); // Rotation around X-axis void aer_apply_rx(void* state, uint_t qubit, double theta); // rotation around Y-axis void aer_apply_ry(void* state, uint_t qubit, double theta); // rotation around Z axis void aer_apply_rz(void* state, uint_t qubit, double theta); // controlled-NOT void aer_apply_cx(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); // controlled-Y void aer_apply_cy(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); // controlled-Z void aer_apply_cz(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); // controlled-phase void aer_apply_cp(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double lambda); // controlled-rx void aer_apply_crx(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta); // controlled-ry void aer_apply_cry(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta); // controlled-rz void aer_apply_crz(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta); // controlled-H void aer_apply_ch(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); // swap void aer_apply_swap(void* state, uint_t qubit0, uint_t qubit1); // Toffoli void aer_apply_ccx(void* state, uint_t qubit0, uint_t qubit1, uint_t qubit2); // controlled-swap void aer_apply_cswap(void* state, uint_t ctrl_qubit, uint_t qubit0, uint_t qubit1); // four parameter controlled-U gate with relative phase γ void aer_apply_cu(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta, double phi, double lambda, double gamma);
3,630
33.254717
123
h
null
qiskit-aer-main/test/runtime/runtime_sample.c
/** * This code is part of Qiskit. * * (C) Copyright IBM 2022. * * This code is licensed under the Apache License, Version 2.0. You may * obtain a copy of this license in the LICENSE.txt file in the root directory * of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. * * Any modifications or derivative works of this code must retain this * copyright notice, and modified files need to carry a notice indicating * that they have been altered from the originals. */ #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <complex.h> #include "aer_runtime_api.h" typedef uint_fast64_t uint_t; int main() { int num_of_qubits = 8; printf("%d-qubits GHZ\n", num_of_qubits); void* state = aer_state(); aer_state_configure(state, "method", "statevector"); aer_state_configure(state, "device", "CPU"); aer_state_configure(state, "precision", "double"); int start_qubit = aer_allocate_qubits(state, num_of_qubits); aer_state_initialize(state); int* qubits = (int*) malloc(sizeof(int) * num_of_qubits); for (int i = 0; i < num_of_qubits; ++i) qubits[i] = start_qubit + i; aer_apply_h(state, qubits[0]); for (int i = 0; i < num_of_qubits - 1; ++i) aer_apply_cx(state, qubits[i], qubits[i + 1]); printf("non-zero probabilities and amplitudes:\n"); for (uint_t i = 0; i < (1UL << num_of_qubits); ++i) { double prob = aer_probability(state, i); if (prob > 0.0) { double complex amp = aer_amplitude(state, i); printf(" %08lx %lf [%lf, %lf]\n", i, prob, creal(amp), cimag(amp)); } } printf("all the amplitudes:\n"); double complex* sv = aer_release_statevector(state); for (uint_t i = 0; i < (1UL << num_of_qubits); ++i) { printf(" %08lx [%lf, %lf]\n", i, creal(sv[i]), cimag(sv[i])); } aer_state_finalize(state); free(qubits); free(sv); printf("finish\n"); return 0; }
1,909
26.285714
78
c
OpenCC
OpenCC-master/deps/google-benchmark/include/benchmark/export.h
#ifndef BENCHMARK_EXPORT_H #define BENCHMARK_EXPORT_H #if defined(_WIN32) #define EXPORT_ATTR __declspec(dllexport) #define IMPORT_ATTR __declspec(dllimport) #define NO_EXPORT_ATTR #define DEPRECATED_ATTR __declspec(deprecated) #else // _WIN32 #define EXPORT_ATTR __attribute__((visibility("default"))) #define IMPORT_ATTR __attribute__((visibility("default"))) #define NO_EXPORT_ATTR __attribute__((visibility("hidden"))) #define DEPRECATE_ATTR __attribute__((__deprecated__)) #endif // _WIN32 #ifdef BENCHMARK_STATIC_DEFINE #define BENCHMARK_EXPORT #define BENCHMARK_NO_EXPORT #else // BENCHMARK_STATIC_DEFINE #ifndef BENCHMARK_EXPORT #ifdef benchmark_EXPORTS /* We are building this library */ #define BENCHMARK_EXPORT EXPORT_ATTR #else // benchmark_EXPORTS /* We are using this library */ #define BENCHMARK_EXPORT IMPORT_ATTR #endif // benchmark_EXPORTS #endif // !BENCHMARK_EXPORT #ifndef BENCHMARK_NO_EXPORT #define BENCHMARK_NO_EXPORT NO_EXPORT_ATTR #endif // !BENCHMARK_NO_EXPORT #endif // BENCHMARK_STATIC_DEFINE #ifndef BENCHMARK_DEPRECATED #define BENCHMARK_DEPRECATED DEPRECATE_ATTR #endif // BENCHMARK_DEPRECATED #ifndef BENCHMARK_DEPRECATED_EXPORT #define BENCHMARK_DEPRECATED_EXPORT BENCHMARK_EXPORT BENCHMARK_DEPRECATED #endif // BENCHMARK_DEPRECATED_EXPORT #ifndef BENCHMARK_DEPRECATED_NO_EXPORT #define BENCHMARK_DEPRECATED_NO_EXPORT BENCHMARK_NO_EXPORT BENCHMARK_DEPRECATED #endif // BENCHMARK_DEPRECATED_EXPORT #endif /* BENCHMARK_EXPORT_H */
1,481
29.875
79
h
OpenCC
OpenCC-master/deps/google-benchmark/src/arraysize.h
#ifndef BENCHMARK_ARRAYSIZE_H_ #define BENCHMARK_ARRAYSIZE_H_ #include "internal_macros.h" namespace benchmark { namespace internal { // The arraysize(arr) macro returns the # of elements in an array arr. // The expression is a compile-time constant, and therefore can be // used in defining new arrays, for example. If you use arraysize on // a pointer by mistake, you will get a compile-time error. // // This template function declaration is used in defining arraysize. // Note that the function doesn't need an implementation, as we only // use its type. template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; // That gcc wants both of these prototypes seems mysterious. VC, for // its part, can't decide which to use (another mystery). Matching of // template overloads: the final frontier. #ifndef COMPILER_MSVC template <typename T, size_t N> char (&ArraySizeHelper(const T (&array)[N]))[N]; #endif #define arraysize(array) (sizeof(::benchmark::internal::ArraySizeHelper(array))) } // end namespace internal } // end namespace benchmark #endif // BENCHMARK_ARRAYSIZE_H_
1,108
31.617647
80
h
OpenCC
OpenCC-master/deps/google-benchmark/src/benchmark_api_internal.h
#ifndef BENCHMARK_API_INTERNAL_H #define BENCHMARK_API_INTERNAL_H #include <cmath> #include <iosfwd> #include <limits> #include <memory> #include <string> #include <vector> #include "benchmark/benchmark.h" #include "commandlineflags.h" namespace benchmark { namespace internal { // Information kept per benchmark we may want to run class BenchmarkInstance { public: BenchmarkInstance(Benchmark* benchmark, int family_index, int per_family_instance_index, const std::vector<int64_t>& args, int threads); const BenchmarkName& name() const { return name_; } int family_index() const { return family_index_; } int per_family_instance_index() const { return per_family_instance_index_; } AggregationReportMode aggregation_report_mode() const { return aggregation_report_mode_; } TimeUnit time_unit() const { return time_unit_; } bool measure_process_cpu_time() const { return measure_process_cpu_time_; } bool use_real_time() const { return use_real_time_; } bool use_manual_time() const { return use_manual_time_; } BigO complexity() const { return complexity_; } BigOFunc* complexity_lambda() const { return complexity_lambda_; } const std::vector<Statistics>& statistics() const { return statistics_; } int repetitions() const { return repetitions_; } double min_time() const { return min_time_; } double min_warmup_time() const { return min_warmup_time_; } IterationCount iterations() const { return iterations_; } int threads() const { return threads_; } void Setup() const; void Teardown() const; State Run(IterationCount iters, int thread_id, internal::ThreadTimer* timer, internal::ThreadManager* manager, internal::PerfCountersMeasurement* perf_counters_measurement) const; private: BenchmarkName name_; Benchmark& benchmark_; const int family_index_; const int per_family_instance_index_; AggregationReportMode aggregation_report_mode_; const std::vector<int64_t>& args_; TimeUnit time_unit_; bool measure_process_cpu_time_; bool use_real_time_; bool use_manual_time_; BigO complexity_; BigOFunc* complexity_lambda_; UserCounters counters_; const std::vector<Statistics>& statistics_; int repetitions_; double min_time_; double min_warmup_time_; IterationCount iterations_; int threads_; // Number of concurrent threads to us typedef void (*callback_function)(const benchmark::State&); callback_function setup_ = nullptr; callback_function teardown_ = nullptr; }; bool FindBenchmarksInternal(const std::string& re, std::vector<BenchmarkInstance>* benchmarks, std::ostream* Err); bool IsZero(double n); BENCHMARK_EXPORT ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false); } // end namespace internal } // end namespace benchmark #endif // BENCHMARK_API_INTERNAL_H
2,923
32.227273
80
h
OpenCC
OpenCC-master/deps/google-benchmark/src/benchmark_register.h
#ifndef BENCHMARK_REGISTER_H #define BENCHMARK_REGISTER_H #include <algorithm> #include <limits> #include <vector> #include "check.h" namespace benchmark { namespace internal { // Append the powers of 'mult' in the closed interval [lo, hi]. // Returns iterator to the start of the inserted range. template <typename T> typename std::vector<T>::iterator AddPowers(std::vector<T>* dst, T lo, T hi, int mult) { BM_CHECK_GE(lo, 0); BM_CHECK_GE(hi, lo); BM_CHECK_GE(mult, 2); const size_t start_offset = dst->size(); static const T kmax = std::numeric_limits<T>::max(); // Space out the values in multiples of "mult" for (T i = static_cast<T>(1); i <= hi; i *= static_cast<T>(mult)) { if (i >= lo) { dst->push_back(i); } // Break the loop here since multiplying by // 'mult' would move outside of the range of T if (i > kmax / mult) break; } return dst->begin() + static_cast<int>(start_offset); } template <typename T> void AddNegatedPowers(std::vector<T>* dst, T lo, T hi, int mult) { // We negate lo and hi so we require that they cannot be equal to 'min'. BM_CHECK_GT(lo, std::numeric_limits<T>::min()); BM_CHECK_GT(hi, std::numeric_limits<T>::min()); BM_CHECK_GE(hi, lo); BM_CHECK_LE(hi, 0); // Add positive powers, then negate and reverse. // Casts necessary since small integers get promoted // to 'int' when negating. const auto lo_complement = static_cast<T>(-lo); const auto hi_complement = static_cast<T>(-hi); const auto it = AddPowers(dst, hi_complement, lo_complement, mult); std::for_each(it, dst->end(), [](T& t) { t *= -1; }); std::reverse(it, dst->end()); } template <typename T> void AddRange(std::vector<T>* dst, T lo, T hi, int mult) { static_assert(std::is_integral<T>::value && std::is_signed<T>::value, "Args type must be a signed integer"); BM_CHECK_GE(hi, lo); BM_CHECK_GE(mult, 2); // Add "lo" dst->push_back(lo); // Handle lo == hi as a special case, so we then know // lo < hi and so it is safe to add 1 to lo and subtract 1 // from hi without falling outside of the range of T. if (lo == hi) return; // Ensure that lo_inner <= hi_inner below. if (lo + 1 == hi) { dst->push_back(hi); return; } // Add all powers of 'mult' in the range [lo+1, hi-1] (inclusive). const auto lo_inner = static_cast<T>(lo + 1); const auto hi_inner = static_cast<T>(hi - 1); // Insert negative values if (lo_inner < 0) { AddNegatedPowers(dst, lo_inner, std::min(hi_inner, T{-1}), mult); } // Treat 0 as a special case (see discussion on #762). if (lo < 0 && hi >= 0) { dst->push_back(0); } // Insert positive values if (hi_inner > 0) { AddPowers(dst, std::max(lo_inner, T{1}), hi_inner, mult); } // Add "hi" (if different from last value). if (hi != dst->back()) { dst->push_back(hi); } } } // namespace internal } // namespace benchmark #endif // BENCHMARK_REGISTER_H
3,006
26.336364
76
h
OpenCC
OpenCC-master/deps/google-benchmark/src/benchmark_runner.h
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef BENCHMARK_RUNNER_H_ #define BENCHMARK_RUNNER_H_ #include <thread> #include <vector> #include "benchmark_api_internal.h" #include "internal_macros.h" #include "perf_counters.h" #include "thread_manager.h" namespace benchmark { BM_DECLARE_double(benchmark_min_time); BM_DECLARE_double(benchmark_min_warmup_time); BM_DECLARE_int32(benchmark_repetitions); BM_DECLARE_bool(benchmark_report_aggregates_only); BM_DECLARE_bool(benchmark_display_aggregates_only); BM_DECLARE_string(benchmark_perf_counters); namespace internal { extern MemoryManager* memory_manager; struct RunResults { std::vector<BenchmarkReporter::Run> non_aggregates; std::vector<BenchmarkReporter::Run> aggregates_only; bool display_report_aggregates_only = false; bool file_report_aggregates_only = false; }; class BenchmarkRunner { public: BenchmarkRunner(const benchmark::internal::BenchmarkInstance& b_, BenchmarkReporter::PerFamilyRunReports* reports_for_family); int GetNumRepeats() const { return repeats; } bool HasRepeatsRemaining() const { return GetNumRepeats() != num_repetitions_done; } void DoOneRepetition(); RunResults&& GetResults(); BenchmarkReporter::PerFamilyRunReports* GetReportsForFamily() const { return reports_for_family; } private: RunResults run_results; const benchmark::internal::BenchmarkInstance& b; BenchmarkReporter::PerFamilyRunReports* reports_for_family; const double min_time; const double min_warmup_time; bool warmup_done; const int repeats; const bool has_explicit_iteration_count; int num_repetitions_done = 0; std::vector<std::thread> pool; std::vector<MemoryManager::Result> memory_results; IterationCount iters; // preserved between repetitions! // So only the first repetition has to find/calculate it, // the other repetitions will just use that precomputed iteration count. PerfCountersMeasurement perf_counters_measurement; PerfCountersMeasurement* const perf_counters_measurement_ptr; struct IterationResults { internal::ThreadManager::Result results; IterationCount iters; double seconds; }; IterationResults DoNIterations(); IterationCount PredictNumItersNeeded(const IterationResults& i) const; bool ShouldReportIterationResults(const IterationResults& i) const; double GetMinTimeToApply() const; void FinishWarmUp(const IterationCount& i); void RunWarmUp(); }; } // namespace internal } // end namespace benchmark #endif // BENCHMARK_RUNNER_H_
3,126
26.429825
78
h
OpenCC
OpenCC-master/deps/google-benchmark/src/check.h
#ifndef CHECK_H_ #define CHECK_H_ #include <cmath> #include <cstdlib> #include <ostream> #include "benchmark/export.h" #include "internal_macros.h" #include "log.h" #if defined(__GNUC__) || defined(__clang__) #define BENCHMARK_NOEXCEPT noexcept #define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) #elif defined(_MSC_VER) && !defined(__clang__) #if _MSC_VER >= 1900 #define BENCHMARK_NOEXCEPT noexcept #define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) #else #define BENCHMARK_NOEXCEPT #define BENCHMARK_NOEXCEPT_OP(x) #endif #define __func__ __FUNCTION__ #else #define BENCHMARK_NOEXCEPT #define BENCHMARK_NOEXCEPT_OP(x) #endif namespace benchmark { namespace internal { typedef void(AbortHandlerT)(); BENCHMARK_EXPORT AbortHandlerT*& GetAbortHandler(); BENCHMARK_NORETURN inline void CallAbortHandler() { GetAbortHandler()(); std::abort(); // fallback to enforce noreturn } // CheckHandler is the class constructed by failing BM_CHECK macros. // CheckHandler will log information about the failures and abort when it is // destructed. class CheckHandler { public: CheckHandler(const char* check, const char* file, const char* func, int line) : log_(GetErrorLogInstance()) { log_ << file << ":" << line << ": " << func << ": Check `" << check << "' failed. "; } LogType& GetLog() { return log_; } #if defined(COMPILER_MSVC) #pragma warning(push) #pragma warning(disable : 4722) #endif BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) { log_ << std::endl; CallAbortHandler(); } #if defined(COMPILER_MSVC) #pragma warning(pop) #endif CheckHandler& operator=(const CheckHandler&) = delete; CheckHandler(const CheckHandler&) = delete; CheckHandler() = delete; private: LogType& log_; }; } // end namespace internal } // end namespace benchmark // The BM_CHECK macro returns a std::ostream object that can have extra // information written to it. #ifndef NDEBUG #define BM_CHECK(b) \ (b ? ::benchmark::internal::GetNullLogInstance() \ : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \ .GetLog()) #else #define BM_CHECK(b) ::benchmark::internal::GetNullLogInstance() #endif // clang-format off // preserve whitespacing between operators for alignment #define BM_CHECK_EQ(a, b) BM_CHECK((a) == (b)) #define BM_CHECK_NE(a, b) BM_CHECK((a) != (b)) #define BM_CHECK_GE(a, b) BM_CHECK((a) >= (b)) #define BM_CHECK_LE(a, b) BM_CHECK((a) <= (b)) #define BM_CHECK_GT(a, b) BM_CHECK((a) > (b)) #define BM_CHECK_LT(a, b) BM_CHECK((a) < (b)) #define BM_CHECK_FLOAT_EQ(a, b, eps) BM_CHECK(std::fabs((a) - (b)) < (eps)) #define BM_CHECK_FLOAT_NE(a, b, eps) BM_CHECK(std::fabs((a) - (b)) >= (eps)) #define BM_CHECK_FLOAT_GE(a, b, eps) BM_CHECK((a) - (b) > -(eps)) #define BM_CHECK_FLOAT_LE(a, b, eps) BM_CHECK((b) - (a) > -(eps)) #define BM_CHECK_FLOAT_GT(a, b, eps) BM_CHECK((a) - (b) > (eps)) #define BM_CHECK_FLOAT_LT(a, b, eps) BM_CHECK((b) - (a) > (eps)) //clang-format on #endif // CHECK_H_
3,079
27.785047
79
h
OpenCC
OpenCC-master/deps/google-benchmark/src/colorprint.h
#ifndef BENCHMARK_COLORPRINT_H_ #define BENCHMARK_COLORPRINT_H_ #include <cstdarg> #include <iostream> #include <string> namespace benchmark { enum LogColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW, COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE }; std::string FormatString(const char* msg, va_list args); std::string FormatString(const char* msg, ...); void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, va_list args); void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...); // Returns true if stdout appears to be a terminal that supports colored // output, false otherwise. bool IsColorTerminal(); } // end namespace benchmark #endif // BENCHMARK_COLORPRINT_H_
760
21.382353
74
h
OpenCC
OpenCC-master/deps/google-benchmark/src/commandlineflags.h
#ifndef BENCHMARK_COMMANDLINEFLAGS_H_ #define BENCHMARK_COMMANDLINEFLAGS_H_ #include <cstdint> #include <map> #include <string> #include "benchmark/export.h" // Macro for referencing flags. #define FLAG(name) FLAGS_##name // Macros for declaring flags. #define BM_DECLARE_bool(name) BENCHMARK_EXPORT extern bool FLAG(name) #define BM_DECLARE_int32(name) BENCHMARK_EXPORT extern int32_t FLAG(name) #define BM_DECLARE_double(name) BENCHMARK_EXPORT extern double FLAG(name) #define BM_DECLARE_string(name) BENCHMARK_EXPORT extern std::string FLAG(name) #define BM_DECLARE_kvpairs(name) \ BENCHMARK_EXPORT extern std::map<std::string, std::string> FLAG(name) // Macros for defining flags. #define BM_DEFINE_bool(name, default_val) \ BENCHMARK_EXPORT bool FLAG(name) = benchmark::BoolFromEnv(#name, default_val) #define BM_DEFINE_int32(name, default_val) \ BENCHMARK_EXPORT int32_t FLAG(name) = \ benchmark::Int32FromEnv(#name, default_val) #define BM_DEFINE_double(name, default_val) \ BENCHMARK_EXPORT double FLAG(name) = \ benchmark::DoubleFromEnv(#name, default_val) #define BM_DEFINE_string(name, default_val) \ BENCHMARK_EXPORT std::string FLAG(name) = \ benchmark::StringFromEnv(#name, default_val) #define BM_DEFINE_kvpairs(name, default_val) \ BENCHMARK_EXPORT std::map<std::string, std::string> FLAG(name) = \ benchmark::KvPairsFromEnv(#name, default_val) namespace benchmark { // Parses a bool from the environment variable corresponding to the given flag. // // If the variable exists, returns IsTruthyFlagValue() value; if not, // returns the given default value. BENCHMARK_EXPORT bool BoolFromEnv(const char* flag, bool default_val); // Parses an Int32 from the environment variable corresponding to the given // flag. // // If the variable exists, returns ParseInt32() value; if not, returns // the given default value. BENCHMARK_EXPORT int32_t Int32FromEnv(const char* flag, int32_t default_val); // Parses an Double from the environment variable corresponding to the given // flag. // // If the variable exists, returns ParseDouble(); if not, returns // the given default value. BENCHMARK_EXPORT double DoubleFromEnv(const char* flag, double default_val); // Parses a string from the environment variable corresponding to the given // flag. // // If variable exists, returns its value; if not, returns // the given default value. BENCHMARK_EXPORT const char* StringFromEnv(const char* flag, const char* default_val); // Parses a set of kvpairs from the environment variable corresponding to the // given flag. // // If variable exists, returns its value; if not, returns // the given default value. BENCHMARK_EXPORT std::map<std::string, std::string> KvPairsFromEnv( const char* flag, std::map<std::string, std::string> default_val); // Parses a string for a bool flag, in the form of either // "--flag=value" or "--flag". // // In the former case, the value is taken as true if it passes IsTruthyValue(). // // In the latter case, the value is taken as true. // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. BENCHMARK_EXPORT bool ParseBoolFlag(const char* str, const char* flag, bool* value); // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. BENCHMARK_EXPORT bool ParseInt32Flag(const char* str, const char* flag, int32_t* value); // Parses a string for a Double flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. BENCHMARK_EXPORT bool ParseDoubleFlag(const char* str, const char* flag, double* value); // Parses a string for a string flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. BENCHMARK_EXPORT bool ParseStringFlag(const char* str, const char* flag, std::string* value); // Parses a string for a kvpairs flag in the form "--flag=key=value,key=value" // // On success, stores the value of the flag in *value and returns true. On // failure returns false, though *value may have been mutated. BENCHMARK_EXPORT bool ParseKeyValueFlag(const char* str, const char* flag, std::map<std::string, std::string>* value); // Returns true if the string matches the flag. BENCHMARK_EXPORT bool IsFlag(const char* str, const char* flag); // Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or // some non-alphanumeric character. Also returns false if the value matches // one of 'no', 'false', 'off' (case-insensitive). As a special case, also // returns true if value is the empty string. BENCHMARK_EXPORT bool IsTruthyFlagValue(const std::string& value); } // end namespace benchmark #endif // BENCHMARK_COMMANDLINEFLAGS_H_
5,044
36.649254
79
h
OpenCC
OpenCC-master/deps/google-benchmark/src/complexity.h
// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Source project : https://github.com/ismaelJimenez/cpp.leastsq // Adapted to be used with google benchmark #ifndef COMPLEXITY_H_ #define COMPLEXITY_H_ #include <string> #include <vector> #include "benchmark/benchmark.h" namespace benchmark { // Return a vector containing the bigO and RMS information for the specified // list of reports. If 'reports.size() < 2' an empty vector is returned. std::vector<BenchmarkReporter::Run> ComputeBigO( const std::vector<BenchmarkReporter::Run>& reports); // This data structure will contain the result returned by MinimalLeastSq // - coef : Estimated coeficient for the high-order term as // interpolated from data. // - rms : Normalized Root Mean Squared Error. // - complexity : Scalability form (e.g. oN, oNLogN). In case a scalability // form has been provided to MinimalLeastSq this will return // the same value. In case BigO::oAuto has been selected, this // parameter will return the best fitting curve detected. struct LeastSq { LeastSq() : coef(0.0), rms(0.0), complexity(oNone) {} double coef; double rms; BigO complexity; }; // Function to return an string for the calculated complexity std::string GetBigOString(BigO complexity); } // end namespace benchmark #endif // COMPLEXITY_H_
1,979
34.357143
80
h
OpenCC
OpenCC-master/deps/google-benchmark/src/counter.h
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef BENCHMARK_COUNTER_H_ #define BENCHMARK_COUNTER_H_ #include "benchmark/benchmark.h" namespace benchmark { // these counter-related functions are hidden to reduce API surface. namespace internal { void Finish(UserCounters* l, IterationCount iterations, double time, double num_threads); void Increment(UserCounters* l, UserCounters const& r); bool SameNames(UserCounters const& l, UserCounters const& r); } // end namespace internal } // end namespace benchmark #endif // BENCHMARK_COUNTER_H_
1,129
33.242424
75
h
OpenCC
OpenCC-master/deps/google-benchmark/src/cycleclock.h
// ---------------------------------------------------------------------- // CycleClock // A CycleClock tells you the current time in Cycles. The "time" // is actually time since power-on. This is like time() but doesn't // involve a system call and is much more precise. // // NOTE: Not all cpu/platform/kernel combinations guarantee that this // clock increments at a constant rate or is synchronized across all logical // cpus in a system. // // If you need the above guarantees, please consider using a different // API. There are efforts to provide an interface which provides a millisecond // granularity and implemented as a memory read. A memory read is generally // cheaper than the CycleClock for many architectures. // // Also, in some out of order CPU implementations, the CycleClock is not // serializing. So if you're trying to count at cycles granularity, your // data might be inaccurate due to out of order instruction execution. // ---------------------------------------------------------------------- #ifndef BENCHMARK_CYCLECLOCK_H_ #define BENCHMARK_CYCLECLOCK_H_ #include <cstdint> #include "benchmark/benchmark.h" #include "internal_macros.h" #if defined(BENCHMARK_OS_MACOSX) #include <mach/mach_time.h> #endif // For MSVC, we want to use '_asm rdtsc' when possible (since it works // with even ancient MSVC compilers), and when not possible the // __rdtsc intrinsic, declared in <intrin.h>. Unfortunately, in some // environments, <windows.h> and <intrin.h> have conflicting // declarations of some other intrinsics, breaking compilation. // Therefore, we simply declare __rdtsc ourselves. See also // http://connect.microsoft.com/VisualStudio/feedback/details/262047 #if defined(COMPILER_MSVC) && !defined(_M_IX86) && !defined(_M_ARM64) extern "C" uint64_t __rdtsc(); #pragma intrinsic(__rdtsc) #endif #if !defined(BENCHMARK_OS_WINDOWS) || defined(BENCHMARK_OS_MINGW) #include <sys/time.h> #include <time.h> #endif #ifdef BENCHMARK_OS_EMSCRIPTEN #include <emscripten.h> #endif namespace benchmark { // NOTE: only i386 and x86_64 have been well tested. // PPC, sparc, alpha, and ia64 are based on // http://peter.kuscsik.com/wordpress/?p=14 // with modifications by m3b. See also // https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h namespace cycleclock { // This should return the number of cycles since power-on. Thread-safe. inline BENCHMARK_ALWAYS_INLINE int64_t Now() { #if defined(BENCHMARK_OS_MACOSX) // this goes at the top because we need ALL Macs, regardless of // architecture, to return the number of "mach time units" that // have passed since startup. See sysinfo.cc where // InitializeSystemInfo() sets the supposed cpu clock frequency of // macs to the number of mach time units per second, not actual // CPU clock frequency (which can change in the face of CPU // frequency scaling). Also note that when the Mac sleeps, this // counter pauses; it does not continue counting, nor does it // reset to zero. return mach_absolute_time(); #elif defined(BENCHMARK_OS_EMSCRIPTEN) // this goes above x86-specific code because old versions of Emscripten // define __x86_64__, although they have nothing to do with it. return static_cast<int64_t>(emscripten_get_now() * 1e+6); #elif defined(__i386__) int64_t ret; __asm__ volatile("rdtsc" : "=A"(ret)); return ret; #elif defined(__x86_64__) || defined(__amd64__) uint64_t low, high; __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); return (high << 32) | low; #elif defined(__powerpc__) || defined(__ppc__) // This returns a time-base, which is not always precisely a cycle-count. #if defined(__powerpc64__) || defined(__ppc64__) int64_t tb; asm volatile("mfspr %0, 268" : "=r"(tb)); return tb; #else uint32_t tbl, tbu0, tbu1; asm volatile( "mftbu %0\n" "mftb %1\n" "mftbu %2" : "=r"(tbu0), "=r"(tbl), "=r"(tbu1)); tbl &= -static_cast<int32_t>(tbu0 == tbu1); // high 32 bits in tbu1; low 32 bits in tbl (tbu0 is no longer needed) return (static_cast<uint64_t>(tbu1) << 32) | tbl; #endif #elif defined(__sparc__) int64_t tick; asm(".byte 0x83, 0x41, 0x00, 0x00"); asm("mov %%g1, %0" : "=r"(tick)); return tick; #elif defined(__ia64__) int64_t itc; asm("mov %0 = ar.itc" : "=r"(itc)); return itc; #elif defined(COMPILER_MSVC) && defined(_M_IX86) // Older MSVC compilers (like 7.x) don't seem to support the // __rdtsc intrinsic properly, so I prefer to use _asm instead // when I know it will work. Otherwise, I'll use __rdtsc and hope // the code is being compiled with a non-ancient compiler. _asm rdtsc #elif defined(COMPILER_MSVC) && defined(_M_ARM64) // See // https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics // and https://reviews.llvm.org/D53115 int64_t virtual_timer_value; virtual_timer_value = _ReadStatusReg(ARM64_CNTVCT); return virtual_timer_value; #elif defined(COMPILER_MSVC) return __rdtsc(); #elif defined(BENCHMARK_OS_NACL) // Native Client validator on x86/x86-64 allows RDTSC instructions, // and this case is handled above. Native Client validator on ARM // rejects MRC instructions (used in the ARM-specific sequence below), // so we handle it here. Portable Native Client compiles to // architecture-agnostic bytecode, which doesn't provide any // cycle counter access mnemonics. // Native Client does not provide any API to access cycle counter. // Use clock_gettime(CLOCK_MONOTONIC, ...) instead of gettimeofday // because is provides nanosecond resolution (which is noticeable at // least for PNaCl modules running on x86 Mac & Linux). // Initialize to always return 0 if clock_gettime fails. struct timespec ts = {0, 0}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<int64_t>(ts.tv_sec) * 1000000000 + ts.tv_nsec; #elif defined(__aarch64__) // System timer of ARMv8 runs at a different frequency than the CPU's. // The frequency is fixed, typically in the range 1-50MHz. It can be // read at CNTFRQ special register. We assume the OS has set up // the virtual timer properly. int64_t virtual_timer_value; asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value)); return virtual_timer_value; #elif defined(__ARM_ARCH) // V6 is the earliest arch that has a standard cyclecount // Native Client validator doesn't allow MRC instructions. #if (__ARM_ARCH >= 6) uint32_t pmccntr; uint32_t pmuseren; uint32_t pmcntenset; // Read the user mode perf monitor counter access permissions. asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); if (pmuseren & 1) { // Allows reading perfmon counters for user mode code. asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); if (pmcntenset & 0x80000000ul) { // Is it counting? asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); // The counter is set up to count every 64th cycle return static_cast<int64_t>(pmccntr) * 64; // Should optimize to << 6 } } #endif struct timeval tv; gettimeofday(&tv, nullptr); return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; #elif defined(__mips__) || defined(__m68k__) // mips apparently only allows rdtsc for superusers, so we fall // back to gettimeofday. It's possible clock_gettime would be better. struct timeval tv; gettimeofday(&tv, nullptr); return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; #elif defined(__loongarch__) || defined(__csky__) struct timeval tv; gettimeofday(&tv, nullptr); return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; #elif defined(__s390__) // Covers both s390 and s390x. // Return the CPU clock. uint64_t tsc; #if defined(BENCHMARK_OS_ZOS) && defined(COMPILER_IBMXL) // z/OS XL compiler HLASM syntax. asm(" stck %0" : "=m"(tsc) : : "cc"); #else asm("stck %0" : "=Q"(tsc) : : "cc"); #endif return tsc; #elif defined(__riscv) // RISC-V // Use RDCYCLE (and RDCYCLEH on riscv32) #if __riscv_xlen == 32 uint32_t cycles_lo, cycles_hi0, cycles_hi1; // This asm also includes the PowerPC overflow handling strategy, as above. // Implemented in assembly because Clang insisted on branching. asm volatile( "rdcycleh %0\n" "rdcycle %1\n" "rdcycleh %2\n" "sub %0, %0, %2\n" "seqz %0, %0\n" "sub %0, zero, %0\n" "and %1, %1, %0\n" : "=r"(cycles_hi0), "=r"(cycles_lo), "=r"(cycles_hi1)); return (static_cast<uint64_t>(cycles_hi1) << 32) | cycles_lo; #else uint64_t cycles; asm volatile("rdcycle %0" : "=r"(cycles)); return cycles; #endif #elif defined(__e2k__) || defined(__elbrus__) struct timeval tv; gettimeofday(&tv, nullptr); return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; #elif defined(__hexagon__) uint64_t pcycle; asm volatile("%0 = C15:14" : "=r"(pcycle)); return static_cast<double>(pcycle); #else // The soft failover to a generic implementation is automatic only for ARM. // For other platforms the developer is expected to make an attempt to create // a fast implementation and use generic version if nothing better is available. #error You need to define CycleTimer for your OS and CPU #endif } } // end namespace cycleclock } // end namespace benchmark #endif // BENCHMARK_CYCLECLOCK_H_
9,288
39.386957
80
h
OpenCC
OpenCC-master/deps/google-benchmark/src/internal_macros.h
#ifndef BENCHMARK_INTERNAL_MACROS_H_ #define BENCHMARK_INTERNAL_MACROS_H_ /* Needed to detect STL */ #include <cstdlib> // clang-format off #ifndef __has_feature #define __has_feature(x) 0 #endif #if defined(__clang__) #if defined(__ibmxl__) #if !defined(COMPILER_IBMXL) #define COMPILER_IBMXL #endif #elif !defined(COMPILER_CLANG) #define COMPILER_CLANG #endif #elif defined(_MSC_VER) #if !defined(COMPILER_MSVC) #define COMPILER_MSVC #endif #elif defined(__GNUC__) #if !defined(COMPILER_GCC) #define COMPILER_GCC #endif #endif #if __has_feature(cxx_attributes) #define BENCHMARK_NORETURN [[noreturn]] #elif defined(__GNUC__) #define BENCHMARK_NORETURN __attribute__((noreturn)) #elif defined(COMPILER_MSVC) #define BENCHMARK_NORETURN __declspec(noreturn) #else #define BENCHMARK_NORETURN #endif #if defined(__CYGWIN__) #define BENCHMARK_OS_CYGWIN 1 #elif defined(_WIN32) #define BENCHMARK_OS_WINDOWS 1 #if defined(WINAPI_FAMILY_PARTITION) #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define BENCHMARK_OS_WINDOWS_WIN32 1 #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define BENCHMARK_OS_WINDOWS_RT 1 #endif #endif #if defined(__MINGW32__) #define BENCHMARK_OS_MINGW 1 #endif #elif defined(__APPLE__) #define BENCHMARK_OS_APPLE 1 #include "TargetConditionals.h" #if defined(TARGET_OS_MAC) #define BENCHMARK_OS_MACOSX 1 #if defined(TARGET_OS_IPHONE) #define BENCHMARK_OS_IOS 1 #endif #endif #elif defined(__FreeBSD__) #define BENCHMARK_OS_FREEBSD 1 #elif defined(__NetBSD__) #define BENCHMARK_OS_NETBSD 1 #elif defined(__OpenBSD__) #define BENCHMARK_OS_OPENBSD 1 #elif defined(__DragonFly__) #define BENCHMARK_OS_DRAGONFLY 1 #elif defined(__linux__) #define BENCHMARK_OS_LINUX 1 #elif defined(__native_client__) #define BENCHMARK_OS_NACL 1 #elif defined(__EMSCRIPTEN__) #define BENCHMARK_OS_EMSCRIPTEN 1 #elif defined(__rtems__) #define BENCHMARK_OS_RTEMS 1 #elif defined(__Fuchsia__) #define BENCHMARK_OS_FUCHSIA 1 #elif defined (__SVR4) && defined (__sun) #define BENCHMARK_OS_SOLARIS 1 #elif defined(__QNX__) #define BENCHMARK_OS_QNX 1 #elif defined(__MVS__) #define BENCHMARK_OS_ZOS 1 #elif defined(__hexagon__) #define BENCHMARK_OS_QURT 1 #endif #if defined(__ANDROID__) && defined(__GLIBCXX__) #define BENCHMARK_STL_ANDROID_GNUSTL 1 #endif #if !__has_feature(cxx_exceptions) && !defined(__cpp_exceptions) \ && !defined(__EXCEPTIONS) #define BENCHMARK_HAS_NO_EXCEPTIONS #endif #if defined(COMPILER_CLANG) || defined(COMPILER_GCC) #define BENCHMARK_MAYBE_UNUSED __attribute__((unused)) #else #define BENCHMARK_MAYBE_UNUSED #endif // clang-format on #endif // BENCHMARK_INTERNAL_MACROS_H_
2,761
24.109091
66
h
OpenCC
OpenCC-master/deps/google-benchmark/src/log.h
#ifndef BENCHMARK_LOG_H_ #define BENCHMARK_LOG_H_ #include <iostream> #include <ostream> // NOTE: this is also defined in benchmark.h but we're trying to avoid a // dependency. // The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer. #if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) #define BENCHMARK_HAS_CXX11 #endif namespace benchmark { namespace internal { typedef std::basic_ostream<char>&(EndLType)(std::basic_ostream<char>&); class LogType { friend LogType& GetNullLogInstance(); friend LogType& GetErrorLogInstance(); // FIXME: Add locking to output. template <class Tp> friend LogType& operator<<(LogType&, Tp const&); friend LogType& operator<<(LogType&, EndLType*); private: LogType(std::ostream* out) : out_(out) {} std::ostream* out_; // NOTE: we could use BENCHMARK_DISALLOW_COPY_AND_ASSIGN but we shouldn't have // a dependency on benchmark.h from here. #ifndef BENCHMARK_HAS_CXX11 LogType(const LogType&); LogType& operator=(const LogType&); #else LogType(const LogType&) = delete; LogType& operator=(const LogType&) = delete; #endif }; template <class Tp> LogType& operator<<(LogType& log, Tp const& value) { if (log.out_) { *log.out_ << value; } return log; } inline LogType& operator<<(LogType& log, EndLType* m) { if (log.out_) { *log.out_ << m; } return log; } inline int& LogLevel() { static int log_level = 0; return log_level; } inline LogType& GetNullLogInstance() { static LogType null_log((std::ostream*)nullptr); return null_log; } inline LogType& GetErrorLogInstance() { static LogType error_log(&std::clog); return error_log; } inline LogType& GetLogInstanceForLevel(int level) { if (level <= LogLevel()) { return GetErrorLogInstance(); } return GetNullLogInstance(); } } // end namespace internal } // end namespace benchmark // clang-format off #define BM_VLOG(x) \ (::benchmark::internal::GetLogInstanceForLevel(x) << "-- LOG(" << x << "):" \ " ") // clang-format on #endif
2,181
23.516854
82
h
OpenCC
OpenCC-master/deps/google-benchmark/src/mutex.h
#ifndef BENCHMARK_MUTEX_H_ #define BENCHMARK_MUTEX_H_ #include <condition_variable> #include <mutex> #include "check.h" // Enable thread safety attributes only with clang. // The attributes can be safely erased when compiling with other compilers. #if defined(HAVE_THREAD_SAFETY_ATTRIBUTES) #define THREAD_ANNOTATION_ATTRIBUTE_(x) __attribute__((x)) #else #define THREAD_ANNOTATION_ATTRIBUTE_(x) // no-op #endif #define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(capability(x)) #define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE_(scoped_lockable) #define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(guarded_by(x)) #define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(pt_guarded_by(x)) #define ACQUIRED_BEFORE(...) \ THREAD_ANNOTATION_ATTRIBUTE_(acquired_before(__VA_ARGS__)) #define ACQUIRED_AFTER(...) \ THREAD_ANNOTATION_ATTRIBUTE_(acquired_after(__VA_ARGS__)) #define REQUIRES(...) \ THREAD_ANNOTATION_ATTRIBUTE_(requires_capability(__VA_ARGS__)) #define REQUIRES_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE_(requires_shared_capability(__VA_ARGS__)) #define ACQUIRE(...) \ THREAD_ANNOTATION_ATTRIBUTE_(acquire_capability(__VA_ARGS__)) #define ACQUIRE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE_(acquire_shared_capability(__VA_ARGS__)) #define RELEASE(...) \ THREAD_ANNOTATION_ATTRIBUTE_(release_capability(__VA_ARGS__)) #define RELEASE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE_(release_shared_capability(__VA_ARGS__)) #define TRY_ACQUIRE(...) \ THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_capability(__VA_ARGS__)) #define TRY_ACQUIRE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_shared_capability(__VA_ARGS__)) #define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE_(locks_excluded(__VA_ARGS__)) #define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(assert_capability(x)) #define ASSERT_SHARED_CAPABILITY(x) \ THREAD_ANNOTATION_ATTRIBUTE_(assert_shared_capability(x)) #define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(lock_returned(x)) #define NO_THREAD_SAFETY_ANALYSIS \ THREAD_ANNOTATION_ATTRIBUTE_(no_thread_safety_analysis) namespace benchmark { typedef std::condition_variable Condition; // NOTE: Wrappers for std::mutex and std::unique_lock are provided so that // we can annotate them with thread safety attributes and use the // -Wthread-safety warning with clang. The standard library types cannot be // used directly because they do not provide the required annotations. class CAPABILITY("mutex") Mutex { public: Mutex() {} void lock() ACQUIRE() { mut_.lock(); } void unlock() RELEASE() { mut_.unlock(); } std::mutex& native_handle() { return mut_; } private: std::mutex mut_; }; class SCOPED_CAPABILITY MutexLock { typedef std::unique_lock<std::mutex> MutexLockImp; public: MutexLock(Mutex& m) ACQUIRE(m) : ml_(m.native_handle()) {} ~MutexLock() RELEASE() {} MutexLockImp& native_handle() { return ml_; } private: MutexLockImp ml_; }; class Barrier { public: Barrier(int num_threads) : running_threads_(num_threads) {} // Called by each thread bool wait() EXCLUDES(lock_) { bool last_thread = false; { MutexLock ml(lock_); last_thread = createBarrier(ml); } if (last_thread) phase_condition_.notify_all(); return last_thread; } void removeThread() EXCLUDES(lock_) { MutexLock ml(lock_); --running_threads_; if (entered_ != 0) phase_condition_.notify_all(); } private: Mutex lock_; Condition phase_condition_; int running_threads_; // State for barrier management int phase_number_ = 0; int entered_ = 0; // Number of threads that have entered this barrier // Enter the barrier and wait until all other threads have also // entered the barrier. Returns iff this is the last thread to // enter the barrier. bool createBarrier(MutexLock& ml) REQUIRES(lock_) { BM_CHECK_LT(entered_, running_threads_); entered_++; if (entered_ < running_threads_) { // Wait for all threads to enter int phase_number_cp = phase_number_; auto cb = [this, phase_number_cp]() { return this->phase_number_ > phase_number_cp || entered_ == running_threads_; // A thread has aborted in error }; phase_condition_.wait(ml.native_handle(), cb); if (phase_number_ > phase_number_cp) return false; // else (running_threads_ == entered_) and we are the last thread. } // Last thread has reached the barrier phase_number_++; entered_ = 0; return true; } }; } // end namespace benchmark #endif // BENCHMARK_MUTEX_H_
4,578
28.352564
79
h
OpenCC
OpenCC-master/deps/google-benchmark/src/perf_counters.h
// Copyright 2021 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef BENCHMARK_PERF_COUNTERS_H #define BENCHMARK_PERF_COUNTERS_H #include <array> #include <cstdint> #include <memory> #include <vector> #include "benchmark/benchmark.h" #include "check.h" #include "log.h" #include "mutex.h" #ifndef BENCHMARK_OS_WINDOWS #include <unistd.h> #endif #if defined(_MSC_VER) #pragma warning(push) // C4251: <symbol> needs to have dll-interface to be used by clients of class #pragma warning(disable : 4251) #endif namespace benchmark { namespace internal { // Typically, we can only read a small number of counters. There is also a // padding preceding counter values, when reading multiple counters with one // syscall (which is desirable). PerfCounterValues abstracts these details. // The implementation ensures the storage is inlined, and allows 0-based // indexing into the counter values. // The object is used in conjunction with a PerfCounters object, by passing it // to Snapshot(). The values are populated such that // perfCounters->names()[i]'s value is obtained at position i (as given by // operator[]) of this object. class PerfCounterValues { public: explicit PerfCounterValues(size_t nr_counters) : nr_counters_(nr_counters) { BM_CHECK_LE(nr_counters_, kMaxCounters); } uint64_t operator[](size_t pos) const { return values_[kPadding + pos]; } static constexpr size_t kMaxCounters = 3; private: friend class PerfCounters; // Get the byte buffer in which perf counters can be captured. // This is used by PerfCounters::Read std::pair<char*, size_t> get_data_buffer() { return {reinterpret_cast<char*>(values_.data()), sizeof(uint64_t) * (kPadding + nr_counters_)}; } static constexpr size_t kPadding = 1; std::array<uint64_t, kPadding + kMaxCounters> values_; const size_t nr_counters_; }; // Collect PMU counters. The object, once constructed, is ready to be used by // calling read(). PMU counter collection is enabled from the time create() is // called, to obtain the object, until the object's destructor is called. class BENCHMARK_EXPORT PerfCounters final { public: // True iff this platform supports performance counters. static const bool kSupported; bool IsValid() const { return !counter_names_.empty(); } static PerfCounters NoCounters() { return PerfCounters(); } ~PerfCounters() { CloseCounters(); } PerfCounters(PerfCounters&&) = default; PerfCounters(const PerfCounters&) = delete; PerfCounters& operator=(PerfCounters&&) noexcept; PerfCounters& operator=(const PerfCounters&) = delete; // Platform-specific implementations may choose to do some library // initialization here. static bool Initialize(); // Return a PerfCounters object ready to read the counters with the names // specified. The values are user-mode only. The counter name format is // implementation and OS specific. // TODO: once we move to C++-17, this should be a std::optional, and then the // IsValid() boolean can be dropped. static PerfCounters Create(const std::vector<std::string>& counter_names); // Take a snapshot of the current value of the counters into the provided // valid PerfCounterValues storage. The values are populated such that: // names()[i]'s value is (*values)[i] BENCHMARK_ALWAYS_INLINE bool Snapshot(PerfCounterValues* values) const { #ifndef BENCHMARK_OS_WINDOWS assert(values != nullptr); assert(IsValid()); auto buffer = values->get_data_buffer(); auto read_bytes = ::read(counter_ids_[0], buffer.first, buffer.second); return static_cast<size_t>(read_bytes) == buffer.second; #else (void)values; return false; #endif } const std::vector<std::string>& names() const { return counter_names_; } size_t num_counters() const { return counter_names_.size(); } private: PerfCounters(const std::vector<std::string>& counter_names, std::vector<int>&& counter_ids) : counter_ids_(std::move(counter_ids)), counter_names_(counter_names) {} PerfCounters() = default; void CloseCounters() const; std::vector<int> counter_ids_; std::vector<std::string> counter_names_; }; // Typical usage of the above primitives. class BENCHMARK_EXPORT PerfCountersMeasurement final { public: PerfCountersMeasurement(const std::vector<std::string>& counter_names); ~PerfCountersMeasurement(); // The only way to get to `counters_` is after ctor-ing a // `PerfCountersMeasurement`, which means that `counters_`'s state is, here, // decided (either invalid or valid) and won't change again even if a ctor is // concurrently running with this. This is preferring efficiency to // maintainability, because the address of the static can be known at compile // time. bool IsValid() const { MutexLock l(mutex_); return counters_.IsValid(); } BENCHMARK_ALWAYS_INLINE void Start() { assert(IsValid()); MutexLock l(mutex_); // Tell the compiler to not move instructions above/below where we take // the snapshot. ClobberMemory(); valid_read_ &= counters_.Snapshot(&start_values_); ClobberMemory(); } BENCHMARK_ALWAYS_INLINE bool Stop( std::vector<std::pair<std::string, double>>& measurements) { assert(IsValid()); MutexLock l(mutex_); // Tell the compiler to not move instructions above/below where we take // the snapshot. ClobberMemory(); valid_read_ &= counters_.Snapshot(&end_values_); ClobberMemory(); for (size_t i = 0; i < counters_.names().size(); ++i) { double measurement = static_cast<double>(end_values_[i]) - static_cast<double>(start_values_[i]); measurements.push_back({counters_.names()[i], measurement}); } return valid_read_; } private: static Mutex mutex_; GUARDED_BY(mutex_) static int ref_count_; GUARDED_BY(mutex_) static PerfCounters counters_; bool valid_read_ = true; PerfCounterValues start_values_; PerfCounterValues end_values_; }; BENCHMARK_UNUSED static bool perf_init_anchor = PerfCounters::Initialize(); } // namespace internal } // namespace benchmark #if defined(_MSC_VER) #pragma warning(pop) #endif #endif // BENCHMARK_PERF_COUNTERS_H
6,759
33.141414
79
h
OpenCC
OpenCC-master/deps/google-benchmark/src/re.h
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef BENCHMARK_RE_H_ #define BENCHMARK_RE_H_ #include "internal_macros.h" // clang-format off #if !defined(HAVE_STD_REGEX) && \ !defined(HAVE_GNU_POSIX_REGEX) && \ !defined(HAVE_POSIX_REGEX) // No explicit regex selection; detect based on builtin hints. #if defined(BENCHMARK_OS_LINUX) || defined(BENCHMARK_OS_APPLE) #define HAVE_POSIX_REGEX 1 #elif __cplusplus >= 199711L #define HAVE_STD_REGEX 1 #endif #endif // Prefer C regex libraries when compiling w/o exceptions so that we can // correctly report errors. #if defined(BENCHMARK_HAS_NO_EXCEPTIONS) && \ defined(BENCHMARK_HAVE_STD_REGEX) && \ (defined(HAVE_GNU_POSIX_REGEX) || defined(HAVE_POSIX_REGEX)) #undef HAVE_STD_REGEX #endif #if defined(HAVE_STD_REGEX) #include <regex> #elif defined(HAVE_GNU_POSIX_REGEX) #include <gnuregex.h> #elif defined(HAVE_POSIX_REGEX) #include <regex.h> #else #error No regular expression backend was found! #endif // clang-format on #include <string> #include "check.h" namespace benchmark { // A wrapper around the POSIX regular expression API that provides automatic // cleanup class Regex { public: Regex() : init_(false) {} ~Regex(); // Compile a regular expression matcher from spec. Returns true on success. // // On failure (and if error is not nullptr), error is populated with a human // readable error message if an error occurs. bool Init(const std::string& spec, std::string* error); // Returns whether str matches the compiled regular expression. bool Match(const std::string& str); private: bool init_; // Underlying regular expression object #if defined(HAVE_STD_REGEX) std::regex re_; #elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX) regex_t re_; #else #error No regular expression backend implementation available #endif }; #if defined(HAVE_STD_REGEX) inline bool Regex::Init(const std::string& spec, std::string* error) { #ifdef BENCHMARK_HAS_NO_EXCEPTIONS ((void)error); // suppress unused warning #else try { #endif re_ = std::regex(spec, std::regex_constants::extended); init_ = true; #ifndef BENCHMARK_HAS_NO_EXCEPTIONS } catch (const std::regex_error& e) { if (error) { *error = e.what(); } } #endif return init_; } inline Regex::~Regex() {} inline bool Regex::Match(const std::string& str) { if (!init_) { return false; } return std::regex_search(str, re_); } #else inline bool Regex::Init(const std::string& spec, std::string* error) { int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB); if (ec != 0) { if (error) { size_t needed = regerror(ec, &re_, nullptr, 0); char* errbuf = new char[needed]; regerror(ec, &re_, errbuf, needed); // regerror returns the number of bytes necessary to null terminate // the string, so we move that when assigning to error. BM_CHECK_NE(needed, 0); error->assign(errbuf, needed - 1); delete[] errbuf; } return false; } init_ = true; return true; } inline Regex::~Regex() { if (init_) { regfree(&re_); } } inline bool Regex::Match(const std::string& str) { if (!init_) { return false; } return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0; } #endif } // end namespace benchmark #endif // BENCHMARK_RE_H_
3,903
23.553459
78
h
OpenCC
OpenCC-master/deps/google-benchmark/src/statistics.h
// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. // Copyright 2017 Roman Lebedev. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef STATISTICS_H_ #define STATISTICS_H_ #include <vector> #include "benchmark/benchmark.h" namespace benchmark { // Return a vector containing the mean, median and standard devation information // (and any user-specified info) for the specified list of reports. If 'reports' // contains less than two non-errored runs an empty vector is returned BENCHMARK_EXPORT std::vector<BenchmarkReporter::Run> ComputeStats( const std::vector<BenchmarkReporter::Run>& reports); BENCHMARK_EXPORT double StatisticsMean(const std::vector<double>& v); BENCHMARK_EXPORT double StatisticsMedian(const std::vector<double>& v); BENCHMARK_EXPORT double StatisticsStdDev(const std::vector<double>& v); BENCHMARK_EXPORT double StatisticsCV(const std::vector<double>& v); } // end namespace benchmark #endif // STATISTICS_H_
1,495
33
80
h
OpenCC
OpenCC-master/deps/google-benchmark/src/string_util.h
#ifndef BENCHMARK_STRING_UTIL_H_ #define BENCHMARK_STRING_UTIL_H_ #include <sstream> #include <string> #include <utility> #include <vector> #include "benchmark/export.h" #include "check.h" #include "internal_macros.h" namespace benchmark { void AppendHumanReadable(int n, std::string* str); std::string HumanReadableNumber(double n, double one_k = 1024.0); BENCHMARK_EXPORT #if defined(__MINGW32__) __attribute__((format(__MINGW_PRINTF_FORMAT, 1, 2))) #elif defined(__GNUC__) __attribute__((format(printf, 1, 2))) #endif std::string StrFormat(const char* format, ...); inline std::ostream& StrCatImp(std::ostream& out) BENCHMARK_NOEXCEPT { return out; } template <class First, class... Rest> inline std::ostream& StrCatImp(std::ostream& out, First&& f, Rest&&... rest) { out << std::forward<First>(f); return StrCatImp(out, std::forward<Rest>(rest)...); } template <class... Args> inline std::string StrCat(Args&&... args) { std::ostringstream ss; StrCatImp(ss, std::forward<Args>(args)...); return ss.str(); } BENCHMARK_EXPORT std::vector<std::string> StrSplit(const std::string& str, char delim); // Disable lint checking for this block since it re-implements C functions. // NOLINTBEGIN #ifdef BENCHMARK_STL_ANDROID_GNUSTL /* * GNU STL in Android NDK lacks support for some C++11 functions, including * stoul, stoi, stod. We reimplement them here using C functions strtoul, * strtol, strtod. Note that reimplemented functions are in benchmark:: * namespace, not std:: namespace. */ unsigned long stoul(const std::string& str, size_t* pos = nullptr, int base = 10); int stoi(const std::string& str, size_t* pos = nullptr, int base = 10); double stod(const std::string& str, size_t* pos = nullptr); #else using std::stod; // NOLINT(misc-unused-using-decls) using std::stoi; // NOLINT(misc-unused-using-decls) using std::stoul; // NOLINT(misc-unused-using-decls) #endif // NOLINTEND } // end namespace benchmark #endif // BENCHMARK_STRING_UTIL_H_
2,004
27.239437
78
h
OpenCC
OpenCC-master/deps/google-benchmark/src/thread_manager.h
#ifndef BENCHMARK_THREAD_MANAGER_H #define BENCHMARK_THREAD_MANAGER_H #include <atomic> #include "benchmark/benchmark.h" #include "mutex.h" namespace benchmark { namespace internal { class ThreadManager { public: explicit ThreadManager(int num_threads) : alive_threads_(num_threads), start_stop_barrier_(num_threads) {} Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) { return benchmark_mutex_; } bool StartStopBarrier() EXCLUDES(end_cond_mutex_) { return start_stop_barrier_.wait(); } void NotifyThreadComplete() EXCLUDES(end_cond_mutex_) { start_stop_barrier_.removeThread(); if (--alive_threads_ == 0) { MutexLock lock(end_cond_mutex_); end_condition_.notify_all(); } } void WaitForAllThreads() EXCLUDES(end_cond_mutex_) { MutexLock lock(end_cond_mutex_); end_condition_.wait(lock.native_handle(), [this]() { return alive_threads_ == 0; }); } struct Result { IterationCount iterations = 0; double real_time_used = 0; double cpu_time_used = 0; double manual_time_used = 0; int64_t complexity_n = 0; std::string report_label_; std::string error_message_; bool has_error_ = false; UserCounters counters; }; GUARDED_BY(GetBenchmarkMutex()) Result results; private: mutable Mutex benchmark_mutex_; std::atomic<int> alive_threads_; Barrier start_stop_barrier_; Mutex end_cond_mutex_; Condition end_condition_; }; } // namespace internal } // namespace benchmark #endif // BENCHMARK_THREAD_MANAGER_H
1,574
23.609375
72
h
OpenCC
OpenCC-master/deps/google-benchmark/src/thread_timer.h
#ifndef BENCHMARK_THREAD_TIMER_H #define BENCHMARK_THREAD_TIMER_H #include "check.h" #include "timers.h" namespace benchmark { namespace internal { class ThreadTimer { explicit ThreadTimer(bool measure_process_cpu_time_) : measure_process_cpu_time(measure_process_cpu_time_) {} public: static ThreadTimer Create() { return ThreadTimer(/*measure_process_cpu_time_=*/false); } static ThreadTimer CreateProcessCpuTime() { return ThreadTimer(/*measure_process_cpu_time_=*/true); } // Called by each thread void StartTimer() { running_ = true; start_real_time_ = ChronoClockNow(); start_cpu_time_ = ReadCpuTimerOfChoice(); } // Called by each thread void StopTimer() { BM_CHECK(running_); running_ = false; real_time_used_ += ChronoClockNow() - start_real_time_; // Floating point error can result in the subtraction producing a negative // time. Guard against that. cpu_time_used_ += std::max<double>(ReadCpuTimerOfChoice() - start_cpu_time_, 0); } // Called by each thread void SetIterationTime(double seconds) { manual_time_used_ += seconds; } bool running() const { return running_; } // REQUIRES: timer is not running double real_time_used() const { BM_CHECK(!running_); return real_time_used_; } // REQUIRES: timer is not running double cpu_time_used() const { BM_CHECK(!running_); return cpu_time_used_; } // REQUIRES: timer is not running double manual_time_used() const { BM_CHECK(!running_); return manual_time_used_; } private: double ReadCpuTimerOfChoice() const { if (measure_process_cpu_time) return ProcessCPUUsage(); return ThreadCPUUsage(); } // should the thread, or the process, time be measured? const bool measure_process_cpu_time; bool running_ = false; // Is the timer running double start_real_time_ = 0; // If running_ double start_cpu_time_ = 0; // If running_ // Accumulated time so far (does not contain current slice if running_) double real_time_used_ = 0; double cpu_time_used_ = 0; // Manually set iteration time. User sets this with SetIterationTime(seconds). double manual_time_used_ = 0; }; } // namespace internal } // namespace benchmark #endif // BENCHMARK_THREAD_TIMER_H
2,297
25.413793
80
h
OpenCC
OpenCC-master/deps/google-benchmark/src/timers.h
#ifndef BENCHMARK_TIMERS_H #define BENCHMARK_TIMERS_H #include <chrono> #include <string> namespace benchmark { // Return the CPU usage of the current process double ProcessCPUUsage(); // Return the CPU usage of the children of the current process double ChildrenCPUUsage(); // Return the CPU usage of the current thread double ThreadCPUUsage(); #if defined(HAVE_STEADY_CLOCK) template <bool HighResIsSteady = std::chrono::high_resolution_clock::is_steady> struct ChooseSteadyClock { typedef std::chrono::high_resolution_clock type; }; template <> struct ChooseSteadyClock<false> { typedef std::chrono::steady_clock type; }; #endif struct ChooseClockType { #if defined(HAVE_STEADY_CLOCK) typedef ChooseSteadyClock<>::type type; #else typedef std::chrono::high_resolution_clock type; #endif }; inline double ChronoClockNow() { typedef ChooseClockType::type ClockType; using FpSeconds = std::chrono::duration<double, std::chrono::seconds::period>; return FpSeconds(ClockType::now().time_since_epoch()).count(); } std::string LocalDateTimeString(); } // end namespace benchmark #endif // BENCHMARK_TIMERS_H
1,132
22.122449
80
h
OpenCC
OpenCC-master/deps/google-benchmark/test/output_test.h
#ifndef TEST_OUTPUT_TEST_H #define TEST_OUTPUT_TEST_H #undef NDEBUG #include <functional> #include <initializer_list> #include <memory> #include <sstream> #include <string> #include <utility> #include <vector> #include "../src/re.h" #include "benchmark/benchmark.h" #define CONCAT2(x, y) x##y #define CONCAT(x, y) CONCAT2(x, y) #define ADD_CASES(...) int CONCAT(dummy, __LINE__) = ::AddCases(__VA_ARGS__) #define SET_SUBSTITUTIONS(...) \ int CONCAT(dummy, __LINE__) = ::SetSubstitutions(__VA_ARGS__) enum MatchRules { MR_Default, // Skip non-matching lines until a match is found. MR_Next, // Match must occur on the next line. MR_Not // No line between the current position and the next match matches // the regex }; struct TestCase { TestCase(std::string re, int rule = MR_Default); std::string regex_str; int match_rule; std::string substituted_regex; std::shared_ptr<benchmark::Regex> regex; }; enum TestCaseID { TC_ConsoleOut, TC_ConsoleErr, TC_JSONOut, TC_JSONErr, TC_CSVOut, TC_CSVErr, TC_NumID // PRIVATE }; // Add a list of test cases to be run against the output specified by // 'ID' int AddCases(TestCaseID ID, std::initializer_list<TestCase> il); // Add or set a list of substitutions to be performed on constructed regex's // See 'output_test_helper.cc' for a list of default substitutions. int SetSubstitutions( std::initializer_list<std::pair<std::string, std::string>> il); // Run all output tests. void RunOutputTests(int argc, char* argv[]); // Count the number of 'pat' substrings in the 'haystack' string. int SubstrCnt(const std::string& haystack, const std::string& pat); // Run registered benchmarks with file reporter enabled, and return the content // outputted by the file reporter. std::string GetFileReporterOutput(int argc, char* argv[]); // ========================================================================= // // ------------------------- Results checking ------------------------------ // // ========================================================================= // // Call this macro to register a benchmark for checking its results. This // should be all that's needed. It subscribes a function to check the (CSV) // results of a benchmark. This is done only after verifying that the output // strings are really as expected. // bm_name_pattern: a name or a regex pattern which will be matched against // all the benchmark names. Matching benchmarks // will be the subject of a call to checker_function // checker_function: should be of type ResultsCheckFn (see below) #define CHECK_BENCHMARK_RESULTS(bm_name_pattern, checker_function) \ size_t CONCAT(dummy, __LINE__) = AddChecker(bm_name_pattern, checker_function) struct Results; typedef std::function<void(Results const&)> ResultsCheckFn; size_t AddChecker(const char* bm_name_pattern, const ResultsCheckFn& fn); // Class holding the results of a benchmark. // It is passed in calls to checker functions. struct Results { // the benchmark name std::string name; // the benchmark fields std::map<std::string, std::string> values; Results(const std::string& n) : name(n) {} int NumThreads() const; double NumIterations() const; typedef enum { kCpuTime, kRealTime } BenchmarkTime; // get cpu_time or real_time in seconds double GetTime(BenchmarkTime which) const; // get the real_time duration of the benchmark in seconds. // it is better to use fuzzy float checks for this, as the float // ASCII formatting is lossy. double DurationRealTime() const { return NumIterations() * GetTime(kRealTime); } // get the cpu_time duration of the benchmark in seconds double DurationCPUTime() const { return NumIterations() * GetTime(kCpuTime); } // get the string for a result by name, or nullptr if the name // is not found const std::string* Get(const char* entry_name) const { auto it = values.find(entry_name); if (it == values.end()) return nullptr; return &it->second; } // get a result by name, parsed as a specific type. // NOTE: for counters, use GetCounterAs instead. template <class T> T GetAs(const char* entry_name) const; // counters are written as doubles, so they have to be read first // as a double, and only then converted to the asked type. template <class T> T GetCounterAs(const char* entry_name) const { double dval = GetAs<double>(entry_name); T tval = static_cast<T>(dval); return tval; } }; template <class T> T Results::GetAs(const char* entry_name) const { auto* sv = Get(entry_name); BM_CHECK(sv != nullptr && !sv->empty()); std::stringstream ss; ss << *sv; T out; ss >> out; BM_CHECK(!ss.fail()); return out; } //---------------------------------- // Macros to help in result checking. Do not use them with arguments causing // side-effects. // clang-format off #define CHECK_RESULT_VALUE_IMPL(entry, getfn, var_type, var_name, relationship, value) \ CONCAT(BM_CHECK_, relationship) \ (entry.getfn< var_type >(var_name), (value)) << "\n" \ << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ << __FILE__ << ":" << __LINE__ << ": " \ << "expected (" << #var_type << ")" << (var_name) \ << "=" << (entry).getfn< var_type >(var_name) \ << " to be " #relationship " to " << (value) << "\n" // check with tolerance. eps_factor is the tolerance window, which is // interpreted relative to value (eg, 0.1 means 10% of value). #define CHECK_FLOAT_RESULT_VALUE_IMPL(entry, getfn, var_type, var_name, relationship, value, eps_factor) \ CONCAT(BM_CHECK_FLOAT_, relationship) \ (entry.getfn< var_type >(var_name), (value), (eps_factor) * (value)) << "\n" \ << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ << __FILE__ << ":" << __LINE__ << ": " \ << "expected (" << #var_type << ")" << (var_name) \ << "=" << (entry).getfn< var_type >(var_name) \ << " to be " #relationship " to " << (value) << "\n" \ << __FILE__ << ":" << __LINE__ << ": " \ << "with tolerance of " << (eps_factor) * (value) \ << " (" << (eps_factor)*100. << "%), " \ << "but delta was " << ((entry).getfn< var_type >(var_name) - (value)) \ << " (" << (((entry).getfn< var_type >(var_name) - (value)) \ / \ ((value) > 1.e-5 || value < -1.e-5 ? value : 1.e-5)*100.) \ << "%)" #define CHECK_RESULT_VALUE(entry, var_type, var_name, relationship, value) \ CHECK_RESULT_VALUE_IMPL(entry, GetAs, var_type, var_name, relationship, value) #define CHECK_COUNTER_VALUE(entry, var_type, var_name, relationship, value) \ CHECK_RESULT_VALUE_IMPL(entry, GetCounterAs, var_type, var_name, relationship, value) #define CHECK_FLOAT_RESULT_VALUE(entry, var_name, relationship, value, eps_factor) \ CHECK_FLOAT_RESULT_VALUE_IMPL(entry, GetAs, double, var_name, relationship, value, eps_factor) #define CHECK_FLOAT_COUNTER_VALUE(entry, var_name, relationship, value, eps_factor) \ CHECK_FLOAT_RESULT_VALUE_IMPL(entry, GetCounterAs, double, var_name, relationship, value, eps_factor) // clang-format on // ========================================================================= // // --------------------------- Misc Utilities ------------------------------ // // ========================================================================= // namespace { const char* const dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"; } // end namespace #endif // TEST_OUTPUT_TEST_H
7,900
36.268868
106
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/gmock-cardinalities.h
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used cardinalities. More // cardinalities can be defined by the user implementing the // CardinalityInterface interface if necessary. // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #include <limits.h> #include <memory> #include <ostream> // NOLINT #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // To implement a cardinality Foo, define: // 1. a class FooCardinality that implements the // CardinalityInterface interface, and // 2. a factory function that creates a Cardinality object from a // const FooCardinality*. // // The two-level delegation design follows that of Matcher, providing // consistency for extension developers. It also eases ownership // management as Cardinality objects can now be copied like plain values. // The implementation of a cardinality. class CardinalityInterface { public: virtual ~CardinalityInterface() {} // Conservative estimate on the lower/upper bound of the number of // calls allowed. virtual int ConservativeLowerBound() const { return 0; } virtual int ConservativeUpperBound() const { return INT_MAX; } // Returns true if and only if call_count calls will satisfy this // cardinality. virtual bool IsSatisfiedByCallCount(int call_count) const = 0; // Returns true if and only if call_count calls will saturate this // cardinality. virtual bool IsSaturatedByCallCount(int call_count) const = 0; // Describes self to an ostream. virtual void DescribeTo(::std::ostream* os) const = 0; }; // A Cardinality is a copyable and IMMUTABLE (except by assignment) // object that specifies how many times a mock function is expected to // be called. The implementation of Cardinality is just a std::shared_ptr // to const CardinalityInterface. Don't inherit from Cardinality! class GTEST_API_ Cardinality { public: // Constructs a null cardinality. Needed for storing Cardinality // objects in STL containers. Cardinality() {} // Constructs a Cardinality from its implementation. explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} // Conservative estimate on the lower/upper bound of the number of // calls allowed. int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } // Returns true if and only if call_count calls will satisfy this // cardinality. bool IsSatisfiedByCallCount(int call_count) const { return impl_->IsSatisfiedByCallCount(call_count); } // Returns true if and only if call_count calls will saturate this // cardinality. bool IsSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count); } // Returns true if and only if call_count calls will over-saturate this // cardinality, i.e. exceed the maximum number of allowed calls. bool IsOverSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count) && !impl_->IsSatisfiedByCallCount(call_count); } // Describes self to an ostream void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } // Describes the given actual call count to an ostream. static void DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os); private: std::shared_ptr<const CardinalityInterface> impl_; }; // Creates a cardinality that allows at least n calls. GTEST_API_ Cardinality AtLeast(int n); // Creates a cardinality that allows at most n calls. GTEST_API_ Cardinality AtMost(int n); // Creates a cardinality that allows any number of calls. GTEST_API_ Cardinality AnyNumber(); // Creates a cardinality that allows between min and max calls. GTEST_API_ Cardinality Between(int min, int max); // Creates a cardinality that allows exactly n calls. GTEST_API_ Cardinality Exactly(int n); // Creates a cardinality from its implementation. inline Cardinality MakeCardinality(const CardinalityInterface* c) { return Cardinality(c); } } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
6,102
37.14375
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/gmock-more-matchers.h
// Copyright 2013, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file implements some matchers that depend on gmock-matchers.h. // // Note that tests are implemented in gmock-matchers_test.cc rather than // gmock-more-matchers-test.cc. // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #include <ostream> #include <string> #include "gmock/gmock-matchers.h" namespace testing { // Silence C4100 (unreferenced formal // parameter) for MSVC #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) #if (_MSC_VER == 1900) // and silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 14 #pragma warning(disable : 4800) #endif #endif namespace internal { // Implements the polymorphic IsEmpty matcher, which // can be used as a Matcher<T> as long as T is either a container that defines // empty() and size() (e.g. std::vector or std::string), or a C-style string. class IsEmptyMatcher { public: // Matches anything that defines empty() and size(). template <typename MatcheeContainerType> bool MatchAndExplain(const MatcheeContainerType& c, MatchResultListener* listener) const { if (c.empty()) { return true; } *listener << "whose size is " << c.size(); return false; } // Matches C-style strings. bool MatchAndExplain(const char* s, MatchResultListener* listener) const { return MatchAndExplain(std::string(s), listener); } // Describes what this matcher matches. void DescribeTo(std::ostream* os) const { *os << "is empty"; } void DescribeNegationTo(std::ostream* os) const { *os << "isn't empty"; } }; } // namespace internal // Creates a polymorphic matcher that matches an empty container or C-style // string. The container must support both size() and empty(), which all // STL-like containers provide. inline PolymorphicMatcher<internal::IsEmptyMatcher> IsEmpty() { return MakePolymorphicMatcher(internal::IsEmptyMatcher()); } // Define a matcher that matches a value that evaluates in boolean // context to true. Useful for types that define "explicit operator // bool" operators and so can't be compared for equality with true // and false. MATCHER(IsTrue, negation ? "is false" : "is true") { return static_cast<bool>(arg); } // Define a matcher that matches a value that evaluates in boolean // context to false. Useful for types that define "explicit operator // bool" operators and so can't be compared for equality with true // and false. MATCHER(IsFalse, negation ? "is true" : "is false") { return !static_cast<bool>(arg); } #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace testing #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
4,416
34.910569
78
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/gmock-nice-strict.h
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Implements class templates NiceMock, NaggyMock, and StrictMock. // // Given a mock class MockFoo that is created using Google Mock, // NiceMock<MockFoo> is a subclass of MockFoo that allows // uninteresting calls (i.e. calls to mock methods that have no // EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo // that prints a warning when an uninteresting call occurs, and // StrictMock<MockFoo> is a subclass of MockFoo that treats all // uninteresting calls as errors. // // Currently a mock is naggy by default, so MockFoo and // NaggyMock<MockFoo> behave like the same. However, we will soon // switch the default behavior of mocks to be nice, as that in general // leads to more maintainable tests. When that happens, MockFoo will // stop behaving like NaggyMock<MockFoo> and start behaving like // NiceMock<MockFoo>. // // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of // their respective base class. Therefore you can write // NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo // has a constructor that accepts (int, const char*), for example. // // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>, // and StrictMock<MockFoo> only works for mock methods defined using // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. // If a mock method is defined in a base class of MockFoo, the "nice" // or "strict" modifier may not affect it, depending on the compiler. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #include <cstdint> #include <type_traits> #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-port.h" namespace testing { template <class MockClass> class NiceMock; template <class MockClass> class NaggyMock; template <class MockClass> class StrictMock; namespace internal { template <typename T> std::true_type StrictnessModifierProbe(const NiceMock<T>&); template <typename T> std::true_type StrictnessModifierProbe(const NaggyMock<T>&); template <typename T> std::true_type StrictnessModifierProbe(const StrictMock<T>&); std::false_type StrictnessModifierProbe(...); template <typename T> constexpr bool HasStrictnessModifier() { return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value; } // Base classes that register and deregister with testing::Mock to alter the // default behavior around uninteresting calls. Inheriting from one of these // classes first and then MockClass ensures the MockClass constructor is run // after registration, and that the MockClass destructor runs before // deregistration. This guarantees that MockClass's constructor and destructor // run with the same level of strictness as its instance methods. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \ (defined(_MSC_VER) || defined(__clang__)) // We need to mark these classes with this declspec to ensure that // the empty base class optimization is performed. #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases) #else #define GTEST_INTERNAL_EMPTY_BASE_CLASS #endif template <typename Base> class NiceMockImpl { public: NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; template <typename Base> class NaggyMockImpl { public: NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; template <typename Base> class StrictMockImpl { public: StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; } // namespace internal template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock : private internal::NiceMockImpl<MockClass>, public MockClass { public: static_assert(!internal::HasStrictnessModifier<MockClass>(), "Can't apply NiceMock to a class hierarchy that already has a " "strictness modifier. See " "https://google.github.io/googletest/" "gmock_cook_book.html#NiceStrictNaggy"); NiceMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected // constructors as public. These tests would need to be cleaned up first. // Single argument constructor is special-cased so that it can be // made explicit. template <typename A> explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: NiceMock(const NiceMock&) = delete; NiceMock& operator=(const NiceMock&) = delete; }; template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock : private internal::NaggyMockImpl<MockClass>, public MockClass { static_assert(!internal::HasStrictnessModifier<MockClass>(), "Can't apply NaggyMock to a class hierarchy that already has a " "strictness modifier. See " "https://google.github.io/googletest/" "gmock_cook_book.html#NiceStrictNaggy"); public: NaggyMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected // constructors as public. These tests would need to be cleaned up first. // Single argument constructor is special-cased so that it can be // made explicit. template <typename A> explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: NaggyMock(const NaggyMock&) = delete; NaggyMock& operator=(const NaggyMock&) = delete; }; template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock : private internal::StrictMockImpl<MockClass>, public MockClass { public: static_assert( !internal::HasStrictnessModifier<MockClass>(), "Can't apply StrictMock to a class hierarchy that already has a " "strictness modifier. See " "https://google.github.io/googletest/" "gmock_cook_book.html#NiceStrictNaggy"); StrictMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected // constructors as public. These tests would need to be cleaned up first. // Single argument constructor is special-cased so that it can be // made explicit. template <typename A> explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: StrictMock(const StrictMock&) = delete; StrictMock& operator=(const StrictMock&) = delete; }; #undef GTEST_INTERNAL_EMPTY_BASE_CLASS } // namespace testing #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
10,840
37.996403
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/gmock.h
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This is the main header file a user should include. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_ // This file implements the following syntax: // // ON_CALL(mock_object, Method(...)) // .With(...) ? // .WillByDefault(...); // // where With() is optional and WillByDefault() must appear exactly // once. // // EXPECT_CALL(mock_object, Method(...)) // .With(...) ? // .Times(...) ? // .InSequence(...) * // .WillOnce(...) * // .WillRepeatedly(...) ? // .RetiresOnSaturation() ? ; // // where all clauses are optional and WillOnce() can be repeated. #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-function-mocker.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-matchers.h" #include "gmock/gmock-nice-strict.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" // Declares Google Mock flags that we want a user to use programmatically. GMOCK_DECLARE_bool_(catch_leaked_mocks); GMOCK_DECLARE_string_(verbose); GMOCK_DECLARE_int32_(default_mock_behavior); namespace testing { // Initializes Google Mock. This must be called before running the // tests. In particular, it parses the command line for the flags // that Google Mock recognizes. Whenever a Google Mock flag is seen, // it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Mock flag variables are // updated. // // Since Google Test is needed for Google Mock to work, this function // also initializes Google Test and parses its flags, if that hasn't // been done. GTEST_API_ void InitGoogleMock(int* argc, char** argv); // This overloaded version can be used in Windows programs compiled in // UNICODE mode. GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv); // This overloaded version can be used on Arduino/embedded platforms where // there is no argc/argv. GTEST_API_ void InitGoogleMock(); } // namespace testing #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
3,723
37.391753
74
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/internal/gmock-internal-utils.h
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file defines some utilities useful for implementing Google // Mock. They are subject to change without notice, so please DO NOT // USE THEM IN USER CODE. // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #include <stdio.h> #include <ostream> // NOLINT #include <string> #include <type_traits> #include <vector> #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { template <typename> class Matcher; namespace internal { // Silence MSVC C4100 (unreferenced formal parameter) and // C4805('==': unsafe mix of type 'const int' and type 'const bool') #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) #pragma warning(disable : 4805) #endif // Joins a vector of strings as if they are fields of a tuple; returns // the joined string. GTEST_API_ std::string JoinAsKeyValueTuple( const std::vector<const char*>& names, const Strings& values); // Converts an identifier name to a space-separated list of lower-case // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is // treated as one word. For example, both "FooBar123" and // "foo_bar_123" are converted to "foo bar 123". GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name); // GetRawPointer(p) returns the raw pointer underlying p when p is a // smart pointer, or returns p itself when p is already a raw pointer. // The following default implementation is for the smart pointer case. template <typename Pointer> inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { return p.get(); } // This overload version is for std::reference_wrapper, which does not work with // the overload above, as it does not have an `element_type`. template <typename Element> inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) { return &r.get(); } // This overloaded version is for the raw pointer case. template <typename Element> inline Element* GetRawPointer(Element* p) { return p; } // Default definitions for all compilers. // NOTE: If you implement support for other compilers, make sure to avoid // unexpected overlaps. // (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.) #define GMOCK_INTERNAL_WARNING_PUSH() #define GMOCK_INTERNAL_WARNING_CLANG(Level, Name) #define GMOCK_INTERNAL_WARNING_POP() #if defined(__clang__) #undef GMOCK_INTERNAL_WARNING_PUSH #define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push") #undef GMOCK_INTERNAL_WARNING_CLANG #define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \ _Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning)) #undef GMOCK_INTERNAL_WARNING_POP #define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop") #endif // MSVC treats wchar_t as a native type usually, but treats it as the // same as unsigned short when the compiler option /Zc:wchar_t- is // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t // is a native type. #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) // wchar_t is a typedef. #else #define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif // In what follows, we use the term "kind" to indicate whether a type // is bool, an integer type (excluding bool), a floating-point type, // or none of them. This categorization is useful for determining // when a matcher argument type can be safely converted to another // type in the implementation of SafeMatcherCast. enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; // KindOf<T>::value is the kind of type T. template <typename T> struct KindOf { enum { value = kOther }; // The default kind. }; // This macro declares that the kind of 'type' is 'kind'. #define GMOCK_DECLARE_KIND_(type, kind) \ template <> \ struct KindOf<type> { \ enum { value = kind }; \ } GMOCK_DECLARE_KIND_(bool, kBool); // All standard integer types. GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DECLARE_KIND_(wchar_t, kInteger); #endif // All standard floating-point types. GMOCK_DECLARE_KIND_(float, kFloatingPoint); GMOCK_DECLARE_KIND_(double, kFloatingPoint); GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ // Evaluates to the kind of 'type'. #define GMOCK_KIND_OF_(type) \ static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf<type>::value) // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value // is true if and only if arithmetic type From can be losslessly converted to // arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a // reference) built-in arithmetic types, kFromKind is the kind of // From, and kToKind is the kind of To; the value is // implementation-defined when the above pre-condition is violated. template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To> using LosslessArithmeticConvertibleImpl = std::integral_constant< bool, // clang-format off // Converting from bool is always lossless (kFromKind == kBool) ? true // Converting between any other type kinds will be lossy if the type // kinds are not the same. : (kFromKind != kToKind) ? false : (kFromKind == kInteger && // Converting between integers of different widths is allowed so long // as the conversion does not go from signed to unsigned. (((sizeof(From) < sizeof(To)) && !(std::is_signed<From>::value && !std::is_signed<To>::value)) || // Converting between integers of the same width only requires the // two types to have the same signedness. ((sizeof(From) == sizeof(To)) && (std::is_signed<From>::value == std::is_signed<To>::value))) ) ? true // Floating point conversions are lossless if and only if `To` is at least // as wide as `From`. : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true : false // clang-format on >; // LosslessArithmeticConvertible<From, To>::value is true if and only if // arithmetic type From can be losslessly converted to arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a // reference) built-in arithmetic types; the value is // implementation-defined when the above pre-condition is violated. template <typename From, typename To> using LosslessArithmeticConvertible = LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To>; // This interface knows how to report a Google Mock failure (either // non-fatal or fatal). class FailureReporterInterface { public: // The type of a failure (either non-fatal or fatal). enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() {} // Reports a failure that occurred at the given source file location. virtual void ReportFailure(FailureType type, const char* file, int line, const std::string& message) = 0; }; // Returns the failure reporter used by Google Mock. GTEST_API_ FailureReporterInterface* GetFailureReporter(); // Asserts that condition is true; aborts the process with the given // message if condition is false. We cannot use LOG(FATAL) or CHECK() // as Google Mock might be used to mock the log sink itself. We // inline this function to prevent it from showing up in the stack // trace. inline void Assert(bool condition, const char* file, int line, const std::string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, line, msg); } } inline void Assert(bool condition, const char* file, int line) { Assert(condition, file, line, "Assertion failed."); } // Verifies that condition is true; generates a non-fatal failure if // condition is false. inline void Expect(bool condition, const char* file, int line, const std::string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, file, line, msg); } } inline void Expect(bool condition, const char* file, int line) { Expect(condition, file, line, "Expectation failed."); } // Severity level of a log. enum LogSeverity { kInfo = 0, kWarning = 1 }; // Valid values for the --gmock_verbose flag. // All logs (informational and warnings) are printed. const char kInfoVerbosity[] = "info"; // Only warnings are printed. const char kWarningVerbosity[] = "warning"; // No logs are printed. const char kErrorVerbosity[] = "error"; // Returns true if and only if a log with the given severity is visible // according to the --gmock_verbose flag. GTEST_API_ bool LogIsVisible(LogSeverity severity); // Prints the given message to stdout if and only if 'severity' >= the level // specified by the --gmock_verbose flag. If stack_frames_to_skip >= // 0, also prints the stack trace excluding the top // stack_frames_to_skip frames. In opt mode, any positive // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip); // A marker class that is used to resolve parameterless expectations to the // correct overload. This must not be instantiable, to prevent client code from // accidentally resolving to the overload; for example: // // ON_CALL(mock, Method({}, nullptr))... // class WithoutMatchers { private: WithoutMatchers() {} friend GTEST_API_ WithoutMatchers GetWithoutMatchers(); }; // Internal use only: access the singleton instance of WithoutMatchers. GTEST_API_ WithoutMatchers GetWithoutMatchers(); // Invalid<T>() is usable as an expression of type T, but will terminate // the program with an assertion failure if actually run. This is useful // when a value of type T is needed for compilation, but the statement // will not really be executed (or we don't care if the statement // crashes). template <typename T> inline T Invalid() { Assert(false, "", -1, "Internal error: attempt to return invalid value"); #if defined(__GNUC__) || defined(__clang__) __builtin_unreachable(); #elif defined(_MSC_VER) __assume(0); #else return Invalid<T>(); #endif } // Given a raw type (i.e. having no top-level reference or const // modifier) RawContainer that's either an STL-style container or a // native array, class StlContainerView<RawContainer> has the // following members: // // - type is a type that provides an STL-style container view to // (i.e. implements the STL container concept for) RawContainer; // - const_reference is a type that provides a reference to a const // RawContainer; // - ConstReference(raw_container) returns a const reference to an STL-style // container view to raw_container, which is a RawContainer. // - Copy(raw_container) returns an STL-style container view of a // copy of raw_container, which is a RawContainer. // // This generic version is used when RawContainer itself is already an // STL-style container. template <class RawContainer> class StlContainerView { public: typedef RawContainer type; typedef const type& const_reference; static const_reference ConstReference(const RawContainer& container) { static_assert(!std::is_const<RawContainer>::value, "RawContainer type must not be const"); return container; } static type Copy(const RawContainer& container) { return container; } }; // This specialization is used when RawContainer is a native array type. template <typename Element, size_t N> class StlContainerView<Element[N]> { public: typedef typename std::remove_const<Element>::type RawElement; typedef internal::NativeArray<RawElement> type; // NativeArray<T> can represent a native array either by value or by // reference (selected by a constructor argument), so 'const type' // can be used to reference a const native array. We cannot // 'typedef const type& const_reference' here, as that would mean // ConstReference() has to return a reference to a local variable. typedef const type const_reference; static const_reference ConstReference(const Element (&array)[N]) { static_assert(std::is_same<Element, RawElement>::value, "Element type must not be const"); return type(array, N, RelationToSourceReference()); } static type Copy(const Element (&array)[N]) { return type(array, N, RelationToSourceCopy()); } }; // This specialization is used when RawContainer is a native array // represented as a (pointer, size) tuple. template <typename ElementPointer, typename Size> class StlContainerView< ::std::tuple<ElementPointer, Size> > { public: typedef typename std::remove_const< typename std::pointer_traits<ElementPointer>::element_type>::type RawElement; typedef internal::NativeArray<RawElement> type; typedef const type const_reference; static const_reference ConstReference( const ::std::tuple<ElementPointer, Size>& array) { return type(std::get<0>(array), std::get<1>(array), RelationToSourceReference()); } static type Copy(const ::std::tuple<ElementPointer, Size>& array) { return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy()); } }; // The following specialization prevents the user from instantiating // StlContainer with a reference type. template <typename T> class StlContainerView<T&>; // A type transform to remove constness from the first part of a pair. // Pairs like that are used as the value_type of associative containers, // and this transform produces a similar but assignable pair. template <typename T> struct RemoveConstFromKey { typedef T type; }; // Partially specialized to remove constness from std::pair<const K, V>. template <typename K, typename V> struct RemoveConstFromKey<std::pair<const K, V> > { typedef std::pair<K, V> type; }; // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to // reduce code size. GTEST_API_ void IllegalDoDefault(const char* file, int line); template <typename F, typename Tuple, size_t... Idx> auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(std::forward<F>(f)( std::get<Idx>(std::forward<Tuple>(args))...)) { return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...); } // Apply the function to a tuple of arguments. template <typename F, typename Tuple> auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl( std::forward<F>(f), std::forward<Tuple>(args), MakeIndexSequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>())) { return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), MakeIndexSequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>()); } // Template struct Function<F>, where F must be a function type, contains // the following typedefs: // // Result: the function's return type. // Arg<N>: the type of the N-th argument, where N starts with 0. // ArgumentTuple: the tuple type consisting of all parameters of F. // ArgumentMatcherTuple: the tuple type consisting of Matchers for all // parameters of F. // MakeResultVoid: the function type obtained by substituting void // for the return type of F. // MakeResultIgnoredValue: // the function type obtained by substituting Something // for the return type of F. template <typename T> struct Function; template <typename R, typename... Args> struct Function<R(Args...)> { using Result = R; static constexpr size_t ArgumentCount = sizeof...(Args); template <size_t I> using Arg = ElemFromList<I, Args...>; using ArgumentTuple = std::tuple<Args...>; using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; using MakeResultVoid = void(Args...); using MakeResultIgnoredValue = IgnoredValue(Args...); }; template <typename R, typename... Args> constexpr size_t Function<R(Args...)>::ArgumentCount; // Workaround for MSVC error C2039: 'type': is not a member of 'std' // when std::tuple_element is used. // See: https://github.com/google/googletest/issues/3931 // Can be replaced with std::tuple_element_t in C++14. template <size_t I, typename T> using TupleElement = typename std::tuple_element<I, T>::type; bool Base64Unescape(const std::string& encoded, std::string* decoded); #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace internal } // namespace testing #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
19,325
38.360489
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/internal/gmock-port.h
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Low-level types and utilities for porting Google Mock to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Mock's public API and can be used by // code outside Google Mock. // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #include <assert.h> #include <stdlib.h> #include <cstdint> #include <iostream> // Most of the utilities needed for porting Google Mock are also // required for Google Test and are defined in gtest-port.h. // // Note to maintainers: to reduce code duplication, prefer adding // portability utilities to Google Test's gtest-port.h instead of // here, as Google Mock depends on Google Test. Only add a utility // here if it's truly specific to Google Mock. #include "gmock/internal/custom/gmock-port.h" #include "gtest/internal/gtest-port.h" #if GTEST_HAS_ABSL #include "absl/flags/declare.h" #include "absl/flags/flag.h" #endif // For MS Visual C++, check the compiler version. At least VS 2015 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1900 #error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." #endif // Macro for referencing flags. This is public as we want the user to // use this syntax to reference Google Mock flags. #define GMOCK_FLAG_NAME_(name) gmock_##name #define GMOCK_FLAG(name) FLAGS_gmock_##name // Pick a command line flags implementation. #if GTEST_HAS_ABSL // Macros for defining flags. #define GMOCK_DEFINE_bool_(name, default_val, doc) \ ABSL_FLAG(bool, GMOCK_FLAG_NAME_(name), default_val, doc) #define GMOCK_DEFINE_int32_(name, default_val, doc) \ ABSL_FLAG(int32_t, GMOCK_FLAG_NAME_(name), default_val, doc) #define GMOCK_DEFINE_string_(name, default_val, doc) \ ABSL_FLAG(std::string, GMOCK_FLAG_NAME_(name), default_val, doc) // Macros for declaring flags. #define GMOCK_DECLARE_bool_(name) \ ABSL_DECLARE_FLAG(bool, GMOCK_FLAG_NAME_(name)) #define GMOCK_DECLARE_int32_(name) \ ABSL_DECLARE_FLAG(int32_t, GMOCK_FLAG_NAME_(name)) #define GMOCK_DECLARE_string_(name) \ ABSL_DECLARE_FLAG(std::string, GMOCK_FLAG_NAME_(name)) #define GMOCK_FLAG_GET(name) ::absl::GetFlag(GMOCK_FLAG(name)) #define GMOCK_FLAG_SET(name, value) \ (void)(::absl::SetFlag(&GMOCK_FLAG(name), value)) #else // GTEST_HAS_ABSL // Macros for defining flags. #define GMOCK_DEFINE_bool_(name, default_val, doc) \ namespace testing { \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DEFINE_int32_(name, default_val, doc) \ namespace testing { \ GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DEFINE_string_(name, default_val, doc) \ namespace testing { \ GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \ } \ static_assert(true, "no-op to require trailing semicolon") // Macros for declaring flags. #define GMOCK_DECLARE_bool_(name) \ namespace testing { \ GTEST_API_ extern bool GMOCK_FLAG(name); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DECLARE_int32_(name) \ namespace testing { \ GTEST_API_ extern int32_t GMOCK_FLAG(name); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DECLARE_string_(name) \ namespace testing { \ GTEST_API_ extern ::std::string GMOCK_FLAG(name); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name) #define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value) #endif // GTEST_HAS_ABSL #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
6,064
42.321429
79
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/internal/gmock-pp.h
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ // Expands and concatenates the arguments. Constructed macros reevaluate. #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2) // Expands and stringifies the only argument. #define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__) // Returns empty. Given a variadic number of arguments. #define GMOCK_PP_EMPTY(...) // Returns a comma. Given a variadic number of arguments. #define GMOCK_PP_COMMA(...) , // Returns the only argument. #define GMOCK_PP_IDENTITY(_1) _1 // Evaluates to the number of arguments after expansion. // // #define PAIR x, y // // GMOCK_PP_NARG() => 1 // GMOCK_PP_NARG(x) => 1 // GMOCK_PP_NARG(x, y) => 2 // GMOCK_PP_NARG(PAIR) => 2 // // Requires: the number of arguments after expansion is at most 15. #define GMOCK_PP_NARG(...) \ GMOCK_PP_INTERNAL_16TH( \ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise // returns 0. Requires no more than 15 unprotected commas. #define GMOCK_PP_HAS_COMMA(...) \ GMOCK_PP_INTERNAL_16TH( \ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)) // Returns the first argument. #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg)) // Returns the tail. A variadic list of all arguments minus the first. Requires // at least one argument. #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__)) // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__) #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ GMOCK_PP_IDENTITY( \ GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)) // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise // evaluates to `0`. // // Requires: * the number of arguments after expansion is at most 15. // * If the argument is a macro, it must be able to be called with one // argument. // // Implementation details: // // There is one case when it generates a compile error: if the argument is macro // that cannot be called with one argument. // // #define M(a, b) // it doesn't matter what it expands to // // // Expected: expands to `0`. // // Actual: compile error. // GMOCK_PP_IS_EMPTY(M) // // There are 4 cases tested: // // * __VA_ARGS__ possible expansion has no unparen'd commas. Expected 0. // * __VA_ARGS__ possible expansion is not enclosed in parenthesis. Expected 0. // * __VA_ARGS__ possible expansion is not a macro that ()-evaluates to a comma. // Expected 0 // * __VA_ARGS__ is empty, or has unparen'd commas, or is enclosed in // parenthesis, or is a macro that ()-evaluates to comma. Expected 1. // // We trigger detection on '0001', i.e. on empty. #define GMOCK_PP_IS_EMPTY(...) \ GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \ GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \ GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \ GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__())) // Evaluates to _Then if _Cond is 1 and _Else if _Cond is 0. #define GMOCK_PP_IF(_Cond, _Then, _Else) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else) // Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses. // // GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c // GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f // #define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \ GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else)) // Evaluates to the number of arguments after expansion. Identifies 'empty' as // 0. // // #define PAIR x, y // // GMOCK_PP_NARG0() => 0 // GMOCK_PP_NARG0(x) => 1 // GMOCK_PP_NARG0(x, y) => 2 // GMOCK_PP_NARG0(PAIR) => 2 // // Requires: * the number of arguments after expansion is at most 15. // * If the argument is a macro, it must be able to be called with one // argument. #define GMOCK_PP_NARG0(...) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__)) // Expands to 1 if the first argument starts with something in parentheses, // otherwise to 0. #define GMOCK_PP_IS_BEGIN_PARENS(...) \ GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \ GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__)) // Expands to 1 is there is only one argument and it is enclosed in parentheses. #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \ GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \ GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0) // Remove the parens, requires GMOCK_PP_IS_ENCLOSED_PARENS(args) => 1. #define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__ // Expands to _Macro(0, _Data, e1) _Macro(1, _Data, e2) ... _Macro(K -1, _Data, // eK) as many of GMOCK_INTERNAL_NARG0 _Tuple. // Requires: * |_Macro| can be called with 3 arguments. // * |_Tuple| expansion has no more than 15 elements. #define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \ (0, _Macro, _Data, _Tuple) // Expands to _Macro(0, _Data, ) _Macro(1, _Data, ) ... _Macro(K - 1, _Data, ) // Empty if _K = 0. // Requires: * |_Macro| can be called with 3 arguments. // * |_K| literal between 0 and 15 #define GMOCK_PP_REPEAT(_Macro, _Data, _N) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \ (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE) // Increments the argument, requires the argument to be between 0 and 15. #define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i) // Returns comma if _i != 0. Requires _i to be between 0 and 15. #define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i) // Internal details follow. Do not use any of these symbols outside of this // file or we will break your code. #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , ) #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__ #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5 #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \ _1, _2, _3, _4)) #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 , #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else // Because of MSVC treating a token with a comma in it as a single token when // passed to another macro, we need to force it to evaluate it as multiple // tokens. We do that by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. We // define one per possible macro that relies on this behavior. Note "_Args" must // be parenthesized. #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \ _10, _11, _12, _13, _14, _15, _16, \ ...) \ _16 #define GMOCK_PP_INTERNAL_16TH(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args) #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1 #define GMOCK_PP_INTERNAL_HEAD(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args) #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__ #define GMOCK_PP_INTERNAL_TAIL(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \ 0, #define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__ #define GMOCK_PP_INTERNAL_INC_0 1 #define GMOCK_PP_INTERNAL_INC_1 2 #define GMOCK_PP_INTERNAL_INC_2 3 #define GMOCK_PP_INTERNAL_INC_3 4 #define GMOCK_PP_INTERNAL_INC_4 5 #define GMOCK_PP_INTERNAL_INC_5 6 #define GMOCK_PP_INTERNAL_INC_6 7 #define GMOCK_PP_INTERNAL_INC_7 8 #define GMOCK_PP_INTERNAL_INC_8 9 #define GMOCK_PP_INTERNAL_INC_9 10 #define GMOCK_PP_INTERNAL_INC_10 11 #define GMOCK_PP_INTERNAL_INC_11 12 #define GMOCK_PP_INTERNAL_INC_12 13 #define GMOCK_PP_INTERNAL_INC_13 14 #define GMOCK_PP_INTERNAL_INC_14 15 #define GMOCK_PP_INTERNAL_INC_15 16 #define GMOCK_PP_INTERNAL_COMMA_IF_0 #define GMOCK_PP_INTERNAL_COMMA_IF_1 , #define GMOCK_PP_INTERNAL_COMMA_IF_2 , #define GMOCK_PP_INTERNAL_COMMA_IF_3 , #define GMOCK_PP_INTERNAL_COMMA_IF_4 , #define GMOCK_PP_INTERNAL_COMMA_IF_5 , #define GMOCK_PP_INTERNAL_COMMA_IF_6 , #define GMOCK_PP_INTERNAL_COMMA_IF_7 , #define GMOCK_PP_INTERNAL_COMMA_IF_8 , #define GMOCK_PP_INTERNAL_COMMA_IF_9 , #define GMOCK_PP_INTERNAL_COMMA_IF_10 , #define GMOCK_PP_INTERNAL_COMMA_IF_11 , #define GMOCK_PP_INTERNAL_COMMA_IF_12 , #define GMOCK_PP_INTERNAL_COMMA_IF_13 , #define GMOCK_PP_INTERNAL_COMMA_IF_14 , #define GMOCK_PP_INTERNAL_COMMA_IF_15 , #define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \ _Macro(_i, _Data, _element) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
13,491
47.185714
81
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/internal/custom/gmock-matchers.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Injection point for custom user configurations. See README for details // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
1,918
49.5
73
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/include/gmock/internal/custom/gmock-port.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
1,953
46.658537
73
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/test/gmock-matchers_test.h
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file tests some commonly used argument matchers. #ifndef GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_ #define GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_ #include <string.h> #include <time.h> #include <array> #include <cstdint> #include <deque> #include <forward_list> #include <functional> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-matchers.h" #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" namespace testing { namespace gmock_matchers_test { using std::greater; using std::less; using std::list; using std::make_pair; using std::map; using std::multimap; using std::multiset; using std::ostream; using std::pair; using std::set; using std::stringstream; using std::vector; using testing::internal::DummyMatchResultListener; using testing::internal::ElementMatcherPair; using testing::internal::ElementMatcherPairs; using testing::internal::ElementsAreArrayMatcher; using testing::internal::ExplainMatchFailureTupleTo; using testing::internal::FloatingEqMatcher; using testing::internal::FormatMatcherDescription; using testing::internal::IsReadableTypeName; using testing::internal::MatchMatrix; using testing::internal::PredicateFormatterFromMatcher; using testing::internal::RE; using testing::internal::StreamMatchResultListener; using testing::internal::Strings; // Helper for testing container-valued matchers in mock method context. It is // important to test matchers in this context, since it requires additional type // deduction beyond what EXPECT_THAT does, thus making it more restrictive. struct ContainerHelper { MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>)); }; // For testing ExplainMatchResultTo(). template <typename T> struct GtestGreaterThanMatcher { using is_gtest_matcher = void; void DescribeTo(ostream* os) const { *os << "is > " << rhs; } void DescribeNegationTo(ostream* os) const { *os << "is <= " << rhs; } bool MatchAndExplain(T lhs, MatchResultListener* listener) const { if (lhs > rhs) { *listener << "which is " << (lhs - rhs) << " more than " << rhs; } else if (lhs == rhs) { *listener << "which is the same as " << rhs; } else { *listener << "which is " << (rhs - lhs) << " less than " << rhs; } return lhs > rhs; } T rhs; }; template <typename T> GtestGreaterThanMatcher<typename std::decay<T>::type> GtestGreaterThan( T&& rhs) { return {rhs}; } // As the matcher above, but using the base class with virtual functions. template <typename T> class GreaterThanMatcher : public MatcherInterface<T> { public: explicit GreaterThanMatcher(T rhs) : impl_{rhs} {} void DescribeTo(ostream* os) const override { impl_.DescribeTo(os); } void DescribeNegationTo(ostream* os) const override { impl_.DescribeNegationTo(os); } bool MatchAndExplain(T lhs, MatchResultListener* listener) const override { return impl_.MatchAndExplain(lhs, listener); } private: const GtestGreaterThanMatcher<T> impl_; }; // Names and instantiates a new instance of GTestMatcherTestP. #define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite) \ using TestSuite##P = GTestMatcherTestP; \ INSTANTIATE_TEST_SUITE_P(MatcherInterface, TestSuite##P, Values(false)); \ INSTANTIATE_TEST_SUITE_P(GtestMatcher, TestSuite##P, Values(true)) class GTestMatcherTestP : public testing::TestWithParam<bool> { public: template <typename T> Matcher<T> GreaterThan(T n) { if (use_gtest_matcher_) { return GtestGreaterThan(n); } else { return MakeMatcher(new GreaterThanMatcher<T>(n)); } } const bool use_gtest_matcher_ = GetParam(); }; // Returns the description of the given matcher. template <typename T> std::string Describe(const Matcher<T>& m) { return DescribeMatcher<T>(m); } // Returns the description of the negation of the given matcher. template <typename T> std::string DescribeNegation(const Matcher<T>& m) { return DescribeMatcher<T>(m, true); } // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> std::string Explain(const MatcherType& m, const Value& x) { StringMatchResultListener listener; ExplainMatchResult(m, x, &listener); return listener.str(); } } // namespace gmock_matchers_test } // namespace testing #endif // GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
6,276
31.523316
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googlemock/test/gmock_link_test.h
// Copyright 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file tests that: // a. A header file defining a mock class can be included in multiple // translation units without causing a link error. // b. Actions and matchers can be instantiated with identical template // arguments in different translation units without causing link // errors. // The following constructs are currently tested: // Actions: // Return() // Return(value) // ReturnNull // ReturnRef // Assign // SetArgPointee // SetArrayArgument // SetErrnoAndReturn // Invoke(function) // Invoke(object, method) // InvokeWithoutArgs(function) // InvokeWithoutArgs(object, method) // InvokeArgument // WithArg // WithArgs // WithoutArgs // DoAll // DoDefault // IgnoreResult // Throw // ACTION()-generated // ACTION_P()-generated // ACTION_P2()-generated // Matchers: // _ // A // An // Eq // Gt, Lt, Ge, Le, Ne // NotNull // Ref // TypedEq // DoubleEq // FloatEq // NanSensitiveDoubleEq // NanSensitiveFloatEq // ContainsRegex // MatchesRegex // EndsWith // HasSubstr // StartsWith // StrCaseEq // StrCaseNe // StrEq // StrNe // ElementsAre // ElementsAreArray // ContainerEq // Field // Property // ResultOf(function) // ResultOf(callback) // Pointee // Truly(predicate) // AddressSatisfies // AllOf // AnyOf // Not // MatcherCast<T> // // Please note: this test does not verify the functioning of these // constructs, only that the programs using them will link successfully. // // Implementation note: // This test requires identical definitions of Interface and Mock to be // included in different translation units. We achieve this by writing // them in this header and #including it in gmock_link_test.cc and // gmock_link2_test.cc. Because the symbols generated by the compiler for // those constructs must be identical in both translation units, // definitions of Interface and Mock tests MUST be kept in the SAME // NON-ANONYMOUS namespace in this file. The test fixture class LinkTest // is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in // gmock_link2_test.cc to avoid producing linker errors. #ifndef GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_ #define GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_ #include "gmock/gmock.h" #if !GTEST_OS_WINDOWS_MOBILE #include <errno.h> #endif #include <iostream> #include <vector> #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" using testing::_; using testing::A; using testing::Action; using testing::AllOf; using testing::AnyOf; using testing::Assign; using testing::ContainerEq; using testing::DoAll; using testing::DoDefault; using testing::DoubleEq; using testing::ElementsAre; using testing::ElementsAreArray; using testing::EndsWith; using testing::Eq; using testing::Field; using testing::FloatEq; using testing::Ge; using testing::Gt; using testing::HasSubstr; using testing::IgnoreResult; using testing::Invoke; using testing::InvokeArgument; using testing::InvokeWithoutArgs; using testing::IsNull; using testing::IsSubsetOf; using testing::IsSupersetOf; using testing::Le; using testing::Lt; using testing::Matcher; using testing::MatcherCast; using testing::NanSensitiveDoubleEq; using testing::NanSensitiveFloatEq; using testing::Ne; using testing::Not; using testing::NotNull; using testing::Pointee; using testing::Property; using testing::Ref; using testing::ResultOf; using testing::Return; using testing::ReturnNull; using testing::ReturnRef; using testing::SetArgPointee; using testing::SetArrayArgument; using testing::StartsWith; using testing::StrCaseEq; using testing::StrCaseNe; using testing::StrEq; using testing::StrNe; using testing::Truly; using testing::TypedEq; using testing::WithArg; using testing::WithArgs; using testing::WithoutArgs; #if !GTEST_OS_WINDOWS_MOBILE using testing::SetErrnoAndReturn; #endif #if GTEST_HAS_EXCEPTIONS using testing::Throw; #endif using testing::ContainsRegex; using testing::MatchesRegex; class Interface { public: virtual ~Interface() {} virtual void VoidFromString(char* str) = 0; virtual char* StringFromString(char* str) = 0; virtual int IntFromString(char* str) = 0; virtual int& IntRefFromString(char* str) = 0; virtual void VoidFromFunc(void (*func)(char* str)) = 0; virtual void VoidFromIntRef(int& n) = 0; // NOLINT virtual void VoidFromFloat(float n) = 0; virtual void VoidFromDouble(double n) = 0; virtual void VoidFromVector(const std::vector<int>& v) = 0; }; class Mock : public Interface { public: Mock() {} MOCK_METHOD1(VoidFromString, void(char* str)); MOCK_METHOD1(StringFromString, char*(char* str)); MOCK_METHOD1(IntFromString, int(char* str)); MOCK_METHOD1(IntRefFromString, int&(char* str)); MOCK_METHOD1(VoidFromFunc, void(void (*func)(char* str))); MOCK_METHOD1(VoidFromIntRef, void(int& n)); // NOLINT MOCK_METHOD1(VoidFromFloat, void(float n)); MOCK_METHOD1(VoidFromDouble, void(double n)); MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v)); private: Mock(const Mock&) = delete; Mock& operator=(const Mock&) = delete; }; class InvokeHelper { public: static void StaticVoidFromVoid() {} void VoidFromVoid() {} static void StaticVoidFromString(char* /* str */) {} void VoidFromString(char* /* str */) {} static int StaticIntFromString(char* /* str */) { return 1; } static bool StaticBoolFromString(const char* /* str */) { return true; } }; class FieldHelper { public: explicit FieldHelper(int a_field) : field_(a_field) {} int field() const { return field_; } int field_; // NOLINT -- need external access to field_ to test // the Field matcher. }; // Tests the linkage of the ReturnVoid action. TEST(LinkTest, TestReturnVoid) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return()); mock.VoidFromString(nullptr); } // Tests the linkage of the Return action. TEST(LinkTest, TestReturn) { Mock mock; char ch = 'x'; EXPECT_CALL(mock, StringFromString(_)).WillOnce(Return(&ch)); mock.StringFromString(nullptr); } // Tests the linkage of the ReturnNull action. TEST(LinkTest, TestReturnNull) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return()); mock.VoidFromString(nullptr); } // Tests the linkage of the ReturnRef action. TEST(LinkTest, TestReturnRef) { Mock mock; int n = 42; EXPECT_CALL(mock, IntRefFromString(_)).WillOnce(ReturnRef(n)); mock.IntRefFromString(nullptr); } // Tests the linkage of the Assign action. TEST(LinkTest, TestAssign) { Mock mock; char ch = 'x'; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Assign(&ch, 'y')); mock.VoidFromString(nullptr); } // Tests the linkage of the SetArgPointee action. TEST(LinkTest, TestSetArgPointee) { Mock mock; char ch = 'x'; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArgPointee<0>('y')); mock.VoidFromString(&ch); } // Tests the linkage of the SetArrayArgument action. TEST(LinkTest, TestSetArrayArgument) { Mock mock; char ch = 'x'; char ch2 = 'y'; EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1)); mock.VoidFromString(&ch); } #if !GTEST_OS_WINDOWS_MOBILE // Tests the linkage of the SetErrnoAndReturn action. TEST(LinkTest, TestSetErrnoAndReturn) { Mock mock; int saved_errno = errno; EXPECT_CALL(mock, IntFromString(_)).WillOnce(SetErrnoAndReturn(1, -1)); mock.IntFromString(nullptr); errno = saved_errno; } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests the linkage of the Invoke(function) and Invoke(object, method) actions. TEST(LinkTest, TestInvoke) { Mock mock; InvokeHelper test_invoke_helper; EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(Invoke(&InvokeHelper::StaticVoidFromString)) .WillOnce(Invoke(&test_invoke_helper, &InvokeHelper::VoidFromString)); mock.VoidFromString(nullptr); mock.VoidFromString(nullptr); } // Tests the linkage of the InvokeWithoutArgs action. TEST(LinkTest, TestInvokeWithoutArgs) { Mock mock; InvokeHelper test_invoke_helper; EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) .WillOnce( InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid)); mock.VoidFromString(nullptr); mock.VoidFromString(nullptr); } // Tests the linkage of the InvokeArgument action. TEST(LinkTest, TestInvokeArgument) { Mock mock; char ch = 'x'; EXPECT_CALL(mock, VoidFromFunc(_)).WillOnce(InvokeArgument<0>(&ch)); mock.VoidFromFunc(InvokeHelper::StaticVoidFromString); } // Tests the linkage of the WithArg action. TEST(LinkTest, TestWithArg) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(WithArg<0>(Invoke(&InvokeHelper::StaticVoidFromString))); mock.VoidFromString(nullptr); } // Tests the linkage of the WithArgs action. TEST(LinkTest, TestWithArgs) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(WithArgs<0>(Invoke(&InvokeHelper::StaticVoidFromString))); mock.VoidFromString(nullptr); } // Tests the linkage of the WithoutArgs action. TEST(LinkTest, TestWithoutArgs) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(WithoutArgs(Return())); mock.VoidFromString(nullptr); } // Tests the linkage of the DoAll action. TEST(LinkTest, TestDoAll) { Mock mock; char ch = 'x'; EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(DoAll(SetArgPointee<0>('y'), Return())); mock.VoidFromString(&ch); } // Tests the linkage of the DoDefault action. TEST(LinkTest, TestDoDefault) { Mock mock; char ch = 'x'; ON_CALL(mock, VoidFromString(_)).WillByDefault(Return()); EXPECT_CALL(mock, VoidFromString(_)).WillOnce(DoDefault()); mock.VoidFromString(&ch); } // Tests the linkage of the IgnoreResult action. TEST(LinkTest, TestIgnoreResult) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(IgnoreResult(Return(42))); mock.VoidFromString(nullptr); } #if GTEST_HAS_EXCEPTIONS // Tests the linkage of the Throw action. TEST(LinkTest, TestThrow) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42)); EXPECT_THROW(mock.VoidFromString(nullptr), int); } #endif // GTEST_HAS_EXCEPTIONS // The ACTION*() macros trigger warning C4100 (unreferenced formal // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) #endif // Tests the linkage of actions created using ACTION macro. namespace { ACTION(Return1) { return 1; } } // namespace TEST(LinkTest, TestActionMacro) { Mock mock; EXPECT_CALL(mock, IntFromString(_)).WillOnce(Return1()); mock.IntFromString(nullptr); } // Tests the linkage of actions created using ACTION_P macro. namespace { ACTION_P(ReturnArgument, ret_value) { return ret_value; } } // namespace TEST(LinkTest, TestActionPMacro) { Mock mock; EXPECT_CALL(mock, IntFromString(_)).WillOnce(ReturnArgument(42)); mock.IntFromString(nullptr); } // Tests the linkage of actions created using ACTION_P2 macro. namespace { ACTION_P2(ReturnEqualsEitherOf, first, second) { return arg0 == first || arg0 == second; } } // namespace #ifdef _MSC_VER #pragma warning(pop) #endif TEST(LinkTest, TestActionP2Macro) { Mock mock; char ch = 'x'; EXPECT_CALL(mock, IntFromString(_)) .WillOnce(ReturnEqualsEitherOf("one", "two")); mock.IntFromString(&ch); } // Tests the linkage of the "_" matcher. TEST(LinkTest, TestMatcherAnything) { Mock mock; ON_CALL(mock, VoidFromString(_)).WillByDefault(Return()); } // Tests the linkage of the A matcher. TEST(LinkTest, TestMatcherA) { Mock mock; ON_CALL(mock, VoidFromString(A<char*>())).WillByDefault(Return()); } // Tests the linkage of the Eq and the "bare value" matcher. TEST(LinkTest, TestMatchersEq) { Mock mock; const char* p = "x"; ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(const_cast<char*>("y"))).WillByDefault(Return()); } // Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers. TEST(LinkTest, TestMatchersRelations) { Mock mock; ON_CALL(mock, VoidFromFloat(Lt(1.0f))).WillByDefault(Return()); ON_CALL(mock, VoidFromFloat(Gt(1.0f))).WillByDefault(Return()); ON_CALL(mock, VoidFromFloat(Le(1.0f))).WillByDefault(Return()); ON_CALL(mock, VoidFromFloat(Ge(1.0f))).WillByDefault(Return()); ON_CALL(mock, VoidFromFloat(Ne(1.0f))).WillByDefault(Return()); } // Tests the linkage of the NotNull matcher. TEST(LinkTest, TestMatcherNotNull) { Mock mock; ON_CALL(mock, VoidFromString(NotNull())).WillByDefault(Return()); } // Tests the linkage of the IsNull matcher. TEST(LinkTest, TestMatcherIsNull) { Mock mock; ON_CALL(mock, VoidFromString(IsNull())).WillByDefault(Return()); } // Tests the linkage of the Ref matcher. TEST(LinkTest, TestMatcherRef) { Mock mock; int a = 0; ON_CALL(mock, VoidFromIntRef(Ref(a))).WillByDefault(Return()); } // Tests the linkage of the TypedEq matcher. TEST(LinkTest, TestMatcherTypedEq) { Mock mock; long a = 0; ON_CALL(mock, VoidFromIntRef(TypedEq<int&>(a))).WillByDefault(Return()); } // Tests the linkage of the FloatEq, DoubleEq, NanSensitiveFloatEq and // NanSensitiveDoubleEq matchers. TEST(LinkTest, TestMatchersFloatingPoint) { Mock mock; float a = 0; ON_CALL(mock, VoidFromFloat(FloatEq(a))).WillByDefault(Return()); ON_CALL(mock, VoidFromDouble(DoubleEq(a))).WillByDefault(Return()); ON_CALL(mock, VoidFromFloat(NanSensitiveFloatEq(a))).WillByDefault(Return()); ON_CALL(mock, VoidFromDouble(NanSensitiveDoubleEq(a))) .WillByDefault(Return()); } // Tests the linkage of the ContainsRegex matcher. TEST(LinkTest, TestMatcherContainsRegex) { Mock mock; ON_CALL(mock, VoidFromString(ContainsRegex(".*"))).WillByDefault(Return()); } // Tests the linkage of the MatchesRegex matcher. TEST(LinkTest, TestMatcherMatchesRegex) { Mock mock; ON_CALL(mock, VoidFromString(MatchesRegex(".*"))).WillByDefault(Return()); } // Tests the linkage of the StartsWith, EndsWith, and HasSubstr matchers. TEST(LinkTest, TestMatchersSubstrings) { Mock mock; ON_CALL(mock, VoidFromString(StartsWith("a"))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(EndsWith("c"))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(HasSubstr("b"))).WillByDefault(Return()); } // Tests the linkage of the StrEq, StrNe, StrCaseEq, and StrCaseNe matchers. TEST(LinkTest, TestMatchersStringEquality) { Mock mock; ON_CALL(mock, VoidFromString(StrEq("a"))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(StrNe("a"))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(StrCaseEq("a"))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(StrCaseNe("a"))).WillByDefault(Return()); } // Tests the linkage of the ElementsAre matcher. TEST(LinkTest, TestMatcherElementsAre) { Mock mock; ON_CALL(mock, VoidFromVector(ElementsAre('a', _))).WillByDefault(Return()); } // Tests the linkage of the ElementsAreArray matcher. TEST(LinkTest, TestMatcherElementsAreArray) { Mock mock; char arr[] = {'a', 'b'}; ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); } // Tests the linkage of the IsSubsetOf matcher. TEST(LinkTest, TestMatcherIsSubsetOf) { Mock mock; char arr[] = {'a', 'b'}; ON_CALL(mock, VoidFromVector(IsSubsetOf(arr))).WillByDefault(Return()); } // Tests the linkage of the IsSupersetOf matcher. TEST(LinkTest, TestMatcherIsSupersetOf) { Mock mock; char arr[] = {'a', 'b'}; ON_CALL(mock, VoidFromVector(IsSupersetOf(arr))).WillByDefault(Return()); } // Tests the linkage of the ContainerEq matcher. TEST(LinkTest, TestMatcherContainerEq) { Mock mock; std::vector<int> v; ON_CALL(mock, VoidFromVector(ContainerEq(v))).WillByDefault(Return()); } // Tests the linkage of the Field matcher. TEST(LinkTest, TestMatcherField) { FieldHelper helper(0); Matcher<const FieldHelper&> m = Field(&FieldHelper::field_, Eq(0)); EXPECT_TRUE(m.Matches(helper)); Matcher<const FieldHelper*> m2 = Field(&FieldHelper::field_, Eq(0)); EXPECT_TRUE(m2.Matches(&helper)); } // Tests the linkage of the Property matcher. TEST(LinkTest, TestMatcherProperty) { FieldHelper helper(0); Matcher<const FieldHelper&> m = Property(&FieldHelper::field, Eq(0)); EXPECT_TRUE(m.Matches(helper)); Matcher<const FieldHelper*> m2 = Property(&FieldHelper::field, Eq(0)); EXPECT_TRUE(m2.Matches(&helper)); } // Tests the linkage of the ResultOf matcher. TEST(LinkTest, TestMatcherResultOf) { Matcher<char*> m = ResultOf(&InvokeHelper::StaticIntFromString, Eq(1)); EXPECT_TRUE(m.Matches(nullptr)); } // Tests the linkage of the ResultOf matcher. TEST(LinkTest, TestMatcherPointee) { int n = 1; Matcher<int*> m = Pointee(Eq(1)); EXPECT_TRUE(m.Matches(&n)); } // Tests the linkage of the Truly matcher. TEST(LinkTest, TestMatcherTruly) { Matcher<const char*> m = Truly(&InvokeHelper::StaticBoolFromString); EXPECT_TRUE(m.Matches(nullptr)); } // Tests the linkage of the AllOf matcher. TEST(LinkTest, TestMatcherAllOf) { Matcher<int> m = AllOf(_, Eq(1)); EXPECT_TRUE(m.Matches(1)); } // Tests the linkage of the AnyOf matcher. TEST(LinkTest, TestMatcherAnyOf) { Matcher<int> m = AnyOf(_, Eq(1)); EXPECT_TRUE(m.Matches(1)); } // Tests the linkage of the Not matcher. TEST(LinkTest, TestMatcherNot) { Matcher<int> m = Not(_); EXPECT_FALSE(m.Matches(1)); } // Tests the linkage of the MatcherCast<T>() function. TEST(LinkTest, TestMatcherCast) { Matcher<const char*> m = MatcherCast<const char*>(_); EXPECT_TRUE(m.Matches(nullptr)); } #endif // GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
19,583
27.382609
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-assertion-result.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The Google C++ Testing and Mocking Framework (Google Test) // // This file implements the AssertionResult type. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_ #include <memory> #include <ostream> #include <string> #include <type_traits> #include "gtest/gtest-message.h" #include "gtest/internal/gtest-port.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // A class for indicating whether an assertion was successful. When // the assertion wasn't successful, the AssertionResult object // remembers a non-empty message that describes how it failed. // // To create an instance of this class, use one of the factory functions // (AssertionSuccess() and AssertionFailure()). // // This class is useful for two purposes: // 1. Defining predicate functions to be used with Boolean test assertions // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts // 2. Defining predicate-format functions to be // used with predicate assertions (ASSERT_PRED_FORMAT*, etc). // // For example, if you define IsEven predicate: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) // will print the message // // Value of: IsEven(Fib(5)) // Actual: false (5 is odd) // Expected: true // // instead of a more opaque // // Value of: IsEven(Fib(5)) // Actual: false // Expected: true // // in case IsEven is a simple Boolean predicate. // // If you expect your predicate to be reused and want to support informative // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up // about half as often as positive ones in our tests), supply messages for // both success and failure cases: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess() << n << " is even"; // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print // // Value of: IsEven(Fib(6)) // Actual: true (8 is even) // Expected: false // // NB: Predicates that support negative Boolean assertions have reduced // performance in positive ones so be careful not to use them in tests // that have lots (tens of thousands) of positive Boolean assertions. // // To use this class with EXPECT_PRED_FORMAT assertions such as: // // // Verifies that Foo() returns an even number. // EXPECT_PRED_FORMAT1(IsEven, Foo()); // // you need to define: // // testing::AssertionResult IsEven(const char* expr, int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() // << "Expected: " << expr << " is even\n Actual: it's " << n; // } // // If Foo() returns 5, you will see the following message: // // Expected: Foo() is even // Actual: it's 5 // class GTEST_API_ AssertionResult { public: // Copy constructor. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult(const AssertionResult& other); // C4800 is a level 3 warning in Visual Studio 2015 and earlier. // This warning is not emitted in Visual Studio 2017. // This warning is off by default starting in Visual Studio 2019 but can be // enabled with command-line options. #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) #endif // Used in the EXPECT_TRUE/FALSE(bool_expression). // // T must be contextually convertible to bool. // // The second parameter prevents this overload from being considered if // the argument is implicitly convertible to AssertionResult. In that case // we want AssertionResult's copy constructor to be used. template <typename T> explicit AssertionResult( const T& success, typename std::enable_if< !std::is_convertible<T, AssertionResult>::value>::type* /*enabler*/ = nullptr) : success_(success) {} #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920) GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // Assignment operator. AssertionResult& operator=(AssertionResult other) { swap(other); return *this; } // Returns true if and only if the assertion succeeded. operator bool() const { return success_; } // NOLINT // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult operator!() const; // Returns the text streamed into this AssertionResult. Test assertions // use it when they fail (i.e., the predicate's outcome doesn't match the // assertion's expectation). When nothing has been streamed into the // object, returns an empty string. const char* message() const { return message_.get() != nullptr ? message_->c_str() : ""; } // Deprecated; please use message() instead. const char* failure_message() const { return message(); } // Streams a custom failure message into this object. template <typename T> AssertionResult& operator<<(const T& value) { AppendMessage(Message() << value); return *this; } // Allows streaming basic output manipulators such as endl or flush into // this object. AssertionResult& operator<<( ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { AppendMessage(Message() << basic_manipulator); return *this; } private: // Appends the contents of message to message_. void AppendMessage(const Message& a_message) { if (message_.get() == nullptr) message_.reset(new ::std::string); message_->append(a_message.GetString().c_str()); } // Swap the contents of this AssertionResult with other. void swap(AssertionResult& other); // Stores result of the assertion predicate. bool success_; // Stores the message describing the condition in case the expectation // construct is not satisfied with the predicate's outcome. // Referenced via a pointer to avoid taking too much stack frame space // with test assertions. std::unique_ptr< ::std::string> message_; }; // Makes a successful assertion result. GTEST_API_ AssertionResult AssertionSuccess(); // Makes a failed assertion result. GTEST_API_ AssertionResult AssertionFailure(); // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << msg. GTEST_API_ AssertionResult AssertionFailure(const Message& msg); } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
8,502
34.726891
76
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-death-test.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the public API for death tests. It is // #included by gtest.h so a user doesn't need to include this // directly. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #include "gtest/internal/gtest-death-test-internal.h" // This flag controls the style of death tests. Valid values are "threadsafe", // meaning that the death test child process will re-execute the test binary // from the start, running only a single death test, or "fast", // meaning that the child process will execute the test logic immediately // after forking. GTEST_DECLARE_string_(death_test_style); namespace testing { #if GTEST_HAS_DEATH_TEST namespace internal { // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as // Valgrind heap checkers may need this to modify their behavior in death // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. GTEST_API_ bool InDeathTestChild(); } // namespace internal // The following macros are useful for writing death tests. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is // executed: // // 1. It generates a warning if there is more than one active // thread. This is because it's safe to fork() or clone() only // when there is a single thread. // // 2. The parent process clone()s a sub-process and runs the death // test in it; the sub-process exits with code 0 at the end of the // death test, if it hasn't exited already. // // 3. The parent process waits for the sub-process to terminate. // // 4. The parent process checks the exit code and error message of // the sub-process. // // Examples: // // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); // for (int i = 0; i < 5; i++) { // EXPECT_DEATH(server.ProcessRequest(i), // "Invalid request .* in ProcessRequest()") // << "Failed to die on request " << i; // } // // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); // // bool KilledBySIGHUP(int exit_code) { // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; // } // // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); // // The final parameter to each of these macros is a matcher applied to any data // the sub-process wrote to stderr. For compatibility with existing tests, a // bare string is interpreted as a regular expression matcher. // // On the regular expressions used in death tests: // // On POSIX-compliant systems (*nix), we use the <regex.h> library, // which uses the POSIX extended regex syntax. // // On other platforms (e.g. Windows or Mac), we only support a simple regex // syntax implemented as part of Google Test. This limited // implementation should be enough most of the time when writing // death tests; though it lacks many features you can find in PCRE // or POSIX extended regex syntax. For example, we don't support // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and // repetition count ("x{5,7}"), among others. // // Below is the syntax that we do support. We chose it to be a // subset of both PCRE and POSIX extended regex, so it's easy to // learn wherever you come from. In the following: 'A' denotes a // literal character, period (.), or a single \\ escape sequence; // 'x' and 'y' denote regular expressions; 'm' and 'n' are for // natural numbers. // // c matches any literal character c // \\d matches any decimal digit // \\D matches any character that's not a decimal digit // \\f matches \f // \\n matches \n // \\r matches \r // \\s matches any ASCII whitespace, including \n // \\S matches any character that's not a whitespace // \\t matches \t // \\v matches \v // \\w matches any letter, _, or decimal digit // \\W matches any character that \\w doesn't match // \\c matches any literal character c, which must be a punctuation // . matches any single character except \n // A? matches 0 or 1 occurrences of A // A* matches 0 or many occurrences of A // A+ matches 1 or many occurrences of A // ^ matches the beginning of a string (not that of each line) // $ matches the end of a string (not that of each line) // xy matches x followed by y // // If you accidentally use PCRE or POSIX extended regex features // not implemented by us, you will get a run-time failure. In that // case, please try to rewrite your regular expression within the // above syntax. // // This implementation is *not* meant to be as highly tuned or robust // as a compiled regex library, but should perform well enough for a // death test, which already incurs significant overhead by launching // a child process. // // Known caveats: // // A "threadsafe" style death test obtains the path to the test // program from argv[0] and re-executes it in the sub-process. For // simplicity, the current implementation doesn't search the PATH // when launching the sub-process. This means that the user must // invoke the test program via a path that contains at least one // path separator (e.g. path/to/foo_test and // /absolute/path/to/bar_test are fine, but foo_test is not). This // is rarely a problem as people usually don't put the test binary // directory in PATH. // // Asserts that a given `statement` causes the program to exit, with an // integer exit status that satisfies `predicate`, and emitting error output // that matches `matcher`. #define ASSERT_EXIT(statement, predicate, matcher) \ GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_) // Like `ASSERT_EXIT`, but continues on to successive tests in the // test suite, if any: #define EXPECT_EXIT(statement, predicate, matcher) \ GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_) // Asserts that a given `statement` causes the program to exit, either by // explicitly exiting with a nonzero exit code or being killed by a // signal, and emitting error output that matches `matcher`. #define ASSERT_DEATH(statement, matcher) \ ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) // Like `ASSERT_DEATH`, but continues on to successive tests in the // test suite, if any: #define EXPECT_DEATH(statement, matcher) \ EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: // Tests that an exit code describes a normal exit with a given exit code. class GTEST_API_ ExitedWithCode { public: explicit ExitedWithCode(int exit_code); ExitedWithCode(const ExitedWithCode&) = default; void operator=(const ExitedWithCode& other) = delete; bool operator()(int exit_status) const; private: const int exit_code_; }; #if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; private: const int signum_; }; #endif // !GTEST_OS_WINDOWS // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // The death testing framework causes this to have interesting semantics, // since the sideeffects of the call are only visible in opt mode, and not // in debug mode. // // In practice, this can be used to test functions that utilize the // LOG(DFATAL) macro using the following style: // // int DieInDebugOr12(int* sideeffect) { // if (sideeffect) { // *sideeffect = 12; // } // LOG(DFATAL) << "death"; // return 12; // } // // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) { // int sideeffect = 0; // // Only asserts in dbg. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); // // #ifdef NDEBUG // // opt-mode has sideeffect visible. // EXPECT_EQ(12, sideeffect); // #else // // dbg-mode no visible sideeffect. // EXPECT_EQ(0, sideeffect); // #endif // } // // This will assert that DieInDebugReturn12InOpt() crashes in debug // mode, usually due to a DCHECK or LOG(DFATAL), but returns the // appropriate fallback value (12 in this case) in opt mode. If you // need to test that a function has appropriate side-effects in opt // mode, include assertions against the side-effects. A general // pattern for this is: // // EXPECT_DEBUG_DEATH({ // // Side-effects here will have an effect after this statement in // // opt mode, but none in debug mode. // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // }, "death"); // #ifdef NDEBUG #define EXPECT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) #define ASSERT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) #else #define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex) #define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex) #endif // NDEBUG for EXPECT_DEBUG_DEATH #endif // GTEST_HAS_DEATH_TEST // This macro is used for implementing macros such as // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where // death tests are not supported. Those macros must compile on such systems // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters // on systems that support death tests. This allows one to write such a macro on // a system that does not support death tests and be sure that it will compile // on a death-test supporting system. It is exposed publicly so that systems // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and // ASSERT_DEATH_IF_SUPPORTED. // // Parameters: // statement - A statement that a macro such as EXPECT_DEATH would test // for program termination. This macro has to make sure this // statement is compiled but not executed, to ensure that // EXPECT_DEATH_IF_SUPPORTED compiles with a certain // parameter if and only if EXPECT_DEATH compiles with it. // regex - A regex that a macro such as EXPECT_DEATH would use to test // the output of statement. This parameter has to be // compiled but not evaluated by this macro, to ensure that // this macro only accepts expressions that a macro such as // EXPECT_DEATH would accept. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED // and a return statement for ASSERT_DEATH_IF_SUPPORTED. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not // compile inside functions where ASSERT_DEATH doesn't // compile. // // The branch that has an always false condition is used to ensure that // statement and regex are compiled (and thus syntactically correct) but // never executed. The unreachable code macro protects the terminator // statement from generating an 'unreachable code' warning in case // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. #define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \ << "Statement '" #statement "' cannot be verified."; \ } else if (::testing::internal::AlwaysFalse()) { \ ::testing::internal::RE::PartialMatch(".*", (regex)); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ terminator; \ } else \ ::testing::Message() // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if // death tests are supported; otherwise they just issue a warning. This is // useful when you are combining death test assertions with normal test // assertions in one test. #if GTEST_HAS_DEATH_TEST #define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ EXPECT_DEATH(statement, regex) #define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ ASSERT_DEATH(statement, regex) #else #define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) #define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) #endif } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
14,886
42.026012
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-message.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the Message class. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #include <limits> #include <memory> #include <sstream> #include "gtest/internal/gtest-port.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) // Ensures that there is at least one operator<< in the global namespace. // See Message& operator<<(...) below for why. void operator<<(const testing::internal::Secret&, int); namespace testing { // The Message class works like an ostream repeater. // // Typical usage: // // 1. You stream a bunch of values to a Message object. // It will remember the text in a stringstream. // 2. Then you stream the Message object to an ostream. // This causes the text in the Message to be streamed // to the ostream. // // For example; // // testing::Message foo; // foo << 1 << " != " << 2; // std::cout << foo; // // will print "1 != 2". // // Message is not intended to be inherited from. In particular, its // destructor is not virtual. // // Note that stringstream behaves differently in gcc and in MSVC. You // can stream a NULL char pointer to it in the former, but not in the // latter (it causes an access violation if you do). The Message // class hides this difference by treating a NULL char pointer as // "(null)". class GTEST_API_ Message { private: // The type of basic IO manipulators (endl, ends, and flush) for // narrow streams. typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); public: // Constructs an empty Message. Message(); // Copy constructor. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT *ss_ << msg.GetString(); } // Constructs a Message from a C-string. explicit Message(const char* str) : ss_(new ::std::stringstream) { *ss_ << str; } // Streams a non-pointer value to this object. template <typename T> inline Message& operator<<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. // // C++'s symbol lookup rule (i.e. Koenig lookup) says that these // overloads are visible in either the std namespace or the global // namespace, but not other namespaces, including the testing // namespace which Google Test's Message class is in. // // To allow STL containers (and other types that has a << operator // defined in the global namespace) to be used in Google Test // assertions, testing::Message must access the custom << operator // from the global namespace. With this using declaration, // overloads of << defined in the global namespace and those // visible via Koenig lookup are both exposed in this function. using ::operator<<; *ss_ << val; return *this; } // Streams a pointer value to this object. // // This function is an overload of the previous one. When you // stream a pointer to a Message, this definition will be used as it // is more specialized. (The C++ Standard, section // [temp.func.order].) If you stream a non-pointer, then the // previous definition will be used. // // The reason for this overload is that streaming a NULL pointer to // ostream is undefined behavior. Depending on the compiler, you // may get "0", "(nil)", "(null)", or an access violation. To // ensure consistent result across compilers, we always treat NULL // as "(null)". template <typename T> inline Message& operator<<(T* const& pointer) { // NOLINT if (pointer == nullptr) { *ss_ << "(null)"; } else { *ss_ << pointer; } return *this; } // Since the basic IO manipulators are overloaded for both narrow // and wide streams, we have to provide this specialized definition // of operator <<, even though its body is the same as the // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. Message& operator<<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. Message& operator<<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& operator<<(const wchar_t* wide_c_str); Message& operator<<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator<<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. std::string GetString() const; private: // We'll hold the text streamed to this object here. const std::unique_ptr< ::std::stringstream> ss_; // We declare (but don't implement) this to prevent the compiler // from implementing the assignment operator. void operator=(const Message&); }; // Streams a Message to an ostream. inline std::ostream& operator<<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } namespace internal { // Converts a streamable value to an std::string. A NULL pointer is // converted to "(null)". When the input value is a ::string, // ::std::string, ::wstring, or ::std::wstring object, each NUL // character in it is replaced with "\\0". template <typename T> std::string StreamableToString(const T& streamable) { return (Message() << streamable).GetString(); } } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
8,109
36.031963
75
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-param-test.h
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Macros and functions for implementing parameterized tests // in Google C++ Testing and Mocking Framework (Google Test) // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ // Value-parameterized tests allow you to test your code with different // parameters without writing multiple copies of the same test. // // Here is how you use value-parameterized tests: #if 0 // To write value-parameterized tests, first you should define a fixture // class. It is usually derived from testing::TestWithParam<T> (see below for // another inheritance scheme that's sometimes useful in more complicated // class hierarchies), where the type of your parameter values. // TestWithParam<T> is itself derived from testing::Test. T can be any // copyable type. If it's a raw pointer, you are responsible for managing the // lifespan of the pointed values. class FooTest : public ::testing::TestWithParam<const char*> { // You can implement all the usual class fixture members here. }; // Then, use the TEST_P macro to define as many parameterized tests // for this fixture as you want. The _P suffix is for "parameterized" // or "pattern", whichever you prefer to think. TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method // of the TestWithParam<T> class: EXPECT_TRUE(foo.Blah(GetParam())); ... } TEST_P(FooTest, HasBlahBlah) { ... } // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test // case with any set of parameters you want. Google Test defines a number // of functions for generating test parameters. They return what we call // (surprise!) parameter generators. Here is a summary of them, which // are all in the testing namespace: // // // Range(begin, end [, step]) - Yields values {begin, begin+step, // begin+step+step, ...}. The values do not // include end. step defaults to 1. // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. // ValuesIn(container) - Yields values from a C-style array, an STL // ValuesIn(begin,end) container, or an iterator range [begin, end). // Bool() - Yields sequence {false, true}. // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product // for the math savvy) of the values generated // by the N generators. // // For more details, see comments at the definitions of these functions below // in this file. // // The following statement will instantiate tests from the FooTest test suite // each with parameter values "meeny", "miny", and "moe". INSTANTIATE_TEST_SUITE_P(InstantiationName, FooTest, Values("meeny", "miny", "moe")); // To distinguish different instances of the pattern, (yes, you // can instantiate it more than once) the first argument to the // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the // actual test suite name. Remember to pick unique prefixes for different // instantiations. The tests from the instantiation above will have // these names: // // * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/1 for "miny" // * InstantiationName/FooTest.DoesBlah/2 for "moe" // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" // * InstantiationName/FooTest.HasBlahBlah/1 for "miny" // * InstantiationName/FooTest.HasBlahBlah/2 for "moe" // // You can use these names in --gtest_filter. // // This statement will instantiate all tests from FooTest again, each // with parameter values "cat" and "dog": const char* pets[] = {"cat", "dog"}; INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // The tests from the instantiation above will have these names: // // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" // // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests // in the given test suite, whether their definitions come before or // AFTER the INSTANTIATE_TEST_SUITE_P statement. // // Please also note that generator expressions (including parameters to the // generators) are evaluated in InitGoogleTest(), after main() has started. // This allows the user on one hand, to adjust generator parameters in order // to dynamically determine a set of tests to run and on the other hand, // give the user a chance to inspect the generated tests with Google Test // reflection API before RUN_ALL_TESTS() is executed. // // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc // for more examples. // // In the future, we plan to publish the API for defining new parameter // generators. But for now this interface remains part of the internal // implementation and is subject to change. // // // A parameterized test fixture must be derived from testing::Test and from // testing::WithParamInterface<T>, where T is the type of the parameter // values. Inheriting from TestWithParam<T> satisfies that requirement because // TestWithParam<T> inherits from both Test and WithParamInterface. In more // complicated hierarchies, however, it is occasionally useful to inherit // separately from Test and WithParamInterface. For example: class BaseTest : public ::testing::Test { // You can inherit all the usual members for a non-parameterized test // fixture here. }; class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> { // The usual test fixture members go here too. }; TEST_F(BaseTest, HasFoo) { // This is an ordinary non-parameterized test. } TEST_P(DerivedTest, DoesBlah) { // GetParam works just the same here as if you inherit from TestWithParam. EXPECT_TRUE(foo.Blah(GetParam())); } #endif // 0 #include <iterator> #include <utility> #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-port.h" namespace testing { // Functions producing parameter generators. // // Google Test uses these generators to produce parameters for value- // parameterized tests. When a parameterized test suite is instantiated // with a particular generator, Google Test creates and runs tests // for each element in the sequence produced by the generator. // // In the following sample, tests from test suite FooTest are instantiated // each three times with parameter values 3, 5, and 8: // // class FooTest : public TestWithParam<int> { ... }; // // TEST_P(FooTest, TestThis) { // } // TEST_P(FooTest, TestThat) { // } // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8)); // // Range() returns generators providing sequences of values in a range. // // Synopsis: // Range(start, end) // - returns a generator producing a sequence of values {start, start+1, // start+2, ..., }. // Range(start, end, step) // - returns a generator producing a sequence of values {start, start+step, // start+step+step, ..., }. // Notes: // * The generated sequences never include end. For example, Range(1, 5) // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) // returns a generator producing {1, 3, 5, 7}. // * start and end must have the same type. That type may be any integral or // floating-point type or a user defined type satisfying these conditions: // * It must be assignable (have operator=() defined). // * It must have operator+() (operator+(int-compatible type) for // two-operand version). // * It must have operator<() defined. // Elements in the resulting sequences will also have that type. // * Condition start < end must be satisfied in order for resulting sequences // to contain any elements. // template <typename T, typename IncrementT> internal::ParamGenerator<T> Range(T start, T end, IncrementT step) { return internal::ParamGenerator<T>( new internal::RangeGenerator<T, IncrementT>(start, end, step)); } template <typename T> internal::ParamGenerator<T> Range(T start, T end) { return Range(start, end, 1); } // ValuesIn() function allows generation of tests with parameters coming from // a container. // // Synopsis: // ValuesIn(const T (&array)[N]) // - returns a generator producing sequences with elements from // a C-style array. // ValuesIn(const Container& container) // - returns a generator producing sequences with elements from // an STL-style container. // ValuesIn(Iterator begin, Iterator end) // - returns a generator producing sequences with elements from // a range [begin, end) defined by a pair of STL-style iterators. These // iterators can also be plain C pointers. // // Please note that ValuesIn copies the values from the containers // passed in and keeps them to generate tests in RUN_ALL_TESTS(). // // Examples: // // This instantiates tests from test suite StringTest // each with C-string values of "foo", "bar", and "baz": // // const char* strings[] = {"foo", "bar", "baz"}; // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings)); // // This instantiates tests from test suite StlStringTest // each with STL strings with values "a" and "b": // // ::std::vector< ::std::string> GetParameterStrings() { // ::std::vector< ::std::string> v; // v.push_back("a"); // v.push_back("b"); // return v; // } // // INSTANTIATE_TEST_SUITE_P(CharSequence, // StlStringTest, // ValuesIn(GetParameterStrings())); // // // This will also instantiate tests from CharTest // each with parameter values 'a' and 'b': // // ::std::list<char> GetParameterChars() { // ::std::list<char> list; // list.push_back('a'); // list.push_back('b'); // return list; // } // ::std::list<char> l = GetParameterChars(); // INSTANTIATE_TEST_SUITE_P(CharSequence2, // CharTest, // ValuesIn(l.begin(), l.end())); // template <typename ForwardIterator> internal::ParamGenerator< typename std::iterator_traits<ForwardIterator>::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end) { typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType; return internal::ParamGenerator<ParamType>( new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end)); } template <typename T, size_t N> internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) { return ValuesIn(array, array + N); } template <class Container> internal::ParamGenerator<typename Container::value_type> ValuesIn( const Container& container) { return ValuesIn(container.begin(), container.end()); } // Values() allows generating tests from explicitly specified list of // parameters. // // Synopsis: // Values(T v1, T v2, ..., T vN) // - returns a generator producing sequences with elements v1, v2, ..., vN. // // For example, this instantiates tests from test suite BarTest each // with values "one", "two", and "three": // // INSTANTIATE_TEST_SUITE_P(NumSequence, // BarTest, // Values("one", "two", "three")); // // This instantiates tests from test suite BazTest each with values 1, 2, 3.5. // The exact type of values will depend on the type of parameter in BazTest. // // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); // // template <typename... T> internal::ValueArray<T...> Values(T... v) { return internal::ValueArray<T...>(std::move(v)...); } // Bool() allows generating tests with parameters in a set of (false, true). // // Synopsis: // Bool() // - returns a generator producing sequences with elements {false, true}. // // It is useful when testing code that depends on Boolean flags. Combinations // of multiple flags can be tested when several Bool()'s are combined using // Combine() function. // // In the following example all tests in the test suite FlagDependentTest // will be instantiated twice with parameters false and true. // // class FlagDependentTest : public testing::TestWithParam<bool> { // virtual void SetUp() { // external_flag = GetParam(); // } // } // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); // inline internal::ParamGenerator<bool> Bool() { return Values(false, true); } // Combine() allows the user to combine two or more sequences to produce // values of a Cartesian product of those sequences' elements. // // Synopsis: // Combine(gen1, gen2, ..., genN) // - returns a generator producing sequences with elements coming from // the Cartesian product of elements from the sequences generated by // gen1, gen2, ..., genN. The sequence elements will have a type of // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types // of elements from sequences produces by gen1, gen2, ..., genN. // // Example: // // This will instantiate tests in test suite AnimalTest each one with // the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // tuple("dog", BLACK), and tuple("dog", WHITE): // // enum Color { BLACK, GRAY, WHITE }; // class AnimalTest // : public testing::TestWithParam<std::tuple<const char*, Color> > {...}; // // TEST_P(AnimalTest, AnimalLooksNice) {...} // // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest, // Combine(Values("cat", "dog"), // Values(BLACK, WHITE))); // // This will instantiate tests in FlagDependentTest with all variations of two // Boolean flags: // // class FlagDependentTest // : public testing::TestWithParam<std::tuple<bool, bool> > { // virtual void SetUp() { // // Assigns external_flag_1 and external_flag_2 values from the tuple. // std::tie(external_flag_1, external_flag_2) = GetParam(); // } // }; // // TEST_P(FlagDependentTest, TestFeature1) { // // Test your code using external_flag_1 and external_flag_2 here. // } // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest, // Combine(Bool(), Bool())); // template <typename... Generator> internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) { return internal::CartesianProductHolder<Generator...>(g...); } // ConvertGenerator() wraps a parameter generator in order to cast each produced // value through a known type before supplying it to the test suite // // Synopsis: // ConvertGenerator<T>(gen) // - returns a generator producing the same elements as generated by gen, but // each element is static_cast to type T before being returned // // It is useful when using the Combine() function to get the generated // parameters in a custom type instead of std::tuple // // Example: // // This will instantiate tests in test suite AnimalTest each one with // the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // tuple("dog", BLACK), and tuple("dog", WHITE): // // enum Color { BLACK, GRAY, WHITE }; // struct ParamType { // using TupleT = std::tuple<const char*, Color>; // std::string animal; // Color color; // ParamType(TupleT t) : animal(std::get<0>(t)), color(std::get<1>(t)) {} // }; // class AnimalTest // : public testing::TestWithParam<ParamType> {...}; // // TEST_P(AnimalTest, AnimalLooksNice) {...} // // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest, // ConvertGenerator<ParamType::TupleT>( // Combine(Values("cat", "dog"), // Values(BLACK, WHITE)))); // template <typename T> internal::ParamConverterGenerator<T> ConvertGenerator( internal::ParamGenerator<T> gen) { return internal::ParamConverterGenerator<T>(gen); } #define TEST_P(test_suite_name, test_name) \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ : public test_suite_name, private ::testing::internal::GTestNonCopyable {\ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ void TestBody() override; \ \ private: \ static int AddToRegistry() { \ ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder<test_suite_name>( \ GTEST_STRINGIFY_(test_suite_name), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ->AddTestPattern( \ GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \ new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \ test_suite_name, test_name)>(), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)); \ return 0; \ } \ static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ }; \ int GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)::gtest_registering_dummy_ = \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \ void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify // generator and an optional function or functor that generates custom test name // suffixes based on the test parameters. Such a function or functor should // accept one argument of type testing::TestParamInfo<class ParamType>, and // return std::string. // // testing::PrintToStringParamName is a builtin test suffix generator that // returns the value of testing::PrintToString(GetParam()). // // Note: test names must be non-empty, unique, and may only contain ASCII // alphanumeric characters or underscore. Because PrintToString adds quotes // to std::string and C strings, it won't work for these types. #define GTEST_EXPAND_(arg) arg #define GTEST_GET_FIRST_(first, ...) first #define GTEST_GET_SECOND_(first, second, ...) second #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ } \ static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \ if (::testing::internal::AlwaysFalse()) { \ ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ __VA_ARGS__, \ ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ DUMMY_PARAM_))); \ auto t = std::make_tuple(__VA_ARGS__); \ static_assert(std::tuple_size<decltype(t)>::value <= 2, \ "Too Many Args!"); \ } \ return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ __VA_ARGS__, \ ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ DUMMY_PARAM_))))(info); \ } \ static int gtest_##prefix##test_suite_name##_dummy_ \ GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder<test_suite_name>( \ GTEST_STRINGIFY_(test_suite_name), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ->AddTestSuiteInstantiation( \ GTEST_STRINGIFY_(prefix), \ &gtest_##prefix##test_suite_name##_EvalGenerator_, \ &gtest_##prefix##test_suite_name##_EvalGenerateName_, \ __FILE__, __LINE__) // Allow Marking a Parameterized test class as not needing to be instantiated. #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \ namespace gtest_do_not_use_outside_namespace_scope {} \ static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \ GTEST_STRINGIFY_(T)) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TEST_CASE_P \ static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \ ""); \ INSTANTIATE_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
23,927
42.824176
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-spi.h
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // This helper class can be used to mock out Google Test failure reporting // so that we can test Google Test or code that builds on Google Test. // // An object of this class appends a TestPartResult object to the // TestPartResultArray object given in the constructor whenever a Google Test // failure is reported. It can either intercept only failures that are // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. enum InterceptMode { INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. INTERCEPT_ALL_THREADS // Intercepts all failures. }; // The c'tor sets this object as the test part result reporter used // by Google Test. The 'result' parameter specifies where to report the // results. This reporter will only catch failures generated in the current // thread. DEPRECATED explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); // Same as above, but you can choose the interception scope of this object. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, TestPartResultArray* result); // The d'tor restores the previous test part result reporter. ~ScopedFakeTestPartResultReporter() override; // Appends the TestPartResult object to the TestPartResultArray // received in the constructor. // // This method is from the TestPartResultReporterInterface // interface. void ReportTestPartResult(const TestPartResult& result) override; private: void Init(); const InterceptMode intercept_mode_; TestPartResultReporterInterface* old_reporter_; TestPartResultArray* const result_; ScopedFakeTestPartResultReporter(const ScopedFakeTestPartResultReporter&) = delete; ScopedFakeTestPartResultReporter& operator=( const ScopedFakeTestPartResultReporter&) = delete; }; namespace internal { // A helper class for implementing EXPECT_FATAL_FAILURE() and // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr); ~SingleFailureChecker(); private: const TestPartResultArray* const results_; const TestPartResult::Type type_; const std::string substr_; SingleFailureChecker(const SingleFailureChecker&) = delete; SingleFailureChecker& operator=(const SingleFailureChecker&) = delete; }; } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // A set of macros for testing Google Test assertions or code that's expected // to generate Google Test fatal failures (e.g. a failure from an ASSERT_EQ, but // not a non-fatal failure, as from EXPECT_EQ). It verifies that the given // statement will cause exactly one fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_FATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - 'statement' cannot reference local non-static variables or // non-static members of the current object. // - 'statement' cannot return a value. // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. #define EXPECT_FATAL_FAILURE(statement, substr) \ do { \ class GTestExpectFatalFailureHelper { \ public: \ static void Execute() { statement; } \ }; \ ::testing::TestPartResultArray gtest_failures; \ ::testing::internal::SingleFailureChecker gtest_checker( \ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \ { \ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, \ &gtest_failures); \ GTestExpectFatalFailureHelper::Execute(); \ } \ } while (::testing::internal::AlwaysFalse()) #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do { \ class GTestExpectFatalFailureHelper { \ public: \ static void Execute() { statement; } \ }; \ ::testing::TestPartResultArray gtest_failures; \ ::testing::internal::SingleFailureChecker gtest_checker( \ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \ { \ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ &gtest_failures); \ GTestExpectFatalFailureHelper::Execute(); \ } \ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to // generate Google Test non-fatal failures (e.g. a failure from an EXPECT_EQ, // but not from an ASSERT_EQ). It asserts that the given statement will cause // exactly one non-fatal Google Test failure with 'substr' being part of the // failure message. // // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // 'statement' is allowed to reference local variables and members of // the current object. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. If we do that, the code won't compile when the user gives // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that // expands to code containing an unprotected comma. The // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc // catches that. // // For the same reason, we have to write // if (::testing::internal::AlwaysTrue()) { statement; } // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. #define EXPECT_NONFATAL_FAILURE(statement, substr) \ do { \ ::testing::TestPartResultArray gtest_failures; \ ::testing::internal::SingleFailureChecker gtest_checker( \ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr)); \ { \ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, \ &gtest_failures); \ if (::testing::internal::AlwaysTrue()) { \ statement; \ } \ } \ } while (::testing::internal::AlwaysFalse()) #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do { \ ::testing::TestPartResultArray gtest_failures; \ ::testing::internal::SingleFailureChecker gtest_checker( \ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr)); \ { \ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ &gtest_failures); \ if (::testing::internal::AlwaysTrue()) { \ statement; \ } \ } \ } while (::testing::internal::AlwaysFalse()) #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
12,824
50.506024
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-test-part.h
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #include <iosfwd> #include <vector> #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { // A copyable object representing the result of a test part (i.e. an // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). // // Don't inherit from TestPartResult as its destructor is not virtual. class GTEST_API_ TestPartResult { public: // The possible outcomes of a test part (i.e. an assertion or an // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). enum Type { kSuccess, // Succeeded. kNonFatalFailure, // Failed but the test can continue. kFatalFailure, // Failed and the test should be terminated. kSkip // Skipped. }; // C'tor. TestPartResult does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestPartResult object. TestPartResult(Type a_type, const char* a_file_name, int a_line_number, const char* a_message) : type_(a_type), file_name_(a_file_name == nullptr ? "" : a_file_name), line_number_(a_line_number), summary_(ExtractSummary(a_message)), message_(a_message) {} // Gets the outcome of the test part. Type type() const { return type_; } // Gets the name of the source file where the test part took place, or // NULL if it's unknown. const char* file_name() const { return file_name_.empty() ? nullptr : file_name_.c_str(); } // Gets the line in the source file where the test part took place, // or -1 if it's unknown. int line_number() const { return line_number_; } // Gets the summary of the failure message. const char* summary() const { return summary_.c_str(); } // Gets the message associated with the test part. const char* message() const { return message_.c_str(); } // Returns true if and only if the test part was skipped. bool skipped() const { return type_ == kSkip; } // Returns true if and only if the test part passed. bool passed() const { return type_ == kSuccess; } // Returns true if and only if the test part non-fatally failed. bool nonfatally_failed() const { return type_ == kNonFatalFailure; } // Returns true if and only if the test part fatally failed. bool fatally_failed() const { return type_ == kFatalFailure; } // Returns true if and only if the test part failed. bool failed() const { return fatally_failed() || nonfatally_failed(); } private: Type type_; // Gets the summary of the failure message by omitting the stack // trace in it. static std::string ExtractSummary(const char* message); // The name of the source file where the test part took place, or // "" if the source file is unknown. std::string file_name_; // The line in the source file where the test part took place, or -1 // if the line number is unknown. int line_number_; std::string summary_; // The test failure summary. std::string message_; // The test failure message. }; // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result); // An array of TestPartResult objects. // // Don't inherit from TestPartResultArray as its destructor is not // virtual. class GTEST_API_ TestPartResultArray { public: TestPartResultArray() {} // Appends the given TestPartResult to the array. void Append(const TestPartResult& result); // Returns the TestPartResult at the given index (0-based). const TestPartResult& GetTestPartResult(int index) const; // Returns the number of TestPartResult objects in the array. int size() const; private: std::vector<TestPartResult> array_; TestPartResultArray(const TestPartResultArray&) = delete; TestPartResultArray& operator=(const TestPartResultArray&) = delete; }; // This interface knows how to report a test part result. class GTEST_API_ TestPartResultReporterInterface { public: virtual ~TestPartResultReporterInterface() {} virtual void ReportTestPartResult(const TestPartResult& result) = 0; }; namespace internal { // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a // statement generates new fatal failures. To do so it registers itself as the // current test part result reporter. Besides checking if fatal failures were // reported, it only delegates the reporting to the former result reporter. // The original result reporter is restored in the destructor. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. class GTEST_API_ HasNewFatalFailureHelper : public TestPartResultReporterInterface { public: HasNewFatalFailureHelper(); ~HasNewFatalFailureHelper() override; void ReportTestPartResult(const TestPartResult& result) override; bool has_new_fatal_failure() const { return has_new_fatal_failure_; } private: bool has_new_fatal_failure_; TestPartResultReporterInterface* original_reporter_; HasNewFatalFailureHelper(const HasNewFatalFailureHelper&) = delete; HasNewFatalFailureHelper& operator=(const HasNewFatalFailureHelper&) = delete; }; } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
7,111
36.235602
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest-typed-test.h
// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ // This header implements typed tests and type-parameterized tests. // Typed (aka type-driven) tests repeat the same test for types in a // list. You must know which types you want to test with when writing // typed tests. Here's how you do it: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template <typename T> class FooTest : public testing::Test { public: ... typedef std::list<T> List; static T shared_; T value_; }; // Next, associate a list of types with the test suite, which will be // repeated for each type in the list. The typedef is necessary for // the macro to parse correctly. typedef testing::Types<char, int, unsigned int> MyTypes; TYPED_TEST_SUITE(FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // TYPED_TEST_SUITE(FooTest, int); // Then, use TYPED_TEST() instead of TEST_F() to define as many typed // tests for this test suite as you want. TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to the special name TypeParam to get the type // parameter. Since we are inside a derived class template, C++ requires // us to visit the members of FooTest via 'this'. TypeParam n = this->value_; // To visit static members of the fixture, add the TestFixture:: // prefix. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the "typename // TestFixture::" prefix. typename TestFixture::List values; values.push_back(n); ... } TYPED_TEST(FooTest, HasPropertyA) { ... } // TYPED_TEST_SUITE takes an optional third argument which allows to specify a // class that generates custom test name suffixes based on the type. This should // be a class which has a static template function GetName(int index) returning // a string for each type. The provided integer index equals the index of the // type in the provided type list. In many cases the index can be ignored. // // For example: // class MyTypeNames { // public: // template <typename T> // static std::string GetName(int) { // if (std::is_same<T, char>()) return "char"; // if (std::is_same<T, int>()) return "int"; // if (std::is_same<T, unsigned int>()) return "unsignedInt"; // } // }; // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames); #endif // 0 // Type-parameterized tests are abstract test patterns parameterized // by a type. Compared with typed tests, type-parameterized tests // allow you to define the test pattern without knowing what the type // parameters are. The defined pattern can be instantiated with // different types any number of times, in any number of translation // units. // // If you are designing an interface or concept, you can define a // suite of type-parameterized tests to verify properties that any // valid implementation of the interface/concept should have. Then, // each implementation can easily instantiate the test suite to verify // that it conforms to the requirements, without having to write // similar tests repeatedly. Here's an example: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template <typename T> class FooTest : public testing::Test { ... }; // Next, declare that you will define a type-parameterized test suite // (the _P suffix is for "parameterized" or "pattern", whichever you // prefer): TYPED_TEST_SUITE_P(FooTest); // Then, use TYPED_TEST_P() to define as many type-parameterized tests // for this type-parameterized test suite as you want. TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; ... } TYPED_TEST_P(FooTest, HasPropertyA) { ... } // Now the tricky part: you need to register all test patterns before // you can instantiate them. The first argument of the macro is the // test suite name; the rest are the names of the tests in this test // case. REGISTER_TYPED_TEST_SUITE_P(FooTest, DoesBlah, HasPropertyA); // Finally, you are free to instantiate the pattern with the types you // want. If you put the above code in a header file, you can #include // it in multiple C++ source files and instantiate it multiple times. // // To distinguish different instances of the pattern, the first // argument to the INSTANTIATE_* macro is a prefix that will be added // to the actual test suite name. Remember to pick unique prefixes for // different instances. typedef testing::Types<char, int, unsigned int> MyTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); // // Similar to the optional argument of TYPED_TEST_SUITE above, // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to // generate custom names. // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames); #endif // 0 #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-type-util.h" // Implements typed tests. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the typedef for the type parameters of the // given test suite. #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_ // Expands to the name of the typedef for the NameGenerator, responsible for // creating the suffixes of the name. #define GTEST_NAME_GENERATOR_(TestSuiteName) \ gtest_type_params_##TestSuiteName##_NameGenerator #define TYPED_TEST_SUITE(CaseName, Types, ...) \ typedef ::testing::internal::GenerateTypeList<Types>::type \ GTEST_TYPE_PARAMS_(CaseName); \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) #define TYPED_TEST(CaseName, TestName) \ static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ "test-name must not be empty"); \ template <typename gtest_TypeParam_> \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName<gtest_TypeParam_> { \ private: \ typedef CaseName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ void TestBody() override; \ }; \ static bool gtest_##CaseName##_##TestName##_registered_ \ GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \ CaseName, \ ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)>, \ GTEST_TYPE_PARAMS_( \ CaseName)>::Register("", \ ::testing::internal::CodeLocation( \ __FILE__, __LINE__), \ GTEST_STRINGIFY_(CaseName), \ GTEST_STRINGIFY_(TestName), 0, \ ::testing::internal::GenerateNames< \ GTEST_NAME_GENERATOR_(CaseName), \ GTEST_TYPE_PARAMS_(CaseName)>()); \ template <typename gtest_TypeParam_> \ void GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)<gtest_TypeParam_>::TestBody() // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_CASE \ static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \ TYPED_TEST_SUITE #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Implements type-parameterized tests. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the namespace name that the type-parameterized tests for // the given type-parameterized test suite are defined in. The exact // name of the namespace is subject to change without notice. #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the variable used to remember the names of // the defined tests in the given test suite. #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \ gtest_typed_test_suite_p_state_##TestSuiteName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // // Expands to the name of the variable used to remember the names of // the registered tests in the given test suite. #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \ gtest_registered_test_names_##TestSuiteName##_ // The variables defined in the type-parameterized test macros are // static as typically these macros are used in a .h file that can be // #included in multiple translation units linked together. #define TYPED_TEST_SUITE_P(SuiteName) \ static ::testing::internal::TypedTestSuitePState \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_CASE_P \ static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \ TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_P(SuiteName, TestName) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ template <typename gtest_TypeParam_> \ class TestName : public SuiteName<gtest_TypeParam_> { \ private: \ typedef SuiteName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ void TestBody() override; \ }; \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ GTEST_STRINGIFY_(TestName)); \ } \ template <typename gtest_TypeParam_> \ void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName<gtest_TypeParam_>::TestBody() // Note: this won't work correctly if the trailing arguments are macros. #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ } \ static const char* const GTEST_REGISTERED_TEST_NAMES_( \ SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define REGISTER_TYPED_TEST_CASE_P \ static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \ ""); \ REGISTER_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ "test-suit-prefix must not be empty"); \ static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTestSuite< \ SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ ::testing::internal::GenerateTypeList<Types>::type>:: \ Register(GTEST_STRINGIFY_(Prefix), \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ GTEST_STRINGIFY_(SuiteName), \ GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ ::testing::internal::GenerateNames< \ ::testing::internal::NameGeneratorSelector< \ __VA_ARGS__>::type, \ ::testing::internal::GenerateTypeList<Types>::type>()) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TYPED_TEST_CASE_P \ static_assert( \ ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \ INSTANTIATE_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
15,921
46.957831
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest_pred_impl.h
// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Implements a family of generic predicate assertion macros. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #include "gtest/gtest-assertion-result.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" namespace testing { // This header implements a family of generic predicate assertion // macros: // // ASSERT_PRED_FORMAT1(pred_format, v1) // ASSERT_PRED_FORMAT2(pred_format, v1, v2) // ... // // where pred_format is a function or functor that takes n (in the // case of ASSERT_PRED_FORMATn) values and their source expression // text, and returns a testing::AssertionResult. See the definition // of ASSERT_EQ in gtest.h for an example. // // If you don't care about formatting, you can use the more // restrictive version: // // ASSERT_PRED1(pred, v1) // ASSERT_PRED2(pred, v1, v2) // ... // // where pred is an n-ary function or functor that returns bool, // and the values v1, v2, ..., must support the << operator for // streaming to std::ostream. // // We also define the EXPECT_* variations. // // For now we only support predicates whose arity is at most 5. // Please email [email protected] if you need // support for higher arities. // GTEST_ASSERT_ is the basic statement to which all of the assertions // in this file reduce. Don't use this in your code. #define GTEST_ASSERT_(expression, on_failure) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ ; \ else \ on_failure(gtest_ar.failure_message()) // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. template <typename Pred, typename T1> AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Don't use this in your code. #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \ GTEST_ASSERT_(pred_format(#v1, v1), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. #define GTEST_PRED1_(pred, v1, on_failure) \ GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure) // Unary predicate assertion macros. #define EXPECT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) #define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. template <typename Pred, typename T1, typename T2> AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Don't use this in your code. #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. #define GTEST_PRED2_(pred, v1, v2, on_failure) \ GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \ on_failure) // Binary predicate assertion macros. #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) #define ASSERT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. template <typename Pred, typename T1, typename T2, typename T3> AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, Pred pred, const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Don't use this in your code. #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. #define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \ GTEST_ASSERT_( \ ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \ on_failure) // Ternary predicate assertion macros. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) #define ASSERT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. template <typename Pred, typename T1, typename T2, typename T3, typename T4> AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" << e4 << " evaluates to " << ::testing::PrintToString(v4); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Don't use this in your code. #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \ GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \ v1, v2, v3, v4), \ on_failure) // 4-ary predicate assertion macros. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) #define ASSERT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. template <typename Pred, typename T1, typename T2, typename T3, typename T4, typename T5> AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ", " << e5 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n" << e5 << " evaluates to " << ::testing::PrintToString(v5); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Don't use this in your code. #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \ pred, v1, v2, v3, v4, v5), \ on_failure) // 5-ary predicate assertion macros. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
12,783
44.657143
79
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/gtest_prod.h
// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google C++ Testing and Mocking Framework definitions useful in production // code. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ // When you need to test the private or protected members of a class, // use the FRIEND_TEST macro to declare your tests as friends of the // class. For example: // // class MyClass { // private: // void PrivateMethod(); // FRIEND_TEST(MyClassTest, PrivateMethodWorks); // }; // // class MyClassTest : public testing::Test { // // ... // }; // // TEST_F(MyClassTest, PrivateMethodWorks) { // // Can call MyClass::PrivateMethod() here. // } // // Note: The test class must be in the same namespace as the class being tested. // For example, putting MyClassTest in an anonymous namespace will not work. #define FRIEND_TEST(test_case_name, test_name) \ friend class test_case_name##_##test_name##_Test #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
2,502
40.032787
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/gtest-death-test-internal.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #include <stdio.h> #include <memory> #include "gtest/gtest-matchers.h" #include "gtest/internal/gtest-internal.h" GTEST_DECLARE_string_(internal_run_death_test); namespace testing { namespace internal { // Names of the flags (needed for parsing Google Test flags). const char kDeathTestStyleFlag[] = "death_test_style"; const char kDeathTestUseFork[] = "death_test_use_fork"; const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; #if GTEST_HAS_DEATH_TEST GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) // DeathTest is a class that hides much of the complexity of the // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method // returns a concrete class that depends on the prevailing death test // style, as defined by the --gtest_death_test_style and/or // --gtest_internal_run_death_test flags. // In describing the results of death tests, these terms are used with // the corresponding definitions: // // exit status: The integer exit information in the format specified // by wait(2) // exit code: The integer code passed to exit(3), _exit(2), or // returned from main() class GTEST_API_ DeathTest { public: // Create returns false if there was an error determining the // appropriate action to take for the current death test; for example, // if the gtest_death_test_style flag is set to an invalid value. // The LastMessage method will return a more detailed message in that // case. Otherwise, the DeathTest pointer pointed to by the "test" // argument is set. If the death test should be skipped, the pointer // is set to NULL; otherwise, it is set to the address of a new concrete // DeathTest object that controls the execution of the current test. static bool Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test); DeathTest(); virtual ~DeathTest() {} // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: explicit ReturnSentinel(DeathTest* test) : test_(test) {} ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } private: DeathTest* const test_; ReturnSentinel(const ReturnSentinel&) = delete; ReturnSentinel& operator=(const ReturnSentinel&) = delete; }; // An enumeration of possible roles that may be taken when a death // test is encountered. EXECUTE means that the death test logic should // be executed immediately. OVERSEE means that the program should prepare // the appropriate environment for a child process to execute the death // test, then wait for it to complete. enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; // An enumeration of the three reasons that a test might be aborted. enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_THREW_EXCEPTION, TEST_DID_NOT_DIE }; // Assumes one of the above roles. virtual TestRole AssumeRole() = 0; // Waits for the death test to finish and returns its status. virtual int Wait() = 0; // Returns true if the death test passed; that is, the test process // exited during the test, its exit status matches a user-supplied // predicate, and its stderr output matches a user-supplied regular // expression. // The user-supplied predicate may be a macro expression rather // than a function pointer or functor, or else Wait and Passed could // be combined. virtual bool Passed(bool exit_status_ok) = 0; // Signals that the death test did not die as expected. virtual void Abort(AbortReason reason) = 0; // Returns a human-readable outcome message regarding the outcome of // the last death test. static const char* LastMessage(); static void set_last_death_test_message(const std::string& message); private: // A string containing a description of the outcome of the last death test. static std::string last_death_test_message_; DeathTest(const DeathTest&) = delete; DeathTest& operator=(const DeathTest&) = delete; }; GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: virtual ~DeathTestFactory() {} virtual bool Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test) = 0; }; // A concrete DeathTestFactory implementation for normal use. class DefaultDeathTestFactory : public DeathTestFactory { public: bool Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test) override; }; // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads // and interpreted as a regex (rather than an Eq matcher) for legacy // compatibility. inline Matcher<const ::std::string&> MakeDeathTestMatcher( ::testing::internal::RE regex) { return ContainsRegex(regex.pattern()); } inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) { return ContainsRegex(regex); } inline Matcher<const ::std::string&> MakeDeathTestMatcher( const ::std::string& regex) { return ContainsRegex(regex); } // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's // used directly. inline Matcher<const ::std::string&> MakeDeathTestMatcher( Matcher<const ::std::string&> matcher) { return matcher; } // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. #if GTEST_HAS_EXCEPTIONS #define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } catch (const ::std::exception& gtest_exception) { \ fprintf( \ stderr, \ "\n%s: Caught std::exception-derived exception escaping the " \ "death test statement. Exception message: %s\n", \ ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ gtest_exception.what()); \ fflush(stderr); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } catch (...) { \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } #else #define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) #endif // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::DeathTest* gtest_dt; \ if (!::testing::internal::DeathTest::Create( \ #statement, \ ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \ __FILE__, __LINE__, &gtest_dt)) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ if (gtest_dt != nullptr) { \ std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \ switch (gtest_dt->AssumeRole()) { \ case ::testing::internal::DeathTest::OVERSEE_TEST: \ if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ break; \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \ ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \ gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ break; \ } \ } \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \ : fail(::testing::internal::DeathTest::LastMessage()) // The symbol "fail" here expands to something into which a message // can be streamed. // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in // NDEBUG mode. In this case we need the statements to be executed and the macro // must accept a streamed message even though the message is never printed. // The regex object is not evaluated, but it is used to prevent "unused" // warnings and to avoid an expression that doesn't compile in debug mode. #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } else if (!::testing::internal::AlwaysTrue()) { \ ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \ } else \ ::testing::Message() // A class representing the parsed contents of the // --gtest_internal_run_death_test flag, as it existed when // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index, int a_write_fd) : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { if (write_fd_ >= 0) posix::Close(write_fd_); } const std::string& file() const { return file_; } int line() const { return line_; } int index() const { return index_; } int write_fd() const { return write_fd_; } private: std::string file_; int line_; int index_; int write_fd_; InternalRunDeathTestFlag(const InternalRunDeathTestFlag&) = delete; InternalRunDeathTestFlag& operator=(const InternalRunDeathTestFlag&) = delete; }; // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); #endif // GTEST_HAS_DEATH_TEST } // namespace internal } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
13,892
44.254072
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/gtest-filepath.h
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Test filepath utilities // // This header file declares classes and functions used internally by // Google Test. They are subject to change without notice. // // This file is #included in gtest/internal/gtest-internal.h. // Do not include this header file separately! // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #include "gtest/internal/gtest-string.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) namespace testing { namespace internal { // FilePath - a class for file and directory pathname manipulation which // handles platform-specific conventions (like the pathname separator). // Used for helper functions for naming files in a directory for xml output. // Except for Set methods, all methods are const or static, which provides an // "immutable value object" -- useful for peace of mind. // A FilePath with a value ending in a path separator ("like/this/") represents // a directory, otherwise it is assumed to represent a file. In either case, // it may or may not represent an actual file or directory in the file system. // Names are NOT checked for syntax correctness -- no checking for illegal // characters, malformed paths, etc. class GTEST_API_ FilePath { public: FilePath() : pathname_("") {} FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {} explicit FilePath(const std::string& pathname) : pathname_(pathname) { Normalize(); } FilePath& operator=(const FilePath& rhs) { Set(rhs); return *this; } void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } const std::string& string() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } // Returns the current working directory, or "" if unsuccessful. static FilePath GetCurrentDir(); // Given directory = "dir", base_name = "test", number = 0, // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. static FilePath MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension); // Given directory = "dir", relative_path = "test.xml", // returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. static FilePath ConcatPaths(const FilePath& directory, const FilePath& relative_path); // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or // directory/base_name_<number>.extension if directory/base_name.extension // already exists. The number will be incremented until a pathname is found // that does not already exist. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. static FilePath GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension); // Returns true if and only if the path is "". bool IsEmpty() const { return pathname_.empty(); } // If input name has a trailing separator character, removes it and returns // the name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath RemoveTrailingPathSeparator() const; // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns // the FilePath unmodified. If there is no file part ("just_a_dir/") it // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath RemoveDirectoryName() const; // RemoveFileName returns the directory path with the filename removed. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". // If the FilePath is "a_file" or "/a_file", RemoveFileName returns // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath RemoveFileName() const; // Returns a copy of the FilePath with the case-insensitive extension removed. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath RemoveExtension(const char* extension) const; // Creates directories so that path exists. Returns true if successful or if // the directories already exist; returns false if unable to create // directories for any reason. Will also return false if the FilePath does // not represent a directory (that is, it doesn't end with a path separator). bool CreateDirectoriesRecursively() const; // Create the directory so that path exists. Returns true if successful or // if the directory already exists; returns false if unable to create the // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool CreateFolder() const; // Returns true if FilePath describes something in the file-system, // either a file, directory, or whatever, and that something exists. bool FileOrDirectoryExists() const; // Returns true if pathname describes a directory in the file-system // that exists. bool DirectoryExists() const; // Returns true if FilePath ends with a path separator, which indicates that // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool IsDirectory() const; // Returns true if pathname describes a root directory. (Windows has one // root directory per disk drive.) bool IsRootDirectory() const; // Returns true if pathname describes an absolute path. bool IsAbsolutePath() const; private: // Replaces multiple consecutive separators with a single separator. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". // // A pathname with multiple consecutive separators may occur either through // user error or as a result of some scripts or APIs that generate a pathname // with a trailing separator. On other platforms the same API or script // may NOT generate a pathname with a trailing "/". Then elsewhere that // pathname may have another "/" and pathname components added to it, // without checking for the separator already being there. // The script language and operating system may allow paths like "foo//bar" // but some of the functions in FilePath will not handle that correctly. In // particular, RemoveTrailingPathSeparator() only removes one separator, and // it is called in CreateDirectoriesRecursively() assuming that it will change // a pathname from directory syntax (trailing separator) to filename syntax. // // On Windows this method also replaces the alternate path separator '/' with // the primary path separator '\\', so that for example "bar\\/\\foo" becomes // "bar\\foo". void Normalize(); // Returns a pointer to the last occurrence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FindLastPathSeparator() const; // Returns the length of the path root, including the directory separator at // the end of the prefix. Returns zero by definition if the path is relative. // Examples: // - [Windows] "..\Sibling" => 0 // - [Windows] "\Windows" => 1 // - [Windows] "C:/Windows\Notepad.exe" => 3 // - [Windows] "\\Host\Share\C$/Windows" => 13 // - [UNIX] "/bin" => 1 size_t CalculateRootLength() const; std::string pathname_; }; // class FilePath } // namespace internal } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
10,220
45.248869
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/gtest-port-arch.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the GTEST_OS_* macro. // It is separate from gtest-port.h so that custom/gtest-port.h can include it. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ // Determines the platform on which Google Test is compiled. #ifdef __CYGWIN__ #define GTEST_OS_CYGWIN 1 #elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__) #define GTEST_OS_WINDOWS_MINGW 1 #define GTEST_OS_WINDOWS 1 #elif defined _WIN32 #define GTEST_OS_WINDOWS 1 #ifdef _WIN32_WCE #define GTEST_OS_WINDOWS_MOBILE 1 #elif defined(WINAPI_FAMILY) #include <winapifamily.h> #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define GTEST_OS_WINDOWS_DESKTOP 1 #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) #define GTEST_OS_WINDOWS_PHONE 1 #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define GTEST_OS_WINDOWS_RT 1 #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) #define GTEST_OS_WINDOWS_PHONE 1 #define GTEST_OS_WINDOWS_TV_TITLE 1 #else // WINAPI_FAMILY defined but no known partition matched. // Default to desktop. #define GTEST_OS_WINDOWS_DESKTOP 1 #endif #else #define GTEST_OS_WINDOWS_DESKTOP 1 #endif // _WIN32_WCE #elif defined __OS2__ #define GTEST_OS_OS2 1 #elif defined __APPLE__ #define GTEST_OS_MAC 1 #include <TargetConditionals.h> #if TARGET_OS_IPHONE #define GTEST_OS_IOS 1 #endif #elif defined __DragonFly__ #define GTEST_OS_DRAGONFLY 1 #elif defined __FreeBSD__ #define GTEST_OS_FREEBSD 1 #elif defined __Fuchsia__ #define GTEST_OS_FUCHSIA 1 #elif defined(__GNU__) #define GTEST_OS_GNU_HURD 1 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__) #define GTEST_OS_GNU_KFREEBSD 1 #elif defined __linux__ #define GTEST_OS_LINUX 1 #if defined __ANDROID__ #define GTEST_OS_LINUX_ANDROID 1 #endif #elif defined __MVS__ #define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) #define GTEST_OS_SOLARIS 1 #elif defined(_AIX) #define GTEST_OS_AIX 1 #elif defined(__hpux) #define GTEST_OS_HPUX 1 #elif defined __native_client__ #define GTEST_OS_NACL 1 #elif defined __NetBSD__ #define GTEST_OS_NETBSD 1 #elif defined __OpenBSD__ #define GTEST_OS_OPENBSD 1 #elif defined __QNX__ #define GTEST_OS_QNX 1 #elif defined(__HAIKU__) #define GTEST_OS_HAIKU 1 #elif defined ESP8266 #define GTEST_OS_ESP8266 1 #elif defined ESP32 #define GTEST_OS_ESP32 1 #elif defined(__XTENSA__) #define GTEST_OS_XTENSA 1 #elif defined(__hexagon__) #define GTEST_OS_QURT 1 #endif // __CYGWIN__ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
4,178
34.117647
79
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/gtest-string.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The Google C++ Testing and Mocking Framework (Google Test) // // This header file declares the String class and functions used internally by // Google Test. They are subject to change without notice. They should not used // by code external to Google Test. // // This header file is #included by gtest-internal.h. // It should not be #included by other files. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #ifdef __BORLANDC__ // string.h is not guaranteed to provide strcpy on C++ Builder. #include <mem.h> #endif #include <string.h> #include <cstdint> #include <string> #include "gtest/internal/gtest-port.h" namespace testing { namespace internal { // String - an abstract class holding static string utilities. class GTEST_API_ String { public: // Static utility methods // Clones a 0-terminated C string, allocating memory using new. The // caller is responsible for deleting the return value using // delete[]. Returns the cloned string, or NULL if the input is // NULL. // // This is different from strdup() in string.h, which allocates // memory using malloc(). static const char* CloneCString(const char* c_str); #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be // able to pass strings to Win32 APIs on CE we need to convert them // to 'Unicode', UTF-16. // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. // // The wide string is created using the ANSI codepage (CP_ACP) to // match the behaviour of the ANSI versions of Win32 calls and the // C runtime. static LPCWSTR AnsiToUtf16(const char* c_str); // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. // // The returned string is created using the ANSI codepage (CP_ACP) to // match the behaviour of the ANSI versions of Win32 calls and the // C runtime. static const char* Utf16ToAnsi(LPCWSTR utf16_str); #endif // Compares two C strings. Returns true if and only if they have the same // content. // // Unlike strcmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool CStringEquals(const char* lhs, const char* rhs); // Converts a wide C string to a String using the UTF-8 encoding. // NULL will be converted to "(null)". If an error occurred during // the conversion, "(failed to convert from wide string)" is // returned. static std::string ShowWideCString(const wchar_t* wide_c_str); // Compares two wide C strings. Returns true if and only if they have the // same content. // // Unlike wcscmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Compares two C strings, ignoring case. Returns true if and only if // they have the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, // including the empty string. static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); // Compares two wide C strings, ignoring case. Returns true if and only if // they have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Returns true if and only if the given string ends with the given suffix, // ignoring case. Any string is considered to end with an empty suffix. static bool EndsWithCaseInsensitive(const std::string& str, const std::string& suffix); // Formats an int value as "%02d". static std::string FormatIntWidth2(int value); // "%02d" for width == 2 // Formats an int value to given width with leading zeros. static std::string FormatIntWidthN(int value, int width); // Formats an int value as "%X". static std::string FormatHexInt(int value); // Formats an int value as "%X". static std::string FormatHexUInt32(uint32_t value); // Formats a byte as "%02X". static std::string FormatByte(unsigned char value); private: String(); // Not meant to be instantiated. }; // class String // Gets the content of the stringstream's buffer as an std::string. Each '\0' // character in the buffer is replaced with "\\0". GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); } // namespace internal } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
7,301
40.022472
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/gtest-type-util.h
// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Type utilities needed for implementing typed and type-parameterized // tests. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #include "gtest/internal/gtest-port.h" // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). #if GTEST_HAS_CXXABI_H_ #include <cxxabi.h> #elif defined(__HP_aCC) #include <acxx_demangle.h> #endif // GTEST_HASH_CXXABI_H_ namespace testing { namespace internal { // Canonicalizes a given name with respect to the Standard C++ Library. // This handles removing the inline namespace within `std` that is // used by various standard libraries (e.g., `std::__1`). Names outside // of namespace std are returned unmodified. inline std::string CanonicalizeForStdLibVersioning(std::string s) { static const char prefix[] = "std::__"; if (s.compare(0, strlen(prefix), prefix) == 0) { std::string::size_type end = s.find("::", strlen(prefix)); if (end != s.npos) { // Erase everything between the initial `std` and the second `::`. s.erase(strlen("std"), end - strlen("std")); } } return s; } #if GTEST_HAS_RTTI // GetTypeName(const std::type_info&) returns a human-readable name of type T. inline std::string GetTypeName(const std::type_info& type) { const char* const name = type.name(); #if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) int status = 0; // gcc's implementation of typeid(T).name() mangles the type name, // so we have to demangle it. #if GTEST_HAS_CXXABI_H_ using abi::__cxa_demangle; #endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status); const std::string name_str(status == 0 ? readable_name : name); free(readable_name); return CanonicalizeForStdLibVersioning(name_str); #else return name; #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC } #endif // GTEST_HAS_RTTI // GetTypeName<T>() returns a human-readable name of type T if and only if // RTTI is enabled, otherwise it returns a dummy type name. // NB: This function is also used in Google Mock, so don't move it inside of // the typed-test-only section below. template <typename T> std::string GetTypeName() { #if GTEST_HAS_RTTI return GetTypeName(typeid(T)); #else return "<type>"; #endif // GTEST_HAS_RTTI } // A unique type indicating an empty node struct None {}; #define GTEST_TEMPLATE_ \ template <typename T> \ class // The template "selector" struct TemplateSel<Tmpl> is used to // represent Tmpl, which must be a class template with one type // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined // as the type Tmpl<T>. This allows us to actually instantiate the // template "selected" by TemplateSel<Tmpl>. // // This trick is necessary for simulating typedef for class templates, // which C++ doesn't support directly. template <GTEST_TEMPLATE_ Tmpl> struct TemplateSel { template <typename T> struct Bind { typedef Tmpl<T> type; }; }; #define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_> struct Templates { using Head = TemplateSel<Head_>; using Tail = Templates<Tail_...>; }; template <GTEST_TEMPLATE_ Head_> struct Templates<Head_> { using Head = TemplateSel<Head_>; using Tail = None; }; // Tuple-like type lists template <typename Head_, typename... Tail_> struct Types { using Head = Head_; using Tail = Types<Tail_...>; }; template <typename Head_> struct Types<Head_> { using Head = Head_; using Tail = None; }; // Helper metafunctions to tell apart a single type from types // generated by ::testing::Types template <typename... Ts> struct ProxyTypeList { using type = Types<Ts...>; }; template <typename> struct is_proxy_type_list : std::false_type {}; template <typename... Ts> struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {}; // Generator which conditionally creates type lists. // It recognizes if a requested type list should be created // and prevents creating a new type list nested within another one. template <typename T> struct GenerateTypeList { private: using proxy = typename std::conditional<is_proxy_type_list<T>::value, T, ProxyTypeList<T>>::type; public: using type = typename proxy::type; }; } // namespace internal template <typename... Ts> using Types = internal::ProxyTypeList<Ts...>; } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
6,247
32.411765
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/custom/gtest-port.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
1,873
48.315789
73
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/custom/gtest-printers.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // This file provides an injection point for custom printers in a local // installation of gTest. // It will be included from gtest-printers.h and the overrides in this file // will be visible to everyone. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
2,094
47.72093
75
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/include/gtest/internal/custom/gtest.h
// Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
1,858
47.921053
73
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/samples/prime_tables.h
// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This provides interface PrimeTable that determines whether a number is a // prime and determines a next prime number. This interface is used // in Google Test samples demonstrating use of parameterized tests. #ifndef GOOGLETEST_SAMPLES_PRIME_TABLES_H_ #define GOOGLETEST_SAMPLES_PRIME_TABLES_H_ #include <algorithm> // The prime table interface. class PrimeTable { public: virtual ~PrimeTable() {} // Returns true if and only if n is a prime number. virtual bool IsPrime(int n) const = 0; // Returns the smallest prime number greater than p; or returns -1 // if the next prime is beyond the capacity of the table. virtual int GetNextPrime(int p) const = 0; }; // Implementation #1 calculates the primes on-the-fly. class OnTheFlyPrimeTable : public PrimeTable { public: bool IsPrime(int n) const override { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) { // n is divisible by an integer other than 1 and itself. if ((n % i) == 0) return false; } return true; } int GetNextPrime(int p) const override { if (p < 0) return -1; for (int n = p + 1;; n++) { if (IsPrime(n)) return n; } } }; // Implementation #2 pre-calculates the primes and stores the result // in an array. class PreCalculatedPrimeTable : public PrimeTable { public: // 'max' specifies the maximum number the prime table holds. explicit PreCalculatedPrimeTable(int max) : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) { CalculatePrimesUpTo(max); } ~PreCalculatedPrimeTable() override { delete[] is_prime_; } bool IsPrime(int n) const override { return 0 <= n && n < is_prime_size_ && is_prime_[n]; } int GetNextPrime(int p) const override { for (int n = p + 1; n < is_prime_size_; n++) { if (is_prime_[n]) return n; } return -1; } private: void CalculatePrimesUpTo(int max) { ::std::fill(is_prime_, is_prime_ + is_prime_size_, true); is_prime_[0] = is_prime_[1] = false; // Checks every candidate for prime number (we know that 2 is the only even // prime). for (int i = 2; i * i <= max; i += i % 2 + 1) { if (!is_prime_[i]) continue; // Marks all multiples of i (except i itself) as non-prime. // We are starting here from i-th multiplier, because all smaller // complex numbers were already marked. for (int j = i * i; j <= max; j += i) { is_prime_[j] = false; } } } const int is_prime_size_; bool* const is_prime_; // Disables compiler warning "assignment operator could not be generated." void operator=(const PreCalculatedPrimeTable& rhs); }; #endif // GOOGLETEST_SAMPLES_PRIME_TABLES_H_
4,255
33.048
79
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/samples/sample1.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. #ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_ #define GOOGLETEST_SAMPLES_SAMPLE1_H_ // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n); // Returns true if and only if n is a prime number. bool IsPrime(int n); #endif // GOOGLETEST_SAMPLES_SAMPLE1_H_
1,919
44.714286
75
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/samples/sample2.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. #ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_ #define GOOGLETEST_SAMPLES_SAMPLE2_H_ #include <string.h> // A simple string class. class MyString { private: const char* c_string_; const MyString& operator=(const MyString& rhs); public: // Clones a 0-terminated C string, allocating memory using new. static const char* CloneCString(const char* a_c_string); //////////////////////////////////////////////////////////// // // C'tors // The default c'tor constructs a NULL string. MyString() : c_string_(nullptr) {} // Constructs a MyString by cloning a 0-terminated C string. explicit MyString(const char* a_c_string) : c_string_(nullptr) { Set(a_c_string); } // Copy c'tor MyString(const MyString& string) : c_string_(nullptr) { Set(string.c_string_); } //////////////////////////////////////////////////////////// // // D'tor. MyString is intended to be a final class, so the d'tor // doesn't need to be virtual. ~MyString() { delete[] c_string_; } // Gets the 0-terminated C string this MyString object represents. const char* c_string() const { return c_string_; } size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); } // Sets the 0-terminated C string this MyString object represents. void Set(const char* c_string); }; #endif // GOOGLETEST_SAMPLES_SAMPLE2_H_
2,981
36.275
80
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/samples/sample3-inl.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. #ifndef GOOGLETEST_SAMPLES_SAMPLE3_INL_H_ #define GOOGLETEST_SAMPLES_SAMPLE3_INL_H_ #include <stddef.h> // Queue is a simple queue implemented as a singled-linked list. // // The element type must support copy constructor. template <typename E> // E is the element type class Queue; // QueueNode is a node in a Queue, which consists of an element of // type E and a pointer to the next node. template <typename E> // E is the element type class QueueNode { friend class Queue<E>; public: // Gets the element in this node. const E& element() const { return element_; } // Gets the next node in the queue. QueueNode* next() { return next_; } const QueueNode* next() const { return next_; } private: // Creates a node with a given element value. The next pointer is // set to NULL. explicit QueueNode(const E& an_element) : element_(an_element), next_(nullptr) {} // We disable the default assignment operator and copy c'tor. const QueueNode& operator=(const QueueNode&); QueueNode(const QueueNode&); E element_; QueueNode* next_; }; template <typename E> // E is the element type. class Queue { public: // Creates an empty queue. Queue() : head_(nullptr), last_(nullptr), size_(0) {} // D'tor. Clears the queue. ~Queue() { Clear(); } // Clears the queue. void Clear() { if (size_ > 0) { // 1. Deletes every node. QueueNode<E>* node = head_; QueueNode<E>* next = node->next(); for (;;) { delete node; node = next; if (node == nullptr) break; next = node->next(); } // 2. Resets the member variables. head_ = last_ = nullptr; size_ = 0; } } // Gets the number of elements. size_t Size() const { return size_; } // Gets the first element of the queue, or NULL if the queue is empty. QueueNode<E>* Head() { return head_; } const QueueNode<E>* Head() const { return head_; } // Gets the last element of the queue, or NULL if the queue is empty. QueueNode<E>* Last() { return last_; } const QueueNode<E>* Last() const { return last_; } // Adds an element to the end of the queue. A copy of the element is // created using the copy constructor, and then stored in the queue. // Changes made to the element in the queue doesn't affect the source // object, and vice versa. void Enqueue(const E& element) { QueueNode<E>* new_node = new QueueNode<E>(element); if (size_ == 0) { head_ = last_ = new_node; size_ = 1; } else { last_->next_ = new_node; last_ = new_node; size_++; } } // Removes the head of the queue and returns it. Returns NULL if // the queue is empty. E* Dequeue() { if (size_ == 0) { return nullptr; } const QueueNode<E>* const old_head = head_; head_ = head_->next_; size_--; if (size_ == 0) { last_ = nullptr; } E* element = new E(old_head->element()); delete old_head; return element; } // Applies a function/functor on each element of the queue, and // returns the result in a new queue. The original queue is not // affected. template <typename F> Queue* Map(F function) const { Queue* new_queue = new Queue(); for (const QueueNode<E>* node = head_; node != nullptr; node = node->next_) { new_queue->Enqueue(function(node->element())); } return new_queue; } private: QueueNode<E>* head_; // The first node of the queue. QueueNode<E>* last_; // The last node of the queue. size_t size_; // The number of elements in the queue. // We disallow copying a queue. Queue(const Queue&); const Queue& operator=(const Queue&); }; #endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
5,376
30.261628
73
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/samples/sample4.h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. #ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_ #define GOOGLETEST_SAMPLES_SAMPLE4_H_ // A simple monotonic counter. class Counter { private: int counter_; public: // Creates a counter that starts at 0. Counter() : counter_(0) {} // Returns the current counter value, and increments it. int Increment(); // Returns the current counter value, and decrements it. int Decrement(); // Prints the current counter value to STDOUT. void Print() const; }; #endif // GOOGLETEST_SAMPLES_SAMPLE4_H_
2,132
38.5
73
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/test/googletest-param-test-test.h
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The Google C++ Testing and Mocking Framework (Google Test) // // This header file provides classes and functions used internally // for testing Google Test itself. #ifndef GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_ #define GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_ #include "gtest/gtest.h" // Test fixture for testing definition and instantiation of a test // in separate translation units. class ExternalInstantiationTest : public ::testing::TestWithParam<int> {}; // Test fixture for testing instantiation of a test in multiple // translation units. class InstantiationInMultipleTranslationUnitsTest : public ::testing::TestWithParam<int> {}; #endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
2,280
44.62
74
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/test/gtest-typed-test_test.h
// Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_ #define GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_ #include "gtest/gtest.h" using testing::Test; // For testing that the same type-parameterized test case can be // instantiated in different translation units linked together. // ContainerTest will be instantiated in both gtest-typed-test_test.cc // and gtest-typed-test2_test.cc. template <typename T> class ContainerTest : public Test {}; TYPED_TEST_SUITE_P(ContainerTest); TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { TypeParam container; } TYPED_TEST_P(ContainerTest, InitialSizeIsZero) { TypeParam container; EXPECT_EQ(0U, container.size()); } REGISTER_TYPED_TEST_SUITE_P(ContainerTest, CanBeDefaultConstructed, InitialSizeIsZero); #endif // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
2,393
40.275862
77
h
OpenCC
OpenCC-master/deps/gtest-1.12.1/googletest/test/production.h
// Copyright 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // This is part of the unit test for gtest_prod.h. #ifndef GOOGLETEST_TEST_PRODUCTION_H_ #define GOOGLETEST_TEST_PRODUCTION_H_ #include "gtest/gtest_prod.h" class PrivateCode { public: // Declares a friend test that does not use a fixture. FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers); // Declares a friend test that uses a fixture. FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers); PrivateCode(); int x() const { return x_; } private: void set_x(int an_x) { x_ = an_x; } int x_; }; #endif // GOOGLETEST_TEST_PRODUCTION_H_
2,131
37.071429
73
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/include/marisa/base.h
#ifndef MARISA_BASE_H_ #define MARISA_BASE_H_ // Old Visual C++ does not provide stdint.h. #ifndef _MSC_VER #include <stdint.h> #endif // _MSC_VER #ifdef __cplusplus #include <cstddef> #else // __cplusplus #include <stddef.h> #endif // __cplusplus #ifdef __cplusplus extern "C" { #endif // __cplusplus #ifdef _MSC_VER typedef unsigned __int8 marisa_uint8; typedef unsigned __int16 marisa_uint16; typedef unsigned __int32 marisa_uint32; typedef unsigned __int64 marisa_uint64; #else // _MSC_VER typedef uint8_t marisa_uint8; typedef uint16_t marisa_uint16; typedef uint32_t marisa_uint32; typedef uint64_t marisa_uint64; #endif // _MSC_VER #if defined(_WIN64) || defined(__amd64__) || defined(__x86_64__) || \ defined(__ia64__) || defined(__ppc64__) || defined(__powerpc64__) || \ defined(__sparc64__) || defined(__mips64__) || defined(__aarch64__) || \ defined(__s390x__) #define MARISA_WORD_SIZE 64 #else // defined(_WIN64), etc. #define MARISA_WORD_SIZE 32 #endif // defined(_WIN64), etc. //#define MARISA_WORD_SIZE (sizeof(void *) * 8) #define MARISA_UINT8_MAX ((marisa_uint8)~(marisa_uint8)0) #define MARISA_UINT16_MAX ((marisa_uint16)~(marisa_uint16)0) #define MARISA_UINT32_MAX ((marisa_uint32)~(marisa_uint32)0) #define MARISA_UINT64_MAX ((marisa_uint64)~(marisa_uint64)0) #define MARISA_SIZE_MAX ((size_t)~(size_t)0) #define MARISA_INVALID_LINK_ID MARISA_UINT32_MAX #define MARISA_INVALID_KEY_ID MARISA_UINT32_MAX #define MARISA_INVALID_EXTRA (MARISA_UINT32_MAX >> 8) // Error codes are defined as members of marisa_error_code. This library throws // an exception with one of the error codes when an error occurs. typedef enum marisa_error_code_ { // MARISA_OK means that a requested operation has succeeded. In practice, an // exception never has MARISA_OK because it is not an error. MARISA_OK = 0, // MARISA_STATE_ERROR means that an object was not ready for a requested // operation. For example, an operation to modify a fixed vector throws an // exception with MARISA_STATE_ERROR. MARISA_STATE_ERROR = 1, // MARISA_NULL_ERROR means that an invalid NULL pointer has been given. MARISA_NULL_ERROR = 2, // MARISA_BOUND_ERROR means that an operation has tried to access an out of // range address. MARISA_BOUND_ERROR = 3, // MARISA_RANGE_ERROR means that an out of range value has appeared in // operation. MARISA_RANGE_ERROR = 4, // MARISA_CODE_ERROR means that an undefined code has appeared in operation. MARISA_CODE_ERROR = 5, // MARISA_RESET_ERROR means that a smart pointer has tried to reset itself. MARISA_RESET_ERROR = 6, // MARISA_SIZE_ERROR means that a size has exceeded a library limitation. MARISA_SIZE_ERROR = 7, // MARISA_MEMORY_ERROR means that a memory allocation has failed. MARISA_MEMORY_ERROR = 8, // MARISA_IO_ERROR means that an I/O operation has failed. MARISA_IO_ERROR = 9, // MARISA_FORMAT_ERROR means that input was in invalid format. MARISA_FORMAT_ERROR = 10, } marisa_error_code; // Min/max values, flags and masks for dictionary settings are defined below. // Please note that unspecified settings will be replaced with the default // settings. For example, 0 is equivalent to (MARISA_DEFAULT_NUM_TRIES | // MARISA_DEFAULT_TRIE | MARISA_DEFAULT_TAIL | MARISA_DEFAULT_ORDER). // A dictionary consists of 3 tries in default. Usually more tries make a // dictionary space-efficient but time-inefficient. typedef enum marisa_num_tries_ { MARISA_MIN_NUM_TRIES = 0x00001, MARISA_MAX_NUM_TRIES = 0x0007F, MARISA_DEFAULT_NUM_TRIES = 0x00003, } marisa_num_tries; // This library uses a cache technique to accelerate search functions. The // following enumerated type marisa_cache_level gives a list of available cache // size options. A larger cache enables faster search but takes a more space. typedef enum marisa_cache_level_ { MARISA_HUGE_CACHE = 0x00080, MARISA_LARGE_CACHE = 0x00100, MARISA_NORMAL_CACHE = 0x00200, MARISA_SMALL_CACHE = 0x00400, MARISA_TINY_CACHE = 0x00800, MARISA_DEFAULT_CACHE = MARISA_NORMAL_CACHE } marisa_cache_level; // This library provides 2 kinds of TAIL implementations. typedef enum marisa_tail_mode_ { // MARISA_TEXT_TAIL merges last labels as zero-terminated strings. So, it is // available if and only if the last labels do not contain a NULL character. // If MARISA_TEXT_TAIL is specified and a NULL character exists in the last // labels, the setting is automatically switched to MARISA_BINARY_TAIL. MARISA_TEXT_TAIL = 0x01000, // MARISA_BINARY_TAIL also merges last labels but as byte sequences. It uses // a bit vector to detect the end of a sequence, instead of NULL characters. // So, MARISA_BINARY_TAIL requires a larger space if the average length of // labels is greater than 8. MARISA_BINARY_TAIL = 0x02000, MARISA_DEFAULT_TAIL = MARISA_TEXT_TAIL, } marisa_tail_mode; // The arrangement of nodes affects the time cost of matching and the order of // predictive search. typedef enum marisa_node_order_ { // MARISA_LABEL_ORDER arranges nodes in ascending label order. // MARISA_LABEL_ORDER is useful if an application needs to predict keys in // label order. MARISA_LABEL_ORDER = 0x10000, // MARISA_WEIGHT_ORDER arranges nodes in descending weight order. // MARISA_WEIGHT_ORDER is generally a better choice because it enables faster // matching. MARISA_WEIGHT_ORDER = 0x20000, MARISA_DEFAULT_ORDER = MARISA_WEIGHT_ORDER, } marisa_node_order; typedef enum marisa_config_mask_ { MARISA_NUM_TRIES_MASK = 0x0007F, MARISA_CACHE_LEVEL_MASK = 0x00F80, MARISA_TAIL_MODE_MASK = 0x0F000, MARISA_NODE_ORDER_MASK = 0xF0000, MARISA_CONFIG_MASK = 0xFFFFF } marisa_config_mask; #ifdef __cplusplus } // extern "C" #endif // __cplusplus #ifdef __cplusplus // `std::swap` is in <utility> since C++ 11 but in <algorithm> in C++ 98: #if __cplusplus >= 201103L #include <utility> #else #include <algorithm> #endif namespace marisa { typedef ::marisa_uint8 UInt8; typedef ::marisa_uint16 UInt16; typedef ::marisa_uint32 UInt32; typedef ::marisa_uint64 UInt64; typedef ::marisa_error_code ErrorCode; typedef ::marisa_cache_level CacheLevel; typedef ::marisa_tail_mode TailMode; typedef ::marisa_node_order NodeOrder; using std::swap; } // namespace marisa #endif // __cplusplus #ifdef __cplusplus #include "marisa/exception.h" #include "marisa/scoped-ptr.h" #include "marisa/scoped-array.h" #endif // __cplusplus #endif // MARISA_BASE_H_
6,613
32.573604
79
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/include/marisa/exception.h
#ifndef MARISA_EXCEPTION_H_ #define MARISA_EXCEPTION_H_ #include <exception> #include "marisa/base.h" namespace marisa { // An exception object keeps a filename, a line number, an error code and an // error message. The message format is as follows: // "__FILE__:__LINE__: error_code: error_message" class Exception : public std::exception { public: Exception(const char *filename, int line, ErrorCode error_code, const char *error_message) : std::exception(), filename_(filename), line_(line), error_code_(error_code), error_message_(error_message) {} Exception(const Exception &ex) : std::exception(), filename_(ex.filename_), line_(ex.line_), error_code_(ex.error_code_), error_message_(ex.error_message_) {} virtual ~Exception() throw() {} Exception &operator=(const Exception &rhs) { filename_ = rhs.filename_; line_ = rhs.line_; error_code_ = rhs.error_code_; error_message_ = rhs.error_message_; return *this; } const char *filename() const { return filename_; } int line() const { return line_; } ErrorCode error_code() const { return error_code_; } const char *error_message() const { return error_message_; } virtual const char *what() const throw() { return error_message_; } private: const char *filename_; int line_; ErrorCode error_code_; const char *error_message_; }; // These macros are used to convert a line number to a string constant. #define MARISA_INT_TO_STR(value) #value #define MARISA_LINE_TO_STR(line) MARISA_INT_TO_STR(line) #define MARISA_LINE_STR MARISA_LINE_TO_STR(__LINE__) // MARISA_THROW throws an exception with a filename, a line number, an error // code and an error message. The message format is as follows: // "__FILE__:__LINE__: error_code: error_message" #define MARISA_THROW(error_code, error_message) \ (throw marisa::Exception(__FILE__, __LINE__, error_code, \ __FILE__ ":" MARISA_LINE_STR ": " #error_code ": " error_message)) // MARISA_THROW_IF throws an exception if `condition' is true. #define MARISA_THROW_IF(condition, error_code) \ (void)((!(condition)) || (MARISA_THROW(error_code, #condition), 0)) // MARISA_DEBUG_IF is ignored if _DEBUG is undefined. So, it is useful for // debugging time-critical codes. #ifdef _DEBUG #define MARISA_DEBUG_IF(cond, error_code) MARISA_THROW_IF(cond, error_code) #else #define MARISA_DEBUG_IF(cond, error_code) #endif } // namespace marisa #endif // MARISA_EXCEPTION_H_
2,504
29.180723
76
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/include/marisa/key.h
#ifndef MARISA_KEY_H_ #define MARISA_KEY_H_ #include "marisa/base.h" namespace marisa { class Key { public: Key() : ptr_(NULL), length_(0), union_() { union_.id = 0; } Key(const Key &key) : ptr_(key.ptr_), length_(key.length_), union_(key.union_) {} Key &operator=(const Key &key) { ptr_ = key.ptr_; length_ = key.length_; union_ = key.union_; return *this; } char operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= length_, MARISA_BOUND_ERROR); return ptr_[i]; } void set_str(const char *str) { MARISA_DEBUG_IF(str == NULL, MARISA_NULL_ERROR); std::size_t length = 0; while (str[length] != '\0') { ++length; } MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); ptr_ = str; length_ = (UInt32)length; } void set_str(const char *ptr, std::size_t length) { MARISA_DEBUG_IF((ptr == NULL) && (length != 0), MARISA_NULL_ERROR); MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); ptr_ = ptr; length_ = (UInt32)length; } void set_id(std::size_t id) { MARISA_DEBUG_IF(id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); union_.id = (UInt32)id; } void set_weight(float weight) { union_.weight = weight; } const char *ptr() const { return ptr_; } std::size_t length() const { return length_; } std::size_t id() const { return union_.id; } float weight() const { return union_.weight; } void clear() { Key().swap(*this); } void swap(Key &rhs) { marisa::swap(ptr_, rhs.ptr_); marisa::swap(length_, rhs.length_); marisa::swap(union_.id, rhs.union_.id); } private: const char *ptr_; UInt32 length_; union Union { UInt32 id; float weight; } union_; }; } // namespace marisa #endif // MARISA_KEY_H_
1,817
20.139535
71
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/include/marisa/keyset.h
#ifndef MARISA_KEYSET_H_ #define MARISA_KEYSET_H_ #include "marisa/key.h" namespace marisa { class Keyset { public: enum { BASE_BLOCK_SIZE = 4096, EXTRA_BLOCK_SIZE = 1024, KEY_BLOCK_SIZE = 256 }; Keyset(); void push_back(const Key &key); void push_back(const Key &key, char end_marker); void push_back(const char *str); void push_back(const char *ptr, std::size_t length, float weight = 1.0); const Key &operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); return key_blocks_[i / KEY_BLOCK_SIZE][i % KEY_BLOCK_SIZE]; } Key &operator[](std::size_t i) { MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); return key_blocks_[i / KEY_BLOCK_SIZE][i % KEY_BLOCK_SIZE]; } std::size_t num_keys() const { return size_; } bool empty() const { return size_ == 0; } std::size_t size() const { return size_; } std::size_t total_length() const { return total_length_; } void reset(); void clear(); void swap(Keyset &rhs); private: scoped_array<scoped_array<char> > base_blocks_; std::size_t base_blocks_size_; std::size_t base_blocks_capacity_; scoped_array<scoped_array<char> > extra_blocks_; std::size_t extra_blocks_size_; std::size_t extra_blocks_capacity_; scoped_array<scoped_array<Key> > key_blocks_; std::size_t key_blocks_size_; std::size_t key_blocks_capacity_; char *ptr_; std::size_t avail_; std::size_t size_; std::size_t total_length_; char *reserve(std::size_t size); void append_base_block(); void append_extra_block(std::size_t size); void append_key_block(); // Disallows copy and assignment. Keyset(const Keyset &); Keyset &operator=(const Keyset &); }; } // namespace marisa #endif // MARISA_KEYSET_H_
1,788
21.08642
74
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/intrin.h
#ifndef MARISA_GRIMOIRE_INTRIN_H_ #define MARISA_GRIMOIRE_INTRIN_H_ #include "marisa/base.h" #if defined(__x86_64__) || defined(_M_X64) #define MARISA_X64 #elif defined(__i386__) || defined(_M_IX86) #define MARISA_X86 #else // defined(__i386__) || defined(_M_IX86) #ifdef MARISA_USE_BMI2 #undef MARISA_USE_BMI2 #endif // MARISA_USE_BMI2 #ifdef MARISA_USE_BMI #undef MARISA_USE_BMI #endif // MARISA_USE_BMI #ifdef MARISA_USE_POPCNT #undef MARISA_USE_POPCNT #endif // MARISA_USE_POPCNT #ifdef MARISA_USE_SSE4A #undef MARISA_USE_SSE4A #endif // MARISA_USE_SSE4A #ifdef MARISA_USE_SSE4 #undef MARISA_USE_SSE4 #endif // MARISA_USE_SSE4 #ifdef MARISA_USE_SSE4_2 #undef MARISA_USE_SSE4_2 #endif // MARISA_USE_SSE4_2 #ifdef MARISA_USE_SSE4_1 #undef MARISA_USE_SSE4_1 #endif // MARISA_USE_SSE4_1 #ifdef MARISA_USE_SSSE3 #undef MARISA_USE_SSSE3 #endif // MARISA_USE_SSSE3 #ifdef MARISA_USE_SSE3 #undef MARISA_USE_SSE3 #endif // MARISA_USE_SSE3 #ifdef MARISA_USE_SSE2 #undef MARISA_USE_SSE2 #endif // MARISA_USE_SSE2 #endif // defined(__i386__) || defined(_M_IX86) #ifdef MARISA_USE_BMI2 #ifndef MARISA_USE_BMI #define MARISA_USE_BMI #endif // MARISA_USE_BMI #ifdef _MSC_VER #include <immintrin.h> #else // _MSC_VER #include <x86intrin.h> #endif // _MSC_VER #endif // MARISA_USE_BMI2 #ifdef MARISA_USE_BMI #ifndef MARISA_USE_SSE4 #define MARISA_USE_SSE4 #endif // MARISA_USE_SSE4 #endif // MARISA_USE_BMI #ifdef MARISA_USE_SSE4A #ifndef MARISA_USE_SSE3 #define MARISA_USE_SSE3 #endif // MARISA_USE_SSE3 #ifndef MARISA_USE_POPCNT #define MARISA_USE_POPCNT #endif // MARISA_USE_POPCNT #endif // MARISA_USE_SSE4A #ifdef MARISA_USE_SSE4 #ifndef MARISA_USE_SSE4_2 #define MARISA_USE_SSE4_2 #endif // MARISA_USE_SSE4_2 #endif // MARISA_USE_SSE4 #ifdef MARISA_USE_SSE4_2 #ifndef MARISA_USE_SSE4_1 #define MARISA_USE_SSE4_1 #endif // MARISA_USE_SSE4_1 #ifndef MARISA_USE_POPCNT #define MARISA_USE_POPCNT #endif // MARISA_USE_POPCNT #endif // MARISA_USE_SSE4_2 #ifdef MARISA_USE_SSE4_1 #ifndef MARISA_USE_SSSE3 #define MARISA_USE_SSSE3 #endif // MARISA_USE_SSSE3 #endif // MARISA_USE_SSE4_1 #ifdef MARISA_USE_POPCNT #ifndef MARISA_USE_SSE3 #define MARISA_USE_SSE3 #endif // MARISA_USE_SSE3 #ifdef _MSC_VER #include <intrin.h> #else // _MSC_VER #include <popcntintrin.h> #endif // _MSC_VER #endif // MARISA_USE_POPCNT #ifdef MARISA_USE_SSSE3 #ifndef MARISA_USE_SSE3 #define MARISA_USE_SSE3 #endif // MARISA_USE_SSE3 #ifdef MARISA_X64 #define MARISA_X64_SSSE3 #else // MARISA_X64 #define MARISA_X86_SSSE3 #endif // MAIRSA_X64 #include <tmmintrin.h> #endif // MARISA_USE_SSSE3 #ifdef MARISA_USE_SSE3 #ifndef MARISA_USE_SSE2 #define MARISA_USE_SSE2 #endif // MARISA_USE_SSE2 #endif // MARISA_USE_SSE3 #ifdef MARISA_USE_SSE2 #ifdef MARISA_X64 #define MARISA_X64_SSE2 #else // MARISA_X64 #define MARISA_X86_SSE2 #endif // MAIRSA_X64 #include <emmintrin.h> #endif // MARISA_USE_SSE2 #ifdef _MSC_VER #if MARISA_WORD_SIZE == 64 #include <intrin.h> #pragma intrinsic(_BitScanForward64) #else // MARISA_WORD_SIZE == 64 #include <intrin.h> #pragma intrinsic(_BitScanForward) #endif // MARISA_WORD_SIZE == 64 #endif // _MSC_VER #endif // MARISA_GRIMOIRE_INTRIN_H_
3,317
22.870504
48
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/algorithm/sort.h
#ifndef MARISA_GRIMOIRE_ALGORITHM_SORT_H_ #define MARISA_GRIMOIRE_ALGORITHM_SORT_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace algorithm { namespace details { enum { MARISA_INSERTION_SORT_THRESHOLD = 10 }; template <typename T> int get_label(const T &unit, std::size_t depth) { MARISA_DEBUG_IF(depth > unit.length(), MARISA_BOUND_ERROR); return (depth < unit.length()) ? (int)(UInt8)unit[depth] : -1; } template <typename T> int median(const T &a, const T &b, const T &c, std::size_t depth) { const int x = get_label(a, depth); const int y = get_label(b, depth); const int z = get_label(c, depth); if (x < y) { if (y < z) { return y; } else if (x < z) { return z; } return x; } else if (x < z) { return x; } else if (y < z) { return z; } return y; } template <typename T> int compare(const T &lhs, const T &rhs, std::size_t depth) { for (std::size_t i = depth; i < lhs.length(); ++i) { if (i == rhs.length()) { return 1; } if (lhs[i] != rhs[i]) { return (UInt8)lhs[i] - (UInt8)rhs[i]; } } if (lhs.length() == rhs.length()) { return 0; } return (lhs.length() < rhs.length()) ? -1 : 1; } template <typename Iterator> std::size_t insertion_sort(Iterator l, Iterator r, std::size_t depth) { MARISA_DEBUG_IF(l > r, MARISA_BOUND_ERROR); std::size_t count = 1; for (Iterator i = l + 1; i < r; ++i) { int result = 0; for (Iterator j = i; j > l; --j) { result = compare(*(j - 1), *j, depth); if (result <= 0) { break; } marisa::swap(*(j - 1), *j); } if (result != 0) { ++count; } } return count; } template <typename Iterator> std::size_t sort(Iterator l, Iterator r, std::size_t depth) { MARISA_DEBUG_IF(l > r, MARISA_BOUND_ERROR); std::size_t count = 0; while ((r - l) > MARISA_INSERTION_SORT_THRESHOLD) { Iterator pl = l; Iterator pr = r; Iterator pivot_l = l; Iterator pivot_r = r; const int pivot = median(*l, *(l + (r - l) / 2), *(r - 1), depth); for ( ; ; ) { while (pl < pr) { const int label = get_label(*pl, depth); if (label > pivot) { break; } else if (label == pivot) { marisa::swap(*pl, *pivot_l); ++pivot_l; } ++pl; } while (pl < pr) { const int label = get_label(*--pr, depth); if (label < pivot) { break; } else if (label == pivot) { marisa::swap(*pr, *--pivot_r); } } if (pl >= pr) { break; } marisa::swap(*pl, *pr); ++pl; } while (pivot_l > l) { marisa::swap(*--pivot_l, *--pl); } while (pivot_r < r) { marisa::swap(*pivot_r, *pr); ++pivot_r; ++pr; } if (((pl - l) > (pr - pl)) || ((r - pr) > (pr - pl))) { if ((pr - pl) == 1) { ++count; } else if ((pr - pl) > 1) { if (pivot == -1) { ++count; } else { count += sort(pl, pr, depth + 1); } } if ((pl - l) < (r - pr)) { if ((pl - l) == 1) { ++count; } else if ((pl - l) > 1) { count += sort(l, pl, depth); } l = pr; } else { if ((r - pr) == 1) { ++count; } else if ((r - pr) > 1) { count += sort(pr, r, depth); } r = pl; } } else { if ((pl - l) == 1) { ++count; } else if ((pl - l) > 1) { count += sort(l, pl, depth); } if ((r - pr) == 1) { ++count; } else if ((r - pr) > 1) { count += sort(pr, r, depth); } l = pl, r = pr; if ((pr - pl) == 1) { ++count; } else if ((pr - pl) > 1) { if (pivot == -1) { l = r; ++count; } else { ++depth; } } } } if ((r - l) > 1) { count += insertion_sort(l, r, depth); } return count; } } // namespace details template <typename Iterator> std::size_t sort(Iterator begin, Iterator end) { MARISA_DEBUG_IF(begin > end, MARISA_BOUND_ERROR); return details::sort(begin, end, 0); }; } // namespace algorithm } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_ALGORITHM_SORT_H_
4,335
21.010152
71
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/io/mapper.h
#ifndef MARISA_GRIMOIRE_IO_MAPPER_H_ #define MARISA_GRIMOIRE_IO_MAPPER_H_ #include <cstdio> #include "marisa/base.h" namespace marisa { namespace grimoire { namespace io { class Mapper { public: Mapper(); ~Mapper(); void open(const char *filename); void open(const void *ptr, std::size_t size); template <typename T> void map(T *obj) { MARISA_THROW_IF(obj == NULL, MARISA_NULL_ERROR); *obj = *static_cast<const T *>(map_data(sizeof(T))); } template <typename T> void map(const T **objs, std::size_t num_objs) { MARISA_THROW_IF((objs == NULL) && (num_objs != 0), MARISA_NULL_ERROR); MARISA_THROW_IF(num_objs > (MARISA_SIZE_MAX / sizeof(T)), MARISA_SIZE_ERROR); *objs = static_cast<const T *>(map_data(sizeof(T) * num_objs)); } void seek(std::size_t size); bool is_open() const; void clear(); void swap(Mapper &rhs); private: const void *ptr_; void *origin_; std::size_t avail_; std::size_t size_; #if (defined _WIN32) || (defined _WIN64) void *file_; void *map_; #else // (defined _WIN32) || (defined _WIN64) int fd_; #endif // (defined _WIN32) || (defined _WIN64) void open_(const char *filename); void open_(const void *ptr, std::size_t size); const void *map_data(std::size_t size); // Disallows copy and assignment. Mapper(const Mapper &); Mapper &operator=(const Mapper &); }; } // namespace io } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_IO_MAPPER_H_
1,490
20.926471
74
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/cache.h
#ifndef MARISA_GRIMOIRE_TRIE_CACHE_H_ #define MARISA_GRIMOIRE_TRIE_CACHE_H_ #include <cfloat> #include "marisa/base.h" namespace marisa { namespace grimoire { namespace trie { class Cache { public: Cache() : parent_(0), child_(0), union_() { union_.weight = FLT_MIN; } Cache(const Cache &cache) : parent_(cache.parent_), child_(cache.child_), union_(cache.union_) {} Cache &operator=(const Cache &cache) { parent_ = cache.parent_; child_ = cache.child_; union_ = cache.union_; return *this; } void set_parent(std::size_t parent) { MARISA_DEBUG_IF(parent > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); parent_ = (UInt32)parent; } void set_child(std::size_t child) { MARISA_DEBUG_IF(child > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); child_ = (UInt32)child; } void set_base(UInt8 base) { union_.link = (union_.link & ~0xFFU) | base; } void set_extra(std::size_t extra) { MARISA_DEBUG_IF(extra > (MARISA_UINT32_MAX >> 8), MARISA_SIZE_ERROR); union_.link = (UInt32)((union_.link & 0xFFU) | (extra << 8)); } void set_weight(float weight) { union_.weight = weight; } std::size_t parent() const { return parent_; } std::size_t child() const { return child_; } UInt8 base() const { return (UInt8)(union_.link & 0xFFU); } std::size_t extra() const { return union_.link >> 8; } char label() const { return (char)base(); } std::size_t link() const { return union_.link; } float weight() const { return union_.weight; } private: UInt32 parent_; UInt32 child_; union Union { UInt32 link; float weight; } union_; }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_CACHE_H_
1,774
20.646341
77
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/config.h
#ifndef MARISA_GRIMOIRE_TRIE_CONFIG_H_ #define MARISA_GRIMOIRE_TRIE_CONFIG_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace trie { class Config { public: Config() : num_tries_(MARISA_DEFAULT_NUM_TRIES), cache_level_(MARISA_DEFAULT_CACHE), tail_mode_(MARISA_DEFAULT_TAIL), node_order_(MARISA_DEFAULT_ORDER) {} void parse(int config_flags) { Config temp; temp.parse_(config_flags); swap(temp); } int flags() const { return (int)num_tries_ | tail_mode_ | node_order_; } std::size_t num_tries() const { return num_tries_; } CacheLevel cache_level() const { return cache_level_; } TailMode tail_mode() const { return tail_mode_; } NodeOrder node_order() const { return node_order_; } void clear() { Config().swap(*this); } void swap(Config &rhs) { marisa::swap(num_tries_, rhs.num_tries_); marisa::swap(cache_level_, rhs.cache_level_); marisa::swap(tail_mode_, rhs.tail_mode_); marisa::swap(node_order_, rhs.node_order_); } private: std::size_t num_tries_; CacheLevel cache_level_; TailMode tail_mode_; NodeOrder node_order_; void parse_(int config_flags) { MARISA_THROW_IF((config_flags & ~MARISA_CONFIG_MASK) != 0, MARISA_CODE_ERROR); parse_num_tries(config_flags); parse_cache_level(config_flags); parse_tail_mode(config_flags); parse_node_order(config_flags); } void parse_num_tries(int config_flags) { const int num_tries = config_flags & MARISA_NUM_TRIES_MASK; if (num_tries != 0) { num_tries_ = static_cast<std::size_t>(num_tries); } } void parse_cache_level(int config_flags) { switch (config_flags & MARISA_CACHE_LEVEL_MASK) { case 0: { cache_level_ = MARISA_DEFAULT_CACHE; break; } case MARISA_HUGE_CACHE: { cache_level_ = MARISA_HUGE_CACHE; break; } case MARISA_LARGE_CACHE: { cache_level_ = MARISA_LARGE_CACHE; break; } case MARISA_NORMAL_CACHE: { cache_level_ = MARISA_NORMAL_CACHE; break; } case MARISA_SMALL_CACHE: { cache_level_ = MARISA_SMALL_CACHE; break; } case MARISA_TINY_CACHE: { cache_level_ = MARISA_TINY_CACHE; break; } default: { MARISA_THROW(MARISA_CODE_ERROR, "undefined cache level"); } } } void parse_tail_mode(int config_flags) { switch (config_flags & MARISA_TAIL_MODE_MASK) { case 0: { tail_mode_ = MARISA_DEFAULT_TAIL; break; } case MARISA_TEXT_TAIL: { tail_mode_ = MARISA_TEXT_TAIL; break; } case MARISA_BINARY_TAIL: { tail_mode_ = MARISA_BINARY_TAIL; break; } default: { MARISA_THROW(MARISA_CODE_ERROR, "undefined tail mode"); } } } void parse_node_order(int config_flags) { switch (config_flags & MARISA_NODE_ORDER_MASK) { case 0: { node_order_ = MARISA_DEFAULT_ORDER; break; } case MARISA_LABEL_ORDER: { node_order_ = MARISA_LABEL_ORDER; break; } case MARISA_WEIGHT_ORDER: { node_order_ = MARISA_WEIGHT_ORDER; break; } default: { MARISA_THROW(MARISA_CODE_ERROR, "undefined node order"); } } } // Disallows copy and assignment. Config(const Config &); Config &operator=(const Config &); }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_CONFIG_H_
3,597
22.064103
65
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/entry.h
#ifndef MARISA_GRIMOIRE_TRIE_ENTRY_H_ #define MARISA_GRIMOIRE_TRIE_ENTRY_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace trie { class Entry { public: Entry() : ptr_(NULL), length_(0), id_(0) {} Entry(const Entry &entry) : ptr_(entry.ptr_), length_(entry.length_), id_(entry.id_) {} Entry &operator=(const Entry &entry) { ptr_ = entry.ptr_; length_ = entry.length_; id_ = entry.id_; return *this; } char operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= length_, MARISA_BOUND_ERROR); return *(ptr_ - i); } void set_str(const char *ptr, std::size_t length) { MARISA_DEBUG_IF((ptr == NULL) && (length != 0), MARISA_NULL_ERROR); MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); ptr_ = ptr + length - 1; length_ = (UInt32)length; } void set_id(std::size_t id) { MARISA_DEBUG_IF(id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); id_ = (UInt32)id; } const char *ptr() const { return ptr_ - length_ + 1; } std::size_t length() const { return length_; } std::size_t id() const { return id_; } class StringComparer { public: bool operator()(const Entry &lhs, const Entry &rhs) const { for (std::size_t i = 0; i < lhs.length(); ++i) { if (i == rhs.length()) { return true; } if (lhs[i] != rhs[i]) { return (UInt8)lhs[i] > (UInt8)rhs[i]; } } return lhs.length() > rhs.length(); } }; class IDComparer { public: bool operator()(const Entry &lhs, const Entry &rhs) const { return lhs.id_ < rhs.id_; } }; private: const char *ptr_; UInt32 length_; UInt32 id_; }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_ENTRY_H_
1,825
21.268293
71
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/history.h
#ifndef MARISA_GRIMOIRE_TRIE_STATE_HISTORY_H_ #define MARISA_GRIMOIRE_TRIE_STATE_HISTORY_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace trie { class History { public: History() : node_id_(0), louds_pos_(0), key_pos_(0), link_id_(MARISA_INVALID_LINK_ID), key_id_(MARISA_INVALID_KEY_ID) {} void set_node_id(std::size_t node_id) { MARISA_DEBUG_IF(node_id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); node_id_ = (UInt32)node_id; } void set_louds_pos(std::size_t louds_pos) { MARISA_DEBUG_IF(louds_pos > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); louds_pos_ = (UInt32)louds_pos; } void set_key_pos(std::size_t key_pos) { MARISA_DEBUG_IF(key_pos > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); key_pos_ = (UInt32)key_pos; } void set_link_id(std::size_t link_id) { MARISA_DEBUG_IF(link_id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); link_id_ = (UInt32)link_id; } void set_key_id(std::size_t key_id) { MARISA_DEBUG_IF(key_id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); key_id_ = (UInt32)key_id; } std::size_t node_id() const { return node_id_; } std::size_t louds_pos() const { return louds_pos_; } std::size_t key_pos() const { return key_pos_; } std::size_t link_id() const { return link_id_; } std::size_t key_id() const { return key_id_; } private: UInt32 node_id_; UInt32 louds_pos_; UInt32 key_pos_; UInt32 link_id_; UInt32 key_id_; }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_STATE_HISTORY_H_
1,598
23.227273
75
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/key.h
#ifndef MARISA_GRIMOIRE_TRIE_KEY_H_ #define MARISA_GRIMOIRE_TRIE_KEY_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace trie { class Key { public: Key() : ptr_(NULL), length_(0), union_(), id_(0) { union_.terminal = 0; } Key(const Key &entry) : ptr_(entry.ptr_), length_(entry.length_), union_(entry.union_), id_(entry.id_) {} Key &operator=(const Key &entry) { ptr_ = entry.ptr_; length_ = entry.length_; union_ = entry.union_; id_ = entry.id_; return *this; } char operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= length_, MARISA_BOUND_ERROR); return ptr_[i]; } void substr(std::size_t pos, std::size_t length) { MARISA_DEBUG_IF(pos > length_, MARISA_BOUND_ERROR); MARISA_DEBUG_IF(length > length_, MARISA_BOUND_ERROR); MARISA_DEBUG_IF(pos > (length_ - length), MARISA_BOUND_ERROR); ptr_ += pos; length_ = (UInt32)length; } void set_str(const char *ptr, std::size_t length) { MARISA_DEBUG_IF((ptr == NULL) && (length != 0), MARISA_NULL_ERROR); MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); ptr_ = ptr; length_ = (UInt32)length; } void set_weight(float weight) { union_.weight = weight; } void set_terminal(std::size_t terminal) { MARISA_DEBUG_IF(terminal > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); union_.terminal = (UInt32)terminal; } void set_id(std::size_t id) { MARISA_DEBUG_IF(id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); id_ = (UInt32)id; } const char *ptr() const { return ptr_; } std::size_t length() const { return length_; } float weight() const { return union_.weight; } std::size_t terminal() const { return union_.terminal; } std::size_t id() const { return id_; } private: const char *ptr_; UInt32 length_; union Union { float weight; UInt32 terminal; } union_; UInt32 id_; }; inline bool operator==(const Key &lhs, const Key &rhs) { if (lhs.length() != rhs.length()) { return false; } for (std::size_t i = 0; i < lhs.length(); ++i) { if (lhs[i] != rhs[i]) { return false; } } return true; } inline bool operator!=(const Key &lhs, const Key &rhs) { return !(lhs == rhs); } inline bool operator<(const Key &lhs, const Key &rhs) { for (std::size_t i = 0; i < lhs.length(); ++i) { if (i == rhs.length()) { return false; } if (lhs[i] != rhs[i]) { return (UInt8)lhs[i] < (UInt8)rhs[i]; } } return lhs.length() < rhs.length(); } inline bool operator>(const Key &lhs, const Key &rhs) { return rhs < lhs; } class ReverseKey { public: ReverseKey() : ptr_(NULL), length_(0), union_(), id_(0) { union_.terminal = 0; } ReverseKey(const ReverseKey &entry) : ptr_(entry.ptr_), length_(entry.length_), union_(entry.union_), id_(entry.id_) {} ReverseKey &operator=(const ReverseKey &entry) { ptr_ = entry.ptr_; length_ = entry.length_; union_ = entry.union_; id_ = entry.id_; return *this; } char operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= length_, MARISA_BOUND_ERROR); return *(ptr_ - i - 1); } void substr(std::size_t pos, std::size_t length) { MARISA_DEBUG_IF(pos > length_, MARISA_BOUND_ERROR); MARISA_DEBUG_IF(length > length_, MARISA_BOUND_ERROR); MARISA_DEBUG_IF(pos > (length_ - length), MARISA_BOUND_ERROR); ptr_ -= pos; length_ = (UInt32)length; } void set_str(const char *ptr, std::size_t length) { MARISA_DEBUG_IF((ptr == NULL) && (length != 0), MARISA_NULL_ERROR); MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); ptr_ = ptr + length; length_ = (UInt32)length; } void set_weight(float weight) { union_.weight = weight; } void set_terminal(std::size_t terminal) { MARISA_DEBUG_IF(terminal > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); union_.terminal = (UInt32)terminal; } void set_id(std::size_t id) { MARISA_DEBUG_IF(id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); id_ = (UInt32)id; } const char *ptr() const { return ptr_ - length_; } std::size_t length() const { return length_; } float weight() const { return union_.weight; } std::size_t terminal() const { return union_.terminal; } std::size_t id() const { return id_; } private: const char *ptr_; UInt32 length_; union Union { float weight; UInt32 terminal; } union_; UInt32 id_; }; inline bool operator==(const ReverseKey &lhs, const ReverseKey &rhs) { if (lhs.length() != rhs.length()) { return false; } for (std::size_t i = 0; i < lhs.length(); ++i) { if (lhs[i] != rhs[i]) { return false; } } return true; } inline bool operator!=(const ReverseKey &lhs, const ReverseKey &rhs) { return !(lhs == rhs); } inline bool operator<(const ReverseKey &lhs, const ReverseKey &rhs) { for (std::size_t i = 0; i < lhs.length(); ++i) { if (i == rhs.length()) { return false; } if (lhs[i] != rhs[i]) { return (UInt8)lhs[i] < (UInt8)rhs[i]; } } return lhs.length() < rhs.length(); } inline bool operator>(const ReverseKey &lhs, const ReverseKey &rhs) { return rhs < lhs; } } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_KEY_H_
5,355
22.594714
71
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/louds-trie.h
#ifndef MARISA_GRIMOIRE_TRIE_LOUDS_TRIE_H_ #define MARISA_GRIMOIRE_TRIE_LOUDS_TRIE_H_ #include "marisa/keyset.h" #include "marisa/agent.h" #include "marisa/grimoire/vector.h" #include "marisa/grimoire/trie/config.h" #include "marisa/grimoire/trie/key.h" #include "marisa/grimoire/trie/tail.h" #include "marisa/grimoire/trie/cache.h" namespace marisa { namespace grimoire { namespace trie { class LoudsTrie { public: LoudsTrie(); ~LoudsTrie(); void build(Keyset &keyset, int flags); void map(Mapper &mapper); void read(Reader &reader); void write(Writer &writer) const; bool lookup(Agent &agent) const; void reverse_lookup(Agent &agent) const; bool common_prefix_search(Agent &agent) const; bool predictive_search(Agent &agent) const; std::size_t num_tries() const { return config_.num_tries(); } std::size_t num_keys() const { return size(); } std::size_t num_nodes() const { return (louds_.size() / 2) - 1; } CacheLevel cache_level() const { return config_.cache_level(); } TailMode tail_mode() const { return config_.tail_mode(); } NodeOrder node_order() const { return config_.node_order(); } bool empty() const { return size() == 0; } std::size_t size() const { return terminal_flags_.num_1s(); } std::size_t total_size() const; std::size_t io_size() const; void clear(); void swap(LoudsTrie &rhs); private: BitVector louds_; BitVector terminal_flags_; BitVector link_flags_; Vector<UInt8> bases_; FlatVector extras_; Tail tail_; scoped_ptr<LoudsTrie> next_trie_; Vector<Cache> cache_; std::size_t cache_mask_; std::size_t num_l1_nodes_; Config config_; Mapper mapper_; void build_(Keyset &keyset, const Config &config); template <typename T> void build_trie(Vector<T> &keys, Vector<UInt32> *terminals, const Config &config, std::size_t trie_id); template <typename T> void build_current_trie(Vector<T> &keys, Vector<UInt32> *terminals, const Config &config, std::size_t trie_id); template <typename T> void build_next_trie(Vector<T> &keys, Vector<UInt32> *terminals, const Config &config, std::size_t trie_id); template <typename T> void build_terminals(const Vector<T> &keys, Vector<UInt32> *terminals) const; void reserve_cache(const Config &config, std::size_t trie_id, std::size_t num_keys); template <typename T> void cache(std::size_t parent, std::size_t child, float weight, char label); void fill_cache(); void map_(Mapper &mapper); void read_(Reader &reader); void write_(Writer &writer) const; inline bool find_child(Agent &agent) const; inline bool predictive_find_child(Agent &agent) const; inline void restore(Agent &agent, std::size_t node_id) const; inline bool match(Agent &agent, std::size_t node_id) const; inline bool prefix_match(Agent &agent, std::size_t node_id) const; void restore_(Agent &agent, std::size_t node_id) const; bool match_(Agent &agent, std::size_t node_id) const; bool prefix_match_(Agent &agent, std::size_t node_id) const; inline std::size_t get_cache_id(std::size_t node_id, char label) const; inline std::size_t get_cache_id(std::size_t node_id) const; inline std::size_t get_link(std::size_t node_id) const; inline std::size_t get_link(std::size_t node_id, std::size_t link_id) const; inline std::size_t update_link_id(std::size_t link_id, std::size_t node_id) const; // Disallows copy and assignment. LoudsTrie(const LoudsTrie &); LoudsTrie &operator=(const LoudsTrie &); }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_LOUDS_TRIE_H_
3,694
26.37037
76
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/range.h
#ifndef MARISA_GRIMOIRE_TRIE_RANGE_H_ #define MARISA_GRIMOIRE_TRIE_RANGE_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace trie { class Range { public: Range() : begin_(0), end_(0), key_pos_(0) {} void set_begin(std::size_t begin) { MARISA_DEBUG_IF(begin > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); begin_ = static_cast<UInt32>(begin); } void set_end(std::size_t end) { MARISA_DEBUG_IF(end > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); end_ = static_cast<UInt32>(end); } void set_key_pos(std::size_t key_pos) { MARISA_DEBUG_IF(key_pos > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); key_pos_ = static_cast<UInt32>(key_pos); } std::size_t begin() const { return begin_; } std::size_t end() const { return end_; } std::size_t key_pos() const { return key_pos_; } private: UInt32 begin_; UInt32 end_; UInt32 key_pos_; }; inline Range make_range(std::size_t begin, std::size_t end, std::size_t key_pos) { Range range; range.set_begin(begin); range.set_end(end); range.set_key_pos(key_pos); return range; } class WeightedRange { public: WeightedRange() : range_(), weight_(0.0F) {} void set_range(const Range &range) { range_ = range; } void set_begin(std::size_t begin) { range_.set_begin(begin); } void set_end(std::size_t end) { range_.set_end(end); } void set_key_pos(std::size_t key_pos) { range_.set_key_pos(key_pos); } void set_weight(float weight) { weight_ = weight; } const Range &range() const { return range_; } std::size_t begin() const { return range_.begin(); } std::size_t end() const { return range_.end(); } std::size_t key_pos() const { return range_.key_pos(); } float weight() const { return weight_; } private: Range range_; float weight_; }; inline bool operator<(const WeightedRange &lhs, const WeightedRange &rhs) { return lhs.weight() < rhs.weight(); } inline bool operator>(const WeightedRange &lhs, const WeightedRange &rhs) { return lhs.weight() > rhs.weight(); } inline WeightedRange make_weighted_range(std::size_t begin, std::size_t end, std::size_t key_pos, float weight) { WeightedRange range; range.set_begin(begin); range.set_end(end); range.set_key_pos(key_pos); range.set_weight(weight); return range; } } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_RANGE_H_
2,468
20.284483
76
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/state.h
#ifndef MARISA_GRIMOIRE_TRIE_STATE_H_ #define MARISA_GRIMOIRE_TRIE_STATE_H_ #include "marisa/grimoire/vector.h" #include "marisa/grimoire/trie/history.h" namespace marisa { namespace grimoire { namespace trie { // A search agent has its internal state and the status codes are defined // below. typedef enum StatusCode { MARISA_READY_TO_ALL, MARISA_READY_TO_COMMON_PREFIX_SEARCH, MARISA_READY_TO_PREDICTIVE_SEARCH, MARISA_END_OF_COMMON_PREFIX_SEARCH, MARISA_END_OF_PREDICTIVE_SEARCH, } StatusCode; class State { public: State() : key_buf_(), history_(), node_id_(0), query_pos_(0), history_pos_(0), status_code_(MARISA_READY_TO_ALL) {} void set_node_id(std::size_t node_id) { MARISA_DEBUG_IF(node_id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); node_id_ = (UInt32)node_id; } void set_query_pos(std::size_t query_pos) { MARISA_DEBUG_IF(query_pos > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); query_pos_ = (UInt32)query_pos; } void set_history_pos(std::size_t history_pos) { MARISA_DEBUG_IF(history_pos > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); history_pos_ = (UInt32)history_pos; } void set_status_code(StatusCode status_code) { status_code_ = status_code; } std::size_t node_id() const { return node_id_; } std::size_t query_pos() const { return query_pos_; } std::size_t history_pos() const { return history_pos_; } StatusCode status_code() const { return status_code_; } const Vector<char> &key_buf() const { return key_buf_; } const Vector<History> &history() const { return history_; } Vector<char> &key_buf() { return key_buf_; } Vector<History> &history() { return history_; } void reset() { status_code_ = MARISA_READY_TO_ALL; } void lookup_init() { node_id_ = 0; query_pos_ = 0; status_code_ = MARISA_READY_TO_ALL; } void reverse_lookup_init() { key_buf_.resize(0); key_buf_.reserve(32); status_code_ = MARISA_READY_TO_ALL; } void common_prefix_search_init() { node_id_ = 0; query_pos_ = 0; status_code_ = MARISA_READY_TO_COMMON_PREFIX_SEARCH; } void predictive_search_init() { key_buf_.resize(0); key_buf_.reserve(64); history_.resize(0); history_.reserve(4); node_id_ = 0; query_pos_ = 0; history_pos_ = 0; status_code_ = MARISA_READY_TO_PREDICTIVE_SEARCH; } private: Vector<char> key_buf_; Vector<History> history_; UInt32 node_id_; UInt32 query_pos_; UInt32 history_pos_; StatusCode status_code_; // Disallows copy and assignment. State(const State &); State &operator=(const State &); }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_STATE_H_
2,761
22.40678
73
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/trie/tail.h
#ifndef MARISA_GRIMOIRE_TRIE_TAIL_H_ #define MARISA_GRIMOIRE_TRIE_TAIL_H_ #include "marisa/agent.h" #include "marisa/grimoire/vector.h" #include "marisa/grimoire/trie/entry.h" namespace marisa { namespace grimoire { namespace trie { class Tail { public: Tail(); void build(Vector<Entry> &entries, Vector<UInt32> *offsets, TailMode mode); void map(Mapper &mapper); void read(Reader &reader); void write(Writer &writer) const; void restore(Agent &agent, std::size_t offset) const; bool match(Agent &agent, std::size_t offset) const; bool prefix_match(Agent &agent, std::size_t offset) const; const char &operator[](std::size_t offset) const { MARISA_DEBUG_IF(offset >= buf_.size(), MARISA_BOUND_ERROR); return buf_[offset]; } TailMode mode() const { return end_flags_.empty() ? MARISA_TEXT_TAIL : MARISA_BINARY_TAIL; } bool empty() const { return buf_.empty(); } std::size_t size() const { return buf_.size(); } std::size_t total_size() const { return buf_.total_size() + end_flags_.total_size(); } std::size_t io_size() const { return buf_.io_size() + end_flags_.io_size(); } void clear(); void swap(Tail &rhs); private: Vector<char> buf_; BitVector end_flags_; void build_(Vector<Entry> &entries, Vector<UInt32> *offsets, TailMode mode); void map_(Mapper &mapper); void read_(Reader &reader); void write_(Writer &writer) const; // Disallows copy and assignment. Tail(const Tail &); Tail &operator=(const Tail &); }; } // namespace trie } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_TRIE_TAIL_H_
1,645
21.547945
70
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/vector/bit-vector.h
#ifndef MARISA_GRIMOIRE_VECTOR_BIT_VECTOR_H_ #define MARISA_GRIMOIRE_VECTOR_BIT_VECTOR_H_ #include "marisa/grimoire/vector/rank-index.h" #include "marisa/grimoire/vector/vector.h" namespace marisa { namespace grimoire { namespace vector { class BitVector { public: #if MARISA_WORD_SIZE == 64 typedef UInt64 Unit; #else // MARISA_WORD_SIZE == 64 typedef UInt32 Unit; #endif // MARISA_WORD_SIZE == 64 BitVector() : units_(), size_(0), num_1s_(0), ranks_(), select0s_(), select1s_() {} void build(bool enables_select0, bool enables_select1) { BitVector temp; temp.build_index(*this, enables_select0, enables_select1); units_.shrink(); temp.units_.swap(units_); swap(temp); } void map(Mapper &mapper) { BitVector temp; temp.map_(mapper); swap(temp); } void read(Reader &reader) { BitVector temp; temp.read_(reader); swap(temp); } void write(Writer &writer) const { write_(writer); } void disable_select0() { select0s_.clear(); } void disable_select1() { select1s_.clear(); } void push_back(bool bit) { MARISA_THROW_IF(size_ == MARISA_UINT32_MAX, MARISA_SIZE_ERROR); if (size_ == (MARISA_WORD_SIZE * units_.size())) { units_.resize(units_.size() + (64 / MARISA_WORD_SIZE), 0); } if (bit) { units_[size_ / MARISA_WORD_SIZE] |= (Unit)1 << (size_ % MARISA_WORD_SIZE); ++num_1s_; } ++size_; } bool operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); return (units_[i / MARISA_WORD_SIZE] & ((Unit)1 << (i % MARISA_WORD_SIZE))) != 0; } std::size_t rank0(std::size_t i) const { MARISA_DEBUG_IF(ranks_.empty(), MARISA_STATE_ERROR); MARISA_DEBUG_IF(i > size_, MARISA_BOUND_ERROR); return i - rank1(i); } std::size_t rank1(std::size_t i) const; std::size_t select0(std::size_t i) const; std::size_t select1(std::size_t i) const; std::size_t num_0s() const { return size_ - num_1s_; } std::size_t num_1s() const { return num_1s_; } bool empty() const { return size_ == 0; } std::size_t size() const { return size_; } std::size_t total_size() const { return units_.total_size() + ranks_.total_size() + select0s_.total_size() + select1s_.total_size(); } std::size_t io_size() const { return units_.io_size() + (sizeof(UInt32) * 2) + ranks_.io_size() + select0s_.io_size() + select1s_.io_size(); } void clear() { BitVector().swap(*this); } void swap(BitVector &rhs) { units_.swap(rhs.units_); marisa::swap(size_, rhs.size_); marisa::swap(num_1s_, rhs.num_1s_); ranks_.swap(rhs.ranks_); select0s_.swap(rhs.select0s_); select1s_.swap(rhs.select1s_); } private: Vector<Unit> units_; std::size_t size_; std::size_t num_1s_; Vector<RankIndex> ranks_; Vector<UInt32> select0s_; Vector<UInt32> select1s_; void build_index(const BitVector &bv, bool enables_select0, bool enables_select1); void map_(Mapper &mapper) { units_.map(mapper); { UInt32 temp_size; mapper.map(&temp_size); size_ = temp_size; } { UInt32 temp_num_1s; mapper.map(&temp_num_1s); MARISA_THROW_IF(temp_num_1s > size_, MARISA_FORMAT_ERROR); num_1s_ = temp_num_1s; } ranks_.map(mapper); select0s_.map(mapper); select1s_.map(mapper); } void read_(Reader &reader) { units_.read(reader); { UInt32 temp_size; reader.read(&temp_size); size_ = temp_size; } { UInt32 temp_num_1s; reader.read(&temp_num_1s); MARISA_THROW_IF(temp_num_1s > size_, MARISA_FORMAT_ERROR); num_1s_ = temp_num_1s; } ranks_.read(reader); select0s_.read(reader); select1s_.read(reader); } void write_(Writer &writer) const { units_.write(writer); writer.write((UInt32)size_); writer.write((UInt32)num_1s_); ranks_.write(writer); select0s_.write(writer); select1s_.write(writer); } // Disallows copy and assignment. BitVector(const BitVector &); BitVector &operator=(const BitVector &); }; } // namespace vector } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_VECTOR_BIT_VECTOR_H_
4,271
22.733333
77
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/vector/flat-vector.h
#ifndef MARISA_GRIMOIRE_VECTOR_FLAT_VECTOR_H_ #define MARISA_GRIMOIRE_VECTOR_FLAT_VECTOR_H_ #include "marisa/grimoire/vector/vector.h" namespace marisa { namespace grimoire { namespace vector { class FlatVector { public: #if MARISA_WORD_SIZE == 64 typedef UInt64 Unit; #else // MARISA_WORD_SIZE == 64 typedef UInt32 Unit; #endif // MARISA_WORD_SIZE == 64 FlatVector() : units_(), value_size_(0), mask_(0), size_(0) {} void build(const Vector<UInt32> &values) { FlatVector temp; temp.build_(values); swap(temp); } void map(Mapper &mapper) { FlatVector temp; temp.map_(mapper); swap(temp); } void read(Reader &reader) { FlatVector temp; temp.read_(reader); swap(temp); } void write(Writer &writer) const { write_(writer); } UInt32 operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); const std::size_t pos = i * value_size_; const std::size_t unit_id = pos / MARISA_WORD_SIZE; const std::size_t unit_offset = pos % MARISA_WORD_SIZE; if ((unit_offset + value_size_) <= MARISA_WORD_SIZE) { return (UInt32)(units_[unit_id] >> unit_offset) & mask_; } else { return (UInt32)((units_[unit_id] >> unit_offset) | (units_[unit_id + 1] << (MARISA_WORD_SIZE - unit_offset))) & mask_; } } std::size_t value_size() const { return value_size_; } UInt32 mask() const { return mask_; } bool empty() const { return size_ == 0; } std::size_t size() const { return size_; } std::size_t total_size() const { return units_.total_size(); } std::size_t io_size() const { return units_.io_size() + (sizeof(UInt32) * 2) + sizeof(UInt64); } void clear() { FlatVector().swap(*this); } void swap(FlatVector &rhs) { units_.swap(rhs.units_); marisa::swap(value_size_, rhs.value_size_); marisa::swap(mask_, rhs.mask_); marisa::swap(size_, rhs.size_); } private: Vector<Unit> units_; std::size_t value_size_; UInt32 mask_; std::size_t size_; void build_(const Vector<UInt32> &values) { UInt32 max_value = 0; for (std::size_t i = 0; i < values.size(); ++i) { if (values[i] > max_value) { max_value = values[i]; } } std::size_t value_size = 0; while (max_value != 0) { ++value_size; max_value >>= 1; } std::size_t num_units = values.empty() ? 0 : (64 / MARISA_WORD_SIZE); if (value_size != 0) { num_units = (std::size_t)( (((UInt64)value_size * values.size()) + (MARISA_WORD_SIZE - 1)) / MARISA_WORD_SIZE); num_units += num_units % (64 / MARISA_WORD_SIZE); } units_.resize(num_units); if (num_units > 0) { units_.back() = 0; } value_size_ = value_size; if (value_size != 0) { mask_ = MARISA_UINT32_MAX >> (32 - value_size); } size_ = values.size(); for (std::size_t i = 0; i < values.size(); ++i) { set(i, values[i]); } } void map_(Mapper &mapper) { units_.map(mapper); { UInt32 temp_value_size; mapper.map(&temp_value_size); MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR); value_size_ = temp_value_size; } { UInt32 temp_mask; mapper.map(&temp_mask); mask_ = temp_mask; } { UInt64 temp_size; mapper.map(&temp_size); MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR); size_ = (std::size_t)temp_size; } } void read_(Reader &reader) { units_.read(reader); { UInt32 temp_value_size; reader.read(&temp_value_size); MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR); value_size_ = temp_value_size; } { UInt32 temp_mask; reader.read(&temp_mask); mask_ = temp_mask; } { UInt64 temp_size; reader.read(&temp_size); MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR); size_ = (std::size_t)temp_size; } } void write_(Writer &writer) const { units_.write(writer); writer.write((UInt32)value_size_); writer.write((UInt32)mask_); writer.write((UInt64)size_); } void set(std::size_t i, UInt32 value) { MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); MARISA_DEBUG_IF(value > mask_, MARISA_RANGE_ERROR); const std::size_t pos = i * value_size_; const std::size_t unit_id = pos / MARISA_WORD_SIZE; const std::size_t unit_offset = pos % MARISA_WORD_SIZE; units_[unit_id] &= ~((Unit)mask_ << unit_offset); units_[unit_id] |= (Unit)(value & mask_) << unit_offset; if ((unit_offset + value_size_) > MARISA_WORD_SIZE) { units_[unit_id + 1] &= ~((Unit)mask_ >> (MARISA_WORD_SIZE - unit_offset)); units_[unit_id + 1] |= (Unit)(value & mask_) >> (MARISA_WORD_SIZE - unit_offset); } } // Disallows copy and assignment. FlatVector(const FlatVector &); FlatVector &operator=(const FlatVector &); }; } // namespace vector } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_VECTOR_FLAT_VECTOR_H_
5,116
23.839806
79
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/vector/pop-count.h
#ifndef MARISA_GRIMOIRE_VECTOR_POP_COUNT_H_ #define MARISA_GRIMOIRE_VECTOR_POP_COUNT_H_ #include "marisa/grimoire/intrin.h" namespace marisa { namespace grimoire { namespace vector { #if MARISA_WORD_SIZE == 64 class PopCount { public: explicit PopCount(UInt64 x) : value_() { x = (x & 0x5555555555555555ULL) + ((x & 0xAAAAAAAAAAAAAAAAULL) >> 1); x = (x & 0x3333333333333333ULL) + ((x & 0xCCCCCCCCCCCCCCCCULL) >> 2); x = (x & 0x0F0F0F0F0F0F0F0FULL) + ((x & 0xF0F0F0F0F0F0F0F0ULL) >> 4); x *= 0x0101010101010101ULL; value_ = x; } std::size_t lo8() const { return (std::size_t)(value_ & 0xFFU); } std::size_t lo16() const { return (std::size_t)((value_ >> 8) & 0xFFU); } std::size_t lo24() const { return (std::size_t)((value_ >> 16) & 0xFFU); } std::size_t lo32() const { return (std::size_t)((value_ >> 24) & 0xFFU); } std::size_t lo40() const { return (std::size_t)((value_ >> 32) & 0xFFU); } std::size_t lo48() const { return (std::size_t)((value_ >> 40) & 0xFFU); } std::size_t lo56() const { return (std::size_t)((value_ >> 48) & 0xFFU); } std::size_t lo64() const { return (std::size_t)((value_ >> 56) & 0xFFU); } static std::size_t count(UInt64 x) { #if defined(MARISA_X64) && defined(MARISA_USE_POPCNT) #ifdef _MSC_VER return __popcnt64(x); #else // _MSC_VER return static_cast<std::size_t>(_mm_popcnt_u64(x)); #endif // _MSC_VER #else // defined(MARISA_X64) && defined(MARISA_USE_POPCNT) return PopCount(x).lo64(); #endif // defined(MARISA_X64) && defined(MARISA_USE_POPCNT) } private: UInt64 value_; }; #else // MARISA_WORD_SIZE == 64 class PopCount { public: explicit PopCount(UInt32 x) : value_() { x = (x & 0x55555555U) + ((x & 0xAAAAAAAAU) >> 1); x = (x & 0x33333333U) + ((x & 0xCCCCCCCCU) >> 2); x = (x & 0x0F0F0F0FU) + ((x & 0xF0F0F0F0U) >> 4); x *= 0x01010101U; value_ = x; } std::size_t lo8() const { return value_ & 0xFFU; } std::size_t lo16() const { return (value_ >> 8) & 0xFFU; } std::size_t lo24() const { return (value_ >> 16) & 0xFFU; } std::size_t lo32() const { return (value_ >> 24) & 0xFFU; } static std::size_t count(UInt32 x) { #ifdef MARISA_USE_POPCNT #ifdef _MSC_VER return __popcnt(x); #else // _MSC_VER return _mm_popcnt_u32(x); #endif // _MSC_VER #else // MARISA_USE_POPCNT return PopCount(x).lo32(); #endif // MARISA_USE_POPCNT } private: UInt32 value_; }; #endif // MARISA_WORD_SIZE == 64 } // namespace vector } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_VECTOR_POP_COUNT_H_
2,659
22.963964
73
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/vector/rank-index.h
#ifndef MARISA_GRIMOIRE_VECTOR_RANK_INDEX_H_ #define MARISA_GRIMOIRE_VECTOR_RANK_INDEX_H_ #include "marisa/base.h" namespace marisa { namespace grimoire { namespace vector { class RankIndex { public: RankIndex() : abs_(0), rel_lo_(0), rel_hi_(0) {} void set_abs(std::size_t value) { MARISA_DEBUG_IF(value > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); abs_ = (UInt32)value; } void set_rel1(std::size_t value) { MARISA_DEBUG_IF(value > 64, MARISA_RANGE_ERROR); rel_lo_ = (UInt32)((rel_lo_ & ~0x7FU) | (value & 0x7FU)); } void set_rel2(std::size_t value) { MARISA_DEBUG_IF(value > 128, MARISA_RANGE_ERROR); rel_lo_ = (UInt32)((rel_lo_ & ~(0xFFU << 7)) | ((value & 0xFFU) << 7)); } void set_rel3(std::size_t value) { MARISA_DEBUG_IF(value > 192, MARISA_RANGE_ERROR); rel_lo_ = (UInt32)((rel_lo_ & ~(0xFFU << 15)) | ((value & 0xFFU) << 15)); } void set_rel4(std::size_t value) { MARISA_DEBUG_IF(value > 256, MARISA_RANGE_ERROR); rel_lo_ = (UInt32)((rel_lo_ & ~(0x1FFU << 23)) | ((value & 0x1FFU) << 23)); } void set_rel5(std::size_t value) { MARISA_DEBUG_IF(value > 320, MARISA_RANGE_ERROR); rel_hi_ = (UInt32)((rel_hi_ & ~0x1FFU) | (value & 0x1FFU)); } void set_rel6(std::size_t value) { MARISA_DEBUG_IF(value > 384, MARISA_RANGE_ERROR); rel_hi_ = (UInt32)((rel_hi_ & ~(0x1FFU << 9)) | ((value & 0x1FFU) << 9)); } void set_rel7(std::size_t value) { MARISA_DEBUG_IF(value > 448, MARISA_RANGE_ERROR); rel_hi_ = (UInt32)((rel_hi_ & ~(0x1FFU << 18)) | ((value & 0x1FFU) << 18)); } std::size_t abs() const { return abs_; } std::size_t rel1() const { return rel_lo_ & 0x7FU; } std::size_t rel2() const { return (rel_lo_ >> 7) & 0xFFU; } std::size_t rel3() const { return (rel_lo_ >> 15) & 0xFFU; } std::size_t rel4() const { return (rel_lo_ >> 23) & 0x1FFU; } std::size_t rel5() const { return rel_hi_ & 0x1FFU; } std::size_t rel6() const { return (rel_hi_ >> 9) & 0x1FFU; } std::size_t rel7() const { return (rel_hi_ >> 18) & 0x1FFU; } private: UInt32 abs_; UInt32 rel_lo_; UInt32 rel_hi_; }; } // namespace vector } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_VECTOR_RANK_INDEX_H_
2,276
26.433735
79
h
OpenCC
OpenCC-master/deps/marisa-0.2.6/lib/marisa/grimoire/vector/vector.h
#ifndef MARISA_GRIMOIRE_VECTOR_VECTOR_H_ #define MARISA_GRIMOIRE_VECTOR_VECTOR_H_ #include <new> #include "marisa/grimoire/io.h" namespace marisa { namespace grimoire { namespace vector { template <typename T> class Vector { public: Vector() : buf_(), objs_(NULL), const_objs_(NULL), size_(0), capacity_(0), fixed_(false) {} ~Vector() { if (objs_ != NULL) { for (std::size_t i = 0; i < size_; ++i) { objs_[i].~T(); } } } void map(Mapper &mapper) { Vector temp; temp.map_(mapper); swap(temp); } void read(Reader &reader) { Vector temp; temp.read_(reader); swap(temp); } void write(Writer &writer) const { write_(writer); } void push_back(const T &x) { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); MARISA_DEBUG_IF(size_ == max_size(), MARISA_SIZE_ERROR); reserve(size_ + 1); new (&objs_[size_]) T(x); ++size_; } void pop_back() { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); MARISA_DEBUG_IF(size_ == 0, MARISA_STATE_ERROR); objs_[--size_].~T(); } // resize() assumes that T's placement new does not throw an exception. void resize(std::size_t size) { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); reserve(size); for (std::size_t i = size_; i < size; ++i) { new (&objs_[i]) T; } for (std::size_t i = size; i < size_; ++i) { objs_[i].~T(); } size_ = size; } // resize() assumes that T's placement new does not throw an exception. void resize(std::size_t size, const T &x) { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); reserve(size); for (std::size_t i = size_; i < size; ++i) { new (&objs_[i]) T(x); } for (std::size_t i = size; i < size_; ++i) { objs_[i].~T(); } size_ = size; } void reserve(std::size_t capacity) { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); if (capacity <= capacity_) { return; } MARISA_DEBUG_IF(capacity > max_size(), MARISA_SIZE_ERROR); std::size_t new_capacity = capacity; if (capacity_ > (capacity / 2)) { if (capacity_ > (max_size() / 2)) { new_capacity = max_size(); } else { new_capacity = capacity_ * 2; } } realloc(new_capacity); } void shrink() { MARISA_THROW_IF(fixed_, MARISA_STATE_ERROR); if (size_ != capacity_) { realloc(size_); } } void fix() { MARISA_THROW_IF(fixed_, MARISA_STATE_ERROR); fixed_ = true; } const T *begin() const { return const_objs_; } const T *end() const { return const_objs_ + size_; } const T &operator[](std::size_t i) const { MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); return const_objs_[i]; } const T &front() const { MARISA_DEBUG_IF(size_ == 0, MARISA_STATE_ERROR); return const_objs_[0]; } const T &back() const { MARISA_DEBUG_IF(size_ == 0, MARISA_STATE_ERROR); return const_objs_[size_ - 1]; } T *begin() { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); return objs_; } T *end() { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); return objs_ + size_; } T &operator[](std::size_t i) { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); MARISA_DEBUG_IF(i >= size_, MARISA_BOUND_ERROR); return objs_[i]; } T &front() { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); MARISA_DEBUG_IF(size_ == 0, MARISA_STATE_ERROR); return objs_[0]; } T &back() { MARISA_DEBUG_IF(fixed_, MARISA_STATE_ERROR); MARISA_DEBUG_IF(size_ == 0, MARISA_STATE_ERROR); return objs_[size_ - 1]; } std::size_t size() const { return size_; } std::size_t capacity() const { return capacity_; } bool fixed() const { return fixed_; } bool empty() const { return size_ == 0; } std::size_t total_size() const { return sizeof(T) * size_; } std::size_t io_size() const { return sizeof(UInt64) + ((total_size() + 7) & ~(std::size_t)0x07); } void clear() { Vector().swap(*this); } void swap(Vector &rhs) { buf_.swap(rhs.buf_); marisa::swap(objs_, rhs.objs_); marisa::swap(const_objs_, rhs.const_objs_); marisa::swap(size_, rhs.size_); marisa::swap(capacity_, rhs.capacity_); marisa::swap(fixed_, rhs.fixed_); } static std::size_t max_size() { return MARISA_SIZE_MAX / sizeof(T); } private: scoped_array<char> buf_; T *objs_; const T *const_objs_; std::size_t size_; std::size_t capacity_; bool fixed_; void map_(Mapper &mapper) { UInt64 total_size; mapper.map(&total_size); MARISA_THROW_IF(total_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR); MARISA_THROW_IF((total_size % sizeof(T)) != 0, MARISA_FORMAT_ERROR); const std::size_t size = (std::size_t)(total_size / sizeof(T)); mapper.map(&const_objs_, size); mapper.seek((std::size_t)((8 - (total_size % 8)) % 8)); size_ = size; fix(); } void read_(Reader &reader) { UInt64 total_size; reader.read(&total_size); MARISA_THROW_IF(total_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR); MARISA_THROW_IF((total_size % sizeof(T)) != 0, MARISA_FORMAT_ERROR); const std::size_t size = (std::size_t)(total_size / sizeof(T)); resize(size); reader.read(objs_, size); reader.seek((std::size_t)((8 - (total_size % 8)) % 8)); } void write_(Writer &writer) const { writer.write((UInt64)total_size()); writer.write(const_objs_, size_); writer.seek((8 - (total_size() % 8)) % 8); } // realloc() assumes that T's placement new does not throw an exception. void realloc(std::size_t new_capacity) { MARISA_DEBUG_IF(new_capacity > max_size(), MARISA_SIZE_ERROR); scoped_array<char> new_buf( new (std::nothrow) char[sizeof(T) * new_capacity]); MARISA_DEBUG_IF(new_buf.get() == NULL, MARISA_MEMORY_ERROR); T *new_objs = reinterpret_cast<T *>(new_buf.get()); for (std::size_t i = 0; i < size_; ++i) { new (&new_objs[i]) T(objs_[i]); } for (std::size_t i = 0; i < size_; ++i) { objs_[i].~T(); } buf_.swap(new_buf); objs_ = new_objs; const_objs_ = new_objs; capacity_ = new_capacity; } // Disallows copy and assignment. Vector(const Vector &); Vector &operator=(const Vector &); }; } // namespace vector } // namespace grimoire } // namespace marisa #endif // MARISA_GRIMOIRE_VECTOR_VECTOR_H_
6,384
23.844358
74
h
OpenCC
OpenCC-master/deps/pybind11-2.10.0/include/pybind11/attr.h
/* pybind11/attr.h: Infrastructure for processing custom type and function attributes Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "detail/common.h" #include "cast.h" #include <functional> PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) /// \addtogroup annotations /// @{ /// Annotation for methods struct is_method { handle class_; explicit is_method(const handle &c) : class_(c) {} }; /// Annotation for operators struct is_operator {}; /// Annotation for classes that cannot be subclassed struct is_final {}; /// Annotation for parent scope struct scope { handle value; explicit scope(const handle &s) : value(s) {} }; /// Annotation for documentation struct doc { const char *value; explicit doc(const char *value) : value(value) {} }; /// Annotation for function names struct name { const char *value; explicit name(const char *value) : value(value) {} }; /// Annotation indicating that a function is an overload associated with a given "sibling" struct sibling { handle value; explicit sibling(const handle &value) : value(value.ptr()) {} }; /// Annotation indicating that a class derives from another given type template <typename T> struct base { PYBIND11_DEPRECATED( "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_") base() = default; }; /// Keep patient alive while nurse lives template <size_t Nurse, size_t Patient> struct keep_alive {}; /// Annotation indicating that a class is involved in a multiple inheritance relationship struct multiple_inheritance {}; /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class struct dynamic_attr {}; /// Annotation which enables the buffer protocol for a type struct buffer_protocol {}; /// Annotation which requests that a special metaclass is created for a type struct metaclass { handle value; PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.") metaclass() = default; /// Override pybind11's default metaclass explicit metaclass(handle value) : value(value) {} }; /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that /// may be used to customize the Python type. /// /// The callback is invoked immediately before `PyType_Ready`. /// /// Note: This is an advanced interface, and uses of it may require changes to /// work with later versions of pybind11. You may wish to consult the /// implementation of `make_new_python_type` in `detail/classes.h` to understand /// the context in which the callback will be run. struct custom_type_setup { using callback = std::function<void(PyHeapTypeObject *heap_type)>; explicit custom_type_setup(callback value) : value(std::move(value)) {} callback value; }; /// Annotation that marks a class as local to the module: struct module_local { const bool value; constexpr explicit module_local(bool v = true) : value(v) {} }; /// Annotation to mark enums as an arithmetic type struct arithmetic {}; /// Mark a function for addition at the beginning of the existing overload chain instead of the end struct prepend {}; /** \rst A call policy which places one or more guard variables (``Ts...``) around the function call. For example, this definition: .. code-block:: cpp m.def("foo", foo, py::call_guard<T>()); is equivalent to the following pseudocode: .. code-block:: cpp m.def("foo", [](args...) { T scope_guard; return foo(args...); // forwarded arguments }); \endrst */ template <typename... Ts> struct call_guard; template <> struct call_guard<> { using type = detail::void_type; }; template <typename T> struct call_guard<T> { static_assert(std::is_default_constructible<T>::value, "The guard type must be default constructible"); using type = T; }; template <typename T, typename... Ts> struct call_guard<T, Ts...> { struct type { T guard{}; // Compose multiple guard types with left-to-right default-constructor order typename call_guard<Ts...>::type next{}; }; }; /// @} annotations PYBIND11_NAMESPACE_BEGIN(detail) /* Forward declarations */ enum op_id : int; enum op_type : int; struct undefined_t; template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_; void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret); /// Internal data structure which holds metadata about a keyword argument struct argument_record { const char *name; ///< Argument name const char *descr; ///< Human-readable version of the argument value handle value; ///< Associated Python object bool convert : 1; ///< True if the argument is allowed to convert when loading bool none : 1; ///< True if None is allowed when loading argument_record(const char *name, const char *descr, handle value, bool convert, bool none) : name(name), descr(descr), value(value), convert(convert), none(none) {} }; /// Internal data structure which holds metadata about a bound function (signature, overloads, /// etc.) struct function_record { function_record() : is_constructor(false), is_new_style_constructor(false), is_stateless(false), is_operator(false), is_method(false), has_args(false), has_kwargs(false), prepend(false) {} /// Function name char *name = nullptr; /* why no C++ strings? They generate heavier code.. */ // User-specified documentation string char *doc = nullptr; /// Human-readable version of the function signature char *signature = nullptr; /// List of registered keyword arguments std::vector<argument_record> args; /// Pointer to lambda function which converts arguments and performs the actual call handle (*impl)(function_call &) = nullptr; /// Storage for the wrapped function pointer and captured data, if any void *data[3] = {}; /// Pointer to custom destructor for 'data' (if needed) void (*free_data)(function_record *ptr) = nullptr; /// Return value policy associated with this function return_value_policy policy = return_value_policy::automatic; /// True if name == '__init__' bool is_constructor : 1; /// True if this is a new-style `__init__` defined in `detail/init.h` bool is_new_style_constructor : 1; /// True if this is a stateless function pointer bool is_stateless : 1; /// True if this is an operator (__add__), etc. bool is_operator : 1; /// True if this is a method bool is_method : 1; /// True if the function has a '*args' argument bool has_args : 1; /// True if the function has a '**kwargs' argument bool has_kwargs : 1; /// True if this function is to be inserted at the beginning of the overload resolution chain bool prepend : 1; /// Number of arguments (including py::args and/or py::kwargs, if present) std::uint16_t nargs; /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs /// argument or by a py::kw_only annotation. std::uint16_t nargs_pos = 0; /// Number of leading arguments (counted in `nargs`) that are positional-only std::uint16_t nargs_pos_only = 0; /// Python method object PyMethodDef *def = nullptr; /// Python handle to the parent scope (a class or a module) handle scope; /// Python handle to the sibling function representing an overload chain handle sibling; /// Pointer to next overload function_record *next = nullptr; }; /// Special data structure which (temporarily) holds metadata about a bound class struct type_record { PYBIND11_NOINLINE type_record() : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false), default_holder(true), module_local(false), is_final(false) {} /// Handle to the parent scope handle scope; /// Name of the class const char *name = nullptr; // Pointer to RTTI type_info data structure const std::type_info *type = nullptr; /// How large is the underlying C++ type? size_t type_size = 0; /// What is the alignment of the underlying C++ type? size_t type_align = 0; /// How large is the type's holder? size_t holder_size = 0; /// The global operator new can be overridden with a class-specific variant void *(*operator_new)(size_t) = nullptr; /// Function pointer to class_<..>::init_instance void (*init_instance)(instance *, const void *) = nullptr; /// Function pointer to class_<..>::dealloc void (*dealloc)(detail::value_and_holder &) = nullptr; /// List of base classes of the newly created type list bases; /// Optional docstring const char *doc = nullptr; /// Custom metaclass (optional) handle metaclass; /// Custom type setup. custom_type_setup::callback custom_type_setup_callback; /// Multiple inheritance marker bool multiple_inheritance : 1; /// Does the class manage a __dict__? bool dynamic_attr : 1; /// Does the class implement the buffer protocol? bool buffer_protocol : 1; /// Is the default (unique_ptr) holder type used? bool default_holder : 1; /// Is the class definition local to the module shared object? bool module_local : 1; /// Is the class inheritable from python classes? bool is_final : 1; PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) { auto *base_info = detail::get_type_info(base, false); if (!base_info) { std::string tname(base.name()); detail::clean_type_id(tname); pybind11_fail("generic_type: type \"" + std::string(name) + "\" referenced unknown base type \"" + tname + "\""); } if (default_holder != base_info->default_holder) { std::string tname(base.name()); detail::clean_type_id(tname); pybind11_fail("generic_type: type \"" + std::string(name) + "\" " + (default_holder ? "does not have" : "has") + " a non-default holder type while its base \"" + tname + "\" " + (base_info->default_holder ? "does not" : "does")); } bases.append((PyObject *) base_info->type); #if PY_VERSION_HEX < 0x030B0000 dynamic_attr |= base_info->type->tp_dictoffset != 0; #else dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0; #endif if (caster) { base_info->implicit_casts.emplace_back(type, caster); } } }; inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) { args.reserve(f.nargs); args_convert.reserve(f.nargs); } /// Tag for a new-style `__init__` defined in `detail/init.h` struct is_new_style_constructor {}; /** * Partial template specializations to process custom attributes provided to * cpp_function_ and class_. These are either used to initialize the respective * fields in the type_record and function_record data structures or executed at * runtime to deal with custom call policies (e.g. keep_alive). */ template <typename T, typename SFINAE = void> struct process_attribute; template <typename T> struct process_attribute_default { /// Default implementation: do nothing static void init(const T &, function_record *) {} static void init(const T &, type_record *) {} static void precall(function_call &) {} static void postcall(function_call &, handle) {} }; /// Process an attribute specifying the function's name template <> struct process_attribute<name> : process_attribute_default<name> { static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); } }; /// Process an attribute specifying the function's docstring template <> struct process_attribute<doc> : process_attribute_default<doc> { static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); } }; /// Process an attribute specifying the function's docstring (provided as a C-style string) template <> struct process_attribute<const char *> : process_attribute_default<const char *> { static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); } static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); } }; template <> struct process_attribute<char *> : process_attribute<const char *> {}; /// Process an attribute indicating the function's return value policy template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> { static void init(const return_value_policy &p, function_record *r) { r->policy = p; } }; /// Process an attribute which indicates that this is an overloaded function associated with a /// given sibling template <> struct process_attribute<sibling> : process_attribute_default<sibling> { static void init(const sibling &s, function_record *r) { r->sibling = s.value; } }; /// Process an attribute which indicates that this function is a method template <> struct process_attribute<is_method> : process_attribute_default<is_method> { static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; } }; /// Process an attribute which indicates the parent scope of a method template <> struct process_attribute<scope> : process_attribute_default<scope> { static void init(const scope &s, function_record *r) { r->scope = s.value; } }; /// Process an attribute which indicates that this function is an operator template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> { static void init(const is_operator &, function_record *r) { r->is_operator = true; } }; template <> struct process_attribute<is_new_style_constructor> : process_attribute_default<is_new_style_constructor> { static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; } }; inline void check_kw_only_arg(const arg &a, function_record *r) { if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) { pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or " "args() argument"); } } inline void append_self_arg_if_needed(function_record *r) { if (r->is_method && r->args.empty()) { r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false); } } /// Process a keyword argument attribute (*without* a default value) template <> struct process_attribute<arg> : process_attribute_default<arg> { static void init(const arg &a, function_record *r) { append_self_arg_if_needed(r); r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none); check_kw_only_arg(a, r); } }; /// Process a keyword argument attribute (*with* a default value) template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> { static void init(const arg_v &a, function_record *r) { if (r->is_method && r->args.empty()) { r->args.emplace_back( "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false); } if (!a.value) { #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) std::string descr("'"); if (a.name) { descr += std::string(a.name) + ": "; } descr += a.type + "'"; if (r->is_method) { if (r->name) { descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'"; } else { descr += " in method of '" + (std::string) str(r->scope) + "'"; } } else if (r->name) { descr += " in function '" + (std::string) r->name + "'"; } pybind11_fail("arg(): could not convert default argument " + descr + " into a Python object (type not registered yet?)"); #else pybind11_fail("arg(): could not convert default argument " "into a Python object (type not registered yet?). " "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for " "more information."); #endif } r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none); check_kw_only_arg(a, r); } }; /// Process a keyword-only-arguments-follow pseudo argument template <> struct process_attribute<kw_only> : process_attribute_default<kw_only> { static void init(const kw_only &, function_record *r) { append_self_arg_if_needed(r); if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) { pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative " "argument location (or omit kw_only() entirely)"); } r->nargs_pos = static_cast<std::uint16_t>(r->args.size()); } }; /// Process a positional-only-argument maker template <> struct process_attribute<pos_only> : process_attribute_default<pos_only> { static void init(const pos_only &, function_record *r) { append_self_arg_if_needed(r); r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size()); if (r->nargs_pos_only > r->nargs_pos) { pybind11_fail("pos_only(): cannot follow a py::args() argument"); } // It also can't follow a kw_only, but a static_assert in pybind11.h checks that } }; /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees /// that) template <typename T> struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> { static void init(const handle &h, type_record *r) { r->bases.append(h); } }; /// Process a parent class attribute (deprecated, does not support multiple inheritance) template <typename T> struct process_attribute<base<T>> : process_attribute_default<base<T>> { static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); } }; /// Process a multiple inheritance attribute template <> struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> { static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; } }; template <> struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> { static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; } }; template <> struct process_attribute<custom_type_setup> { static void init(const custom_type_setup &value, type_record *r) { r->custom_type_setup_callback = value.value; } }; template <> struct process_attribute<is_final> : process_attribute_default<is_final> { static void init(const is_final &, type_record *r) { r->is_final = true; } }; template <> struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> { static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; } }; template <> struct process_attribute<metaclass> : process_attribute_default<metaclass> { static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; } }; template <> struct process_attribute<module_local> : process_attribute_default<module_local> { static void init(const module_local &l, type_record *r) { r->module_local = l.value; } }; /// Process a 'prepend' attribute, putting this at the beginning of the overload chain template <> struct process_attribute<prepend> : process_attribute_default<prepend> { static void init(const prepend &, function_record *r) { r->prepend = true; } }; /// Process an 'arithmetic' attribute for enums (does nothing here) template <> struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {}; template <typename... Ts> struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {}; /** * Process a keep_alive call policy -- invokes keep_alive_impl during the * pre-call handler if both Nurse, Patient != 0 and use the post-call handler * otherwise */ template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> { template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0> static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); } template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0> static void postcall(function_call &, handle) {} template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0> static void precall(function_call &) {} template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0> static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); } }; /// Recursively iterate over variadic template arguments template <typename... Args> struct process_attributes { static void init(const Args &...args, function_record *r) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); using expander = int[]; (void) expander{ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...}; } static void init(const Args &...args, type_record *r) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); using expander = int[]; (void) expander{0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...}; } static void precall(function_call &call) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call); using expander = int[]; (void) expander{0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...}; } static void postcall(function_call &call, handle fn_ret) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret); using expander = int[]; (void) expander{ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...}; } }; template <typename T> using is_call_guard = is_instantiation<call_guard, T>; /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found) template <typename... Extra> using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type; /// Check the number of named arguments at compile time template <typename... Extra, size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...), size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)> constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs); return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs; } PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
23,979
34.316642
99
h
OpenCC
OpenCC-master/deps/pybind11-2.10.0/include/pybind11/buffer_info.h
/* pybind11/buffer_info.h: Python buffer object interface Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "detail/common.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) // Default, C-style strides inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) { auto ndim = shape.size(); std::vector<ssize_t> strides(ndim, itemsize); if (ndim > 0) { for (size_t i = ndim - 1; i > 0; --i) { strides[i - 1] = strides[i] * shape[i]; } } return strides; } // F-style strides; default when constructing an array_t with `ExtraFlags & f_style` inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) { auto ndim = shape.size(); std::vector<ssize_t> strides(ndim, itemsize); for (size_t i = 1; i < ndim; ++i) { strides[i] = strides[i - 1] * shape[i - 1]; } return strides; } PYBIND11_NAMESPACE_END(detail) /// Information record describing a Python buffer object struct buffer_info { void *ptr = nullptr; // Pointer to the underlying storage ssize_t itemsize = 0; // Size of individual items in bytes ssize_t size = 0; // Total number of entries std::string format; // For homogeneous buffers, this should be set to // format_descriptor<T>::format() ssize_t ndim = 0; // Number of dimensions std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension) std::vector<ssize_t> strides; // Number of bytes between adjacent entries // (for each per dimension) bool readonly = false; // flag to indicate if the underlying storage may be written to buffer_info() = default; buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in, bool readonly = false) : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim), shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) { if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) { pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length"); } for (size_t i = 0; i < (size_t) ndim; ++i) { size *= shape[i]; } } template <typename T> buffer_info(T *ptr, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in, bool readonly = false) : buffer_info(private_ctr_tag(), ptr, sizeof(T), format_descriptor<T>::format(), static_cast<ssize_t>(shape_in->size()), std::move(shape_in), std::move(strides_in), readonly) {} buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size, bool readonly = false) : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {} template <typename T> buffer_info(T *ptr, ssize_t size, bool readonly = false) : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {} template <typename T> buffer_info(const T *ptr, ssize_t size, bool readonly = true) : buffer_info( const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {} explicit buffer_info(Py_buffer *view, bool ownview = true) : buffer_info( view->buf, view->itemsize, view->format, view->ndim, {view->shape, view->shape + view->ndim}, /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects * ignore this flag and return a view with NULL strides. * When strides are NULL, build them manually. */ view->strides ? std::vector<ssize_t>(view->strides, view->strides + view->ndim) : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize), (view->readonly != 0)) { // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) this->m_view = view; // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) this->ownview = ownview; } buffer_info(const buffer_info &) = delete; buffer_info &operator=(const buffer_info &) = delete; buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); } buffer_info &operator=(buffer_info &&rhs) noexcept { ptr = rhs.ptr; itemsize = rhs.itemsize; size = rhs.size; format = std::move(rhs.format); ndim = rhs.ndim; shape = std::move(rhs.shape); strides = std::move(rhs.strides); std::swap(m_view, rhs.m_view); std::swap(ownview, rhs.ownview); readonly = rhs.readonly; return *this; } ~buffer_info() { if (m_view && ownview) { PyBuffer_Release(m_view); delete m_view; } } Py_buffer *view() const { return m_view; } Py_buffer *&view() { return m_view; } private: struct private_ctr_tag {}; buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim, detail::any_container<ssize_t> &&shape_in, detail::any_container<ssize_t> &&strides_in, bool readonly) : buffer_info( ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {} Py_buffer *m_view = nullptr; bool ownview = false; }; PYBIND11_NAMESPACE_BEGIN(detail) template <typename T, typename SFINAE = void> struct compare_buffer_info { static bool compare(const buffer_info &b) { return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T); } }; template <typename T> struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> { static bool compare(const buffer_info &b) { return (size_t) b.itemsize == sizeof(T) && (b.format == format_descriptor<T>::value || ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned<T>::value ? "L" : "l")) || ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned<T>::value ? "N" : "n"))); } }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
7,069
35.443299
97
h