common.h revision fbaaef999ba563838ebd00874ed8a1c01fbf286d
1// Protocol Buffers - Google's data interchange format 2// Copyright 2008 Google Inc. All rights reserved. 3// http://code.google.com/p/protobuf/ 4// 5// Redistribution and use in source and binary forms, with or without 6// modification, are permitted provided that the following conditions are 7// met: 8// 9// * Redistributions of source code must retain the above copyright 10// notice, this list of conditions and the following disclaimer. 11// * Redistributions in binary form must reproduce the above 12// copyright notice, this list of conditions and the following disclaimer 13// in the documentation and/or other materials provided with the 14// distribution. 15// * Neither the name of Google Inc. nor the names of its 16// contributors may be used to endorse or promote products derived from 17// this software without specific prior written permission. 18// 19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 31// Author: kenton@google.com (Kenton Varda) and others 32// 33// Contains basic types and utilities used by the rest of the library. 34 35#ifndef GOOGLE_PROTOBUF_COMMON_H__ 36#define GOOGLE_PROTOBUF_COMMON_H__ 37 38#include <assert.h> 39#include <stdlib.h> 40#include <cstddef> 41#include <string> 42#include <string.h> 43#if defined(__osf__) 44// Tru64 lacks stdint.h, but has inttypes.h which defines a superset of 45// what stdint.h would define. 46#include <inttypes.h> 47#elif !defined(_MSC_VER) 48#include <stdint.h> 49#endif 50 51namespace std {} 52 53namespace google { 54namespace protobuf { 55 56using namespace std; // Don't do this at home, kids. 57 58#undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS 59#define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName) \ 60 TypeName(const TypeName&); \ 61 void operator=(const TypeName&) 62 63#if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS) 64 #ifdef LIBPROTOBUF_EXPORTS 65 #define LIBPROTOBUF_EXPORT __declspec(dllexport) 66 #else 67 #define LIBPROTOBUF_EXPORT __declspec(dllimport) 68 #endif 69 #ifdef LIBPROTOC_EXPORTS 70 #define LIBPROTOC_EXPORT __declspec(dllexport) 71 #else 72 #define LIBPROTOC_EXPORT __declspec(dllimport) 73 #endif 74#else 75 #define LIBPROTOBUF_EXPORT 76 #define LIBPROTOC_EXPORT 77#endif 78 79namespace internal { 80 81// Some of these constants are macros rather than const ints so that they can 82// be used in #if directives. 83 84// The current version, represented as a single integer to make comparison 85// easier: major * 10^6 + minor * 10^3 + micro 86#define GOOGLE_PROTOBUF_VERSION 2002000 87 88// The minimum library version which works with the current version of the 89// headers. 90#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 2002000 91 92// The minimum header version which works with the current version of 93// the library. This constant should only be used by protoc's C++ code 94// generator. 95static const int kMinHeaderVersionForLibrary = 2002000; 96 97// The minimum protoc version which works with the current version of the 98// headers. 99#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 2002000 100 101// The minimum header version which works with the current version of 102// protoc. This constant should only be used in VerifyVersion(). 103static const int kMinHeaderVersionForProtoc = 2002000; 104 105// Verifies that the headers and libraries are compatible. Use the macro 106// below to call this. 107void LIBPROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion, 108 const char* filename); 109 110// Converts a numeric version number to a string. 111string LIBPROTOBUF_EXPORT VersionString(int version); 112 113} // namespace internal 114 115// Place this macro in your main() function (or somewhere before you attempt 116// to use the protobuf library) to verify that the version you link against 117// matches the headers you compiled against. If a version mismatch is 118// detected, the process will abort. 119#define GOOGLE_PROTOBUF_VERIFY_VERSION \ 120 ::google::protobuf::internal::VerifyVersion( \ 121 GOOGLE_PROTOBUF_VERSION, GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION, \ 122 __FILE__) 123 124// =================================================================== 125// from google3/base/port.h 126 127typedef unsigned int uint; 128 129#ifdef _MSC_VER 130typedef __int8 int8; 131typedef __int16 int16; 132typedef __int32 int32; 133typedef __int64 int64; 134 135typedef unsigned __int8 uint8; 136typedef unsigned __int16 uint16; 137typedef unsigned __int32 uint32; 138typedef unsigned __int64 uint64; 139#else 140typedef int8_t int8; 141typedef int16_t int16; 142typedef int32_t int32; 143typedef int64_t int64; 144 145typedef uint8_t uint8; 146typedef uint16_t uint16; 147typedef uint32_t uint32; 148typedef uint64_t uint64; 149#endif 150 151// long long macros to be used because gcc and vc++ use different suffixes, 152// and different size specifiers in format strings 153#undef GOOGLE_LONGLONG 154#undef GOOGLE_ULONGLONG 155#undef GOOGLE_LL_FORMAT 156 157#ifdef _MSC_VER 158#define GOOGLE_LONGLONG(x) x##I64 159#define GOOGLE_ULONGLONG(x) x##UI64 160#define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...) 161#else 162#define GOOGLE_LONGLONG(x) x##LL 163#define GOOGLE_ULONGLONG(x) x##ULL 164#define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also. 165#endif 166 167static const int32 kint32max = 0x7FFFFFFF; 168static const int32 kint32min = -kint32max - 1; 169static const int64 kint64max = GOOGLE_LONGLONG(0x7FFFFFFFFFFFFFFF); 170static const int64 kint64min = -kint64max - 1; 171static const uint32 kuint32max = 0xFFFFFFFFu; 172static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); 173 174#undef GOOGLE_ATTRIBUTE_ALWAYS_INLINE 175#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) 176// For functions we want to force inline. 177// Introduced in gcc 3.1. 178#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline)) 179#else 180// Other compilers will have to figure it out for themselves. 181#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE 182#endif 183 184#undef GOOGLE_ATTRIBUTE_DEPRECATED 185#ifdef __GNUC__ 186// If the method/variable/type is used anywhere, produce a warning. 187#define GOOGLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated)) 188#else 189#define GOOGLE_ATTRIBUTE_DEPRECATED 190#endif 191 192// =================================================================== 193// from google3/base/basictypes.h 194 195// The GOOGLE_ARRAYSIZE(arr) macro returns the # of elements in an array arr. 196// The expression is a compile-time constant, and therefore can be 197// used in defining new arrays, for example. 198// 199// GOOGLE_ARRAYSIZE catches a few type errors. If you see a compiler error 200// 201// "warning: division by zero in ..." 202// 203// when using GOOGLE_ARRAYSIZE, you are (wrongfully) giving it a pointer. 204// You should only use GOOGLE_ARRAYSIZE on statically allocated arrays. 205// 206// The following comments are on the implementation details, and can 207// be ignored by the users. 208// 209// ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in 210// the array) and sizeof(*(arr)) (the # of bytes in one array 211// element). If the former is divisible by the latter, perhaps arr is 212// indeed an array, in which case the division result is the # of 213// elements in the array. Otherwise, arr cannot possibly be an array, 214// and we generate a compiler error to prevent the code from 215// compiling. 216// 217// Since the size of bool is implementation-defined, we need to cast 218// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final 219// result has type size_t. 220// 221// This macro is not perfect as it wrongfully accepts certain 222// pointers, namely where the pointer size is divisible by the pointee 223// size. Since all our code has to go through a 32-bit compiler, 224// where a pointer is 4 bytes, this means all pointers to a type whose 225// size is 3 or greater than 4 will be (righteously) rejected. 226// 227// Kudos to Jorg Brown for this simple and elegant implementation. 228 229#undef GOOGLE_ARRAYSIZE 230#define GOOGLE_ARRAYSIZE(a) \ 231 ((sizeof(a) / sizeof(*(a))) / \ 232 static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) 233 234namespace internal { 235 236// Use implicit_cast as a safe version of static_cast or const_cast 237// for upcasting in the type hierarchy (i.e. casting a pointer to Foo 238// to a pointer to SuperclassOfFoo or casting a pointer to Foo to 239// a const pointer to Foo). 240// When you use implicit_cast, the compiler checks that the cast is safe. 241// Such explicit implicit_casts are necessary in surprisingly many 242// situations where C++ demands an exact type match instead of an 243// argument type convertable to a target type. 244// 245// The From type can be inferred, so the preferred syntax for using 246// implicit_cast is the same as for static_cast etc.: 247// 248// implicit_cast<ToType>(expr) 249// 250// implicit_cast would have been part of the C++ standard library, 251// but the proposal was submitted too late. It will probably make 252// its way into the language in the future. 253template<typename To, typename From> 254inline To implicit_cast(From const &f) { 255 return f; 256} 257 258// When you upcast (that is, cast a pointer from type Foo to type 259// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts 260// always succeed. When you downcast (that is, cast a pointer from 261// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because 262// how do you know the pointer is really of type SubclassOfFoo? It 263// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, 264// when you downcast, you should use this macro. In debug mode, we 265// use dynamic_cast<> to double-check the downcast is legal (we die 266// if it's not). In normal mode, we do the efficient static_cast<> 267// instead. Thus, it's important to test in debug mode to make sure 268// the cast is legal! 269// This is the only place in the code we should use dynamic_cast<>. 270// In particular, you SHOULDN'T be using dynamic_cast<> in order to 271// do RTTI (eg code like this: 272// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); 273// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); 274// You should design the code some other way not to need this. 275 276template<typename To, typename From> // use like this: down_cast<T*>(foo); 277inline To down_cast(From* f) { // so we only accept pointers 278 // Ensures that To is a sub-type of From *. This test is here only 279 // for compile-time type checking, and has no overhead in an 280 // optimized build at run-time, as it will be optimized away 281 // completely. 282 if (false) { 283 implicit_cast<From*, To>(0); 284 } 285 286 assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only! 287 return static_cast<To>(f); 288} 289 290} // namespace internal 291 292// We made these internal so that they would show up as such in the docs, 293// but we don't want to stick "internal::" in front of them everywhere. 294using internal::implicit_cast; 295using internal::down_cast; 296 297// The COMPILE_ASSERT macro can be used to verify that a compile time 298// expression is true. For example, you could use it to verify the 299// size of a static array: 300// 301// COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, 302// content_type_names_incorrect_size); 303// 304// or to make sure a struct is smaller than a certain size: 305// 306// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); 307// 308// The second argument to the macro is the name of the variable. If 309// the expression is false, most compilers will issue a warning/error 310// containing the name of the variable. 311 312namespace internal { 313 314template <bool> 315struct CompileAssert { 316}; 317 318} // namespace internal 319 320#undef GOOGLE_COMPILE_ASSERT 321#define GOOGLE_COMPILE_ASSERT(expr, msg) \ 322 typedef ::google::protobuf::internal::CompileAssert<(bool(expr))> \ 323 msg[bool(expr) ? 1 : -1] 324 325// Implementation details of COMPILE_ASSERT: 326// 327// - COMPILE_ASSERT works by defining an array type that has -1 328// elements (and thus is invalid) when the expression is false. 329// 330// - The simpler definition 331// 332// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] 333// 334// does not work, as gcc supports variable-length arrays whose sizes 335// are determined at run-time (this is gcc's extension and not part 336// of the C++ standard). As a result, gcc fails to reject the 337// following code with the simple definition: 338// 339// int foo; 340// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is 341// // not a compile-time constant. 342// 343// - By using the type CompileAssert<(bool(expr))>, we ensures that 344// expr is a compile-time constant. (Template arguments must be 345// determined at compile-time.) 346// 347// - The outter parentheses in CompileAssert<(bool(expr))> are necessary 348// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written 349// 350// CompileAssert<bool(expr)> 351// 352// instead, these compilers will refuse to compile 353// 354// COMPILE_ASSERT(5 > 0, some_message); 355// 356// (They seem to think the ">" in "5 > 0" marks the end of the 357// template argument list.) 358// 359// - The array size is (bool(expr) ? 1 : -1), instead of simply 360// 361// ((expr) ? 1 : -1). 362// 363// This is to avoid running into a bug in MS VC 7.1, which 364// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. 365 366// =================================================================== 367// from google3/base/scoped_ptr.h 368 369namespace internal { 370 371// This is an implementation designed to match the anticipated future TR2 372// implementation of the scoped_ptr class, and its closely-related brethren, 373// scoped_array, scoped_ptr_malloc, and make_scoped_ptr. 374 375template <class C> class scoped_ptr; 376template <class C> class scoped_array; 377 378// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T> 379// automatically deletes the pointer it holds (if any). 380// That is, scoped_ptr<T> owns the T object that it points to. 381// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object. 382// 383// The size of a scoped_ptr is small: 384// sizeof(scoped_ptr<C>) == sizeof(C*) 385template <class C> 386class scoped_ptr { 387 public: 388 389 // The element type 390 typedef C element_type; 391 392 // Constructor. Defaults to intializing with NULL. 393 // There is no way to create an uninitialized scoped_ptr. 394 // The input parameter must be allocated with new. 395 explicit scoped_ptr(C* p = NULL) : ptr_(p) { } 396 397 // Destructor. If there is a C object, delete it. 398 // We don't need to test ptr_ == NULL because C++ does that for us. 399 ~scoped_ptr() { 400 enum { type_must_be_complete = sizeof(C) }; 401 delete ptr_; 402 } 403 404 // Reset. Deletes the current owned object, if any. 405 // Then takes ownership of a new object, if given. 406 // this->reset(this->get()) works. 407 void reset(C* p = NULL) { 408 if (p != ptr_) { 409 enum { type_must_be_complete = sizeof(C) }; 410 delete ptr_; 411 ptr_ = p; 412 } 413 } 414 415 // Accessors to get the owned object. 416 // operator* and operator-> will assert() if there is no current object. 417 C& operator*() const { 418 assert(ptr_ != NULL); 419 return *ptr_; 420 } 421 C* operator->() const { 422 assert(ptr_ != NULL); 423 return ptr_; 424 } 425 C* get() const { return ptr_; } 426 427 // Comparison operators. 428 // These return whether two scoped_ptr refer to the same object, not just to 429 // two different but equal objects. 430 bool operator==(C* p) const { return ptr_ == p; } 431 bool operator!=(C* p) const { return ptr_ != p; } 432 433 // Swap two scoped pointers. 434 void swap(scoped_ptr& p2) { 435 C* tmp = ptr_; 436 ptr_ = p2.ptr_; 437 p2.ptr_ = tmp; 438 } 439 440 // Release a pointer. 441 // The return value is the current pointer held by this object. 442 // If this object holds a NULL pointer, the return value is NULL. 443 // After this operation, this object will hold a NULL pointer, 444 // and will not own the object any more. 445 C* release() { 446 C* retVal = ptr_; 447 ptr_ = NULL; 448 return retVal; 449 } 450 451 private: 452 C* ptr_; 453 454 // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't 455 // make sense, and if C2 == C, it still doesn't make sense because you should 456 // never have the same object owned by two different scoped_ptrs. 457 template <class C2> bool operator==(scoped_ptr<C2> const& p2) const; 458 template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const; 459 460 // Disallow evil constructors 461 scoped_ptr(const scoped_ptr&); 462 void operator=(const scoped_ptr&); 463}; 464 465// scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate 466// with new [] and the destructor deletes objects with delete []. 467// 468// As with scoped_ptr<C>, a scoped_array<C> either points to an object 469// or is NULL. A scoped_array<C> owns the object that it points to. 470// 471// Size: sizeof(scoped_array<C>) == sizeof(C*) 472template <class C> 473class scoped_array { 474 public: 475 476 // The element type 477 typedef C element_type; 478 479 // Constructor. Defaults to intializing with NULL. 480 // There is no way to create an uninitialized scoped_array. 481 // The input parameter must be allocated with new []. 482 explicit scoped_array(C* p = NULL) : array_(p) { } 483 484 // Destructor. If there is a C object, delete it. 485 // We don't need to test ptr_ == NULL because C++ does that for us. 486 ~scoped_array() { 487 enum { type_must_be_complete = sizeof(C) }; 488 delete[] array_; 489 } 490 491 // Reset. Deletes the current owned object, if any. 492 // Then takes ownership of a new object, if given. 493 // this->reset(this->get()) works. 494 void reset(C* p = NULL) { 495 if (p != array_) { 496 enum { type_must_be_complete = sizeof(C) }; 497 delete[] array_; 498 array_ = p; 499 } 500 } 501 502 // Get one element of the current object. 503 // Will assert() if there is no current object, or index i is negative. 504 C& operator[](std::ptrdiff_t i) const { 505 assert(i >= 0); 506 assert(array_ != NULL); 507 return array_[i]; 508 } 509 510 // Get a pointer to the zeroth element of the current object. 511 // If there is no current object, return NULL. 512 C* get() const { 513 return array_; 514 } 515 516 // Comparison operators. 517 // These return whether two scoped_array refer to the same object, not just to 518 // two different but equal objects. 519 bool operator==(C* p) const { return array_ == p; } 520 bool operator!=(C* p) const { return array_ != p; } 521 522 // Swap two scoped arrays. 523 void swap(scoped_array& p2) { 524 C* tmp = array_; 525 array_ = p2.array_; 526 p2.array_ = tmp; 527 } 528 529 // Release an array. 530 // The return value is the current pointer held by this object. 531 // If this object holds a NULL pointer, the return value is NULL. 532 // After this operation, this object will hold a NULL pointer, 533 // and will not own the object any more. 534 C* release() { 535 C* retVal = array_; 536 array_ = NULL; 537 return retVal; 538 } 539 540 private: 541 C* array_; 542 543 // Forbid comparison of different scoped_array types. 544 template <class C2> bool operator==(scoped_array<C2> const& p2) const; 545 template <class C2> bool operator!=(scoped_array<C2> const& p2) const; 546 547 // Disallow evil constructors 548 scoped_array(const scoped_array&); 549 void operator=(const scoped_array&); 550}; 551 552} // namespace internal 553 554// We made these internal so that they would show up as such in the docs, 555// but we don't want to stick "internal::" in front of them everywhere. 556using internal::scoped_ptr; 557using internal::scoped_array; 558 559// =================================================================== 560// emulates google3/base/logging.h 561 562enum LogLevel { 563 LOGLEVEL_INFO, // Informational. This is never actually used by 564 // libprotobuf. 565 LOGLEVEL_WARNING, // Warns about issues that, although not technically a 566 // problem now, could cause problems in the future. For 567 // example, a // warning will be printed when parsing a 568 // message that is near the message size limit. 569 LOGLEVEL_ERROR, // An error occurred which should never happen during 570 // normal use. 571 LOGLEVEL_FATAL, // An error occurred from which the library cannot 572 // recover. This usually indicates a programming error 573 // in the code which calls the library, especially when 574 // compiled in debug mode. 575 576#ifdef NDEBUG 577 LOGLEVEL_DFATAL = LOGLEVEL_ERROR 578#else 579 LOGLEVEL_DFATAL = LOGLEVEL_FATAL 580#endif 581}; 582 583namespace internal { 584 585class LogFinisher; 586 587class LIBPROTOBUF_EXPORT LogMessage { 588 public: 589 LogMessage(LogLevel level, const char* filename, int line); 590 ~LogMessage(); 591 592 LogMessage& operator<<(const string& value); 593 LogMessage& operator<<(const char* value); 594 LogMessage& operator<<(char value); 595 LogMessage& operator<<(int value); 596 LogMessage& operator<<(uint value); 597 LogMessage& operator<<(long value); 598 LogMessage& operator<<(unsigned long value); 599 LogMessage& operator<<(double value); 600 601 private: 602 friend class LogFinisher; 603 void Finish(); 604 605 LogLevel level_; 606 const char* filename_; 607 int line_; 608 string message_; 609}; 610 611// Used to make the entire "LOG(BLAH) << etc." expression have a void return 612// type and print a newline after each message. 613class LIBPROTOBUF_EXPORT LogFinisher { 614 public: 615 void operator=(LogMessage& other); 616}; 617 618} // namespace internal 619 620// Undef everything in case we're being mixed with some other Google library 621// which already defined them itself. Presumably all Google libraries will 622// support the same syntax for these so it should not be a big deal if they 623// end up using our definitions instead. 624#undef GOOGLE_LOG 625#undef GOOGLE_LOG_IF 626 627#undef GOOGLE_CHECK 628#undef GOOGLE_CHECK_EQ 629#undef GOOGLE_CHECK_NE 630#undef GOOGLE_CHECK_LT 631#undef GOOGLE_CHECK_LE 632#undef GOOGLE_CHECK_GT 633#undef GOOGLE_CHECK_GE 634 635#undef GOOGLE_DLOG 636#undef GOOGLE_DCHECK 637#undef GOOGLE_DCHECK_EQ 638#undef GOOGLE_DCHECK_NE 639#undef GOOGLE_DCHECK_LT 640#undef GOOGLE_DCHECK_LE 641#undef GOOGLE_DCHECK_GT 642#undef GOOGLE_DCHECK_GE 643 644#define GOOGLE_LOG(LEVEL) \ 645 ::google::protobuf::internal::LogFinisher() = \ 646 ::google::protobuf::internal::LogMessage( \ 647 ::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__) 648#define GOOGLE_LOG_IF(LEVEL, CONDITION) \ 649 !(CONDITION) ? (void)0 : GOOGLE_LOG(LEVEL) 650 651#define GOOGLE_CHECK(EXPRESSION) \ 652 GOOGLE_LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": " 653#define GOOGLE_CHECK_EQ(A, B) GOOGLE_CHECK((A) == (B)) 654#define GOOGLE_CHECK_NE(A, B) GOOGLE_CHECK((A) != (B)) 655#define GOOGLE_CHECK_LT(A, B) GOOGLE_CHECK((A) < (B)) 656#define GOOGLE_CHECK_LE(A, B) GOOGLE_CHECK((A) <= (B)) 657#define GOOGLE_CHECK_GT(A, B) GOOGLE_CHECK((A) > (B)) 658#define GOOGLE_CHECK_GE(A, B) GOOGLE_CHECK((A) >= (B)) 659 660#ifdef NDEBUG 661 662#define GOOGLE_DLOG GOOGLE_LOG_IF(INFO, false) 663 664#define GOOGLE_DCHECK(EXPRESSION) while(false) GOOGLE_CHECK(EXPRESSION) 665#define GOOGLE_DCHECK_EQ(A, B) GOOGLE_DCHECK((A) == (B)) 666#define GOOGLE_DCHECK_NE(A, B) GOOGLE_DCHECK((A) != (B)) 667#define GOOGLE_DCHECK_LT(A, B) GOOGLE_DCHECK((A) < (B)) 668#define GOOGLE_DCHECK_LE(A, B) GOOGLE_DCHECK((A) <= (B)) 669#define GOOGLE_DCHECK_GT(A, B) GOOGLE_DCHECK((A) > (B)) 670#define GOOGLE_DCHECK_GE(A, B) GOOGLE_DCHECK((A) >= (B)) 671 672#else // NDEBUG 673 674#define GOOGLE_DLOG GOOGLE_LOG 675 676#define GOOGLE_DCHECK GOOGLE_CHECK 677#define GOOGLE_DCHECK_EQ GOOGLE_CHECK_EQ 678#define GOOGLE_DCHECK_NE GOOGLE_CHECK_NE 679#define GOOGLE_DCHECK_LT GOOGLE_CHECK_LT 680#define GOOGLE_DCHECK_LE GOOGLE_CHECK_LE 681#define GOOGLE_DCHECK_GT GOOGLE_CHECK_GT 682#define GOOGLE_DCHECK_GE GOOGLE_CHECK_GE 683 684#endif // !NDEBUG 685 686typedef void LogHandler(LogLevel level, const char* filename, int line, 687 const string& message); 688 689// The protobuf library sometimes writes warning and error messages to 690// stderr. These messages are primarily useful for developers, but may 691// also help end users figure out a problem. If you would prefer that 692// these messages be sent somewhere other than stderr, call SetLogHandler() 693// to set your own handler. This returns the old handler. Set the handler 694// to NULL to ignore log messages (but see also LogSilencer, below). 695// 696// Obviously, SetLogHandler is not thread-safe. You should only call it 697// at initialization time, and probably not from library code. If you 698// simply want to suppress log messages temporarily (e.g. because you 699// have some code that tends to trigger them frequently and you know 700// the warnings are not important to you), use the LogSilencer class 701// below. 702LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func); 703 704// Create a LogSilencer if you want to temporarily suppress all log 705// messages. As long as any LogSilencer objects exist, non-fatal 706// log messages will be discarded (the current LogHandler will *not* 707// be called). Constructing a LogSilencer is thread-safe. You may 708// accidentally suppress log messages occurring in another thread, but 709// since messages are generally for debugging purposes only, this isn't 710// a big deal. If you want to intercept log messages, use SetLogHandler(). 711class LIBPROTOBUF_EXPORT LogSilencer { 712 public: 713 LogSilencer(); 714 ~LogSilencer(); 715}; 716 717// =================================================================== 718// emulates google3/base/callback.h 719 720// Abstract interface for a callback. When calling an RPC, you must provide 721// a Closure to call when the procedure completes. See the Service interface 722// in service.h. 723// 724// To automatically construct a Closure which calls a particular function or 725// method with a particular set of parameters, use the NewCallback() function. 726// Example: 727// void FooDone(const FooResponse* response) { 728// ... 729// } 730// 731// void CallFoo() { 732// ... 733// // When done, call FooDone() and pass it a pointer to the response. 734// Closure* callback = NewCallback(&FooDone, response); 735// // Make the call. 736// service->Foo(controller, request, response, callback); 737// } 738// 739// Example that calls a method: 740// class Handler { 741// public: 742// ... 743// 744// void FooDone(const FooResponse* response) { 745// ... 746// } 747// 748// void CallFoo() { 749// ... 750// // When done, call FooDone() and pass it a pointer to the response. 751// Closure* callback = NewCallback(this, &Handler::FooDone, response); 752// // Make the call. 753// service->Foo(controller, request, response, callback); 754// } 755// }; 756// 757// Currently NewCallback() supports binding zero, one, or two arguments. 758// 759// Callbacks created with NewCallback() automatically delete themselves when 760// executed. They should be used when a callback is to be called exactly 761// once (usually the case with RPC callbacks). If a callback may be called 762// a different number of times (including zero), create it with 763// NewPermanentCallback() instead. You are then responsible for deleting the 764// callback (using the "delete" keyword as normal). 765// 766// Note that NewCallback() is a bit touchy regarding argument types. Generally, 767// the values you provide for the parameter bindings must exactly match the 768// types accepted by the callback function. For example: 769// void Foo(string s); 770// NewCallback(&Foo, "foo"); // WON'T WORK: const char* != string 771// NewCallback(&Foo, string("foo")); // WORKS 772// Also note that the arguments cannot be references: 773// void Foo(const string& s); 774// string my_str; 775// NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes. 776// However, correctly-typed pointers will work just fine. 777class LIBPROTOBUF_EXPORT Closure { 778 public: 779 Closure() {} 780 virtual ~Closure(); 781 782 virtual void Run() = 0; 783 784 private: 785 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Closure); 786}; 787 788namespace internal { 789 790class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure { 791 public: 792 typedef void (*FunctionType)(); 793 794 FunctionClosure0(FunctionType function, bool self_deleting) 795 : function_(function), self_deleting_(self_deleting) {} 796 ~FunctionClosure0(); 797 798 void Run() { 799 function_(); 800 if (self_deleting_) delete this; 801 } 802 803 private: 804 FunctionType function_; 805 bool self_deleting_; 806}; 807 808template <typename Class> 809class MethodClosure0 : public Closure { 810 public: 811 typedef void (Class::*MethodType)(); 812 813 MethodClosure0(Class* object, MethodType method, bool self_deleting) 814 : object_(object), method_(method), self_deleting_(self_deleting) {} 815 ~MethodClosure0() {} 816 817 void Run() { 818 (object_->*method_)(); 819 if (self_deleting_) delete this; 820 } 821 822 private: 823 Class* object_; 824 MethodType method_; 825 bool self_deleting_; 826}; 827 828template <typename Arg1> 829class FunctionClosure1 : public Closure { 830 public: 831 typedef void (*FunctionType)(Arg1 arg1); 832 833 FunctionClosure1(FunctionType function, bool self_deleting, 834 Arg1 arg1) 835 : function_(function), self_deleting_(self_deleting), 836 arg1_(arg1) {} 837 ~FunctionClosure1() {} 838 839 void Run() { 840 function_(arg1_); 841 if (self_deleting_) delete this; 842 } 843 844 private: 845 FunctionType function_; 846 bool self_deleting_; 847 Arg1 arg1_; 848}; 849 850template <typename Class, typename Arg1> 851class MethodClosure1 : public Closure { 852 public: 853 typedef void (Class::*MethodType)(Arg1 arg1); 854 855 MethodClosure1(Class* object, MethodType method, bool self_deleting, 856 Arg1 arg1) 857 : object_(object), method_(method), self_deleting_(self_deleting), 858 arg1_(arg1) {} 859 ~MethodClosure1() {} 860 861 void Run() { 862 (object_->*method_)(arg1_); 863 if (self_deleting_) delete this; 864 } 865 866 private: 867 Class* object_; 868 MethodType method_; 869 bool self_deleting_; 870 Arg1 arg1_; 871}; 872 873template <typename Arg1, typename Arg2> 874class FunctionClosure2 : public Closure { 875 public: 876 typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2); 877 878 FunctionClosure2(FunctionType function, bool self_deleting, 879 Arg1 arg1, Arg2 arg2) 880 : function_(function), self_deleting_(self_deleting), 881 arg1_(arg1), arg2_(arg2) {} 882 ~FunctionClosure2() {} 883 884 void Run() { 885 function_(arg1_, arg2_); 886 if (self_deleting_) delete this; 887 } 888 889 private: 890 FunctionType function_; 891 bool self_deleting_; 892 Arg1 arg1_; 893 Arg2 arg2_; 894}; 895 896template <typename Class, typename Arg1, typename Arg2> 897class MethodClosure2 : public Closure { 898 public: 899 typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2); 900 901 MethodClosure2(Class* object, MethodType method, bool self_deleting, 902 Arg1 arg1, Arg2 arg2) 903 : object_(object), method_(method), self_deleting_(self_deleting), 904 arg1_(arg1), arg2_(arg2) {} 905 ~MethodClosure2() {} 906 907 void Run() { 908 (object_->*method_)(arg1_, arg2_); 909 if (self_deleting_) delete this; 910 } 911 912 private: 913 Class* object_; 914 MethodType method_; 915 bool self_deleting_; 916 Arg1 arg1_; 917 Arg2 arg2_; 918}; 919 920} // namespace internal 921 922// See Closure. 923inline Closure* NewCallback(void (*function)()) { 924 return new internal::FunctionClosure0(function, true); 925} 926 927// See Closure. 928inline Closure* NewPermanentCallback(void (*function)()) { 929 return new internal::FunctionClosure0(function, false); 930} 931 932// See Closure. 933template <typename Class> 934inline Closure* NewCallback(Class* object, void (Class::*method)()) { 935 return new internal::MethodClosure0<Class>(object, method, true); 936} 937 938// See Closure. 939template <typename Class> 940inline Closure* NewPermanentCallback(Class* object, void (Class::*method)()) { 941 return new internal::MethodClosure0<Class>(object, method, false); 942} 943 944// See Closure. 945template <typename Arg1> 946inline Closure* NewCallback(void (*function)(Arg1), 947 Arg1 arg1) { 948 return new internal::FunctionClosure1<Arg1>(function, true, arg1); 949} 950 951// See Closure. 952template <typename Arg1> 953inline Closure* NewPermanentCallback(void (*function)(Arg1), 954 Arg1 arg1) { 955 return new internal::FunctionClosure1<Arg1>(function, false, arg1); 956} 957 958// See Closure. 959template <typename Class, typename Arg1> 960inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1), 961 Arg1 arg1) { 962 return new internal::MethodClosure1<Class, Arg1>(object, method, true, arg1); 963} 964 965// See Closure. 966template <typename Class, typename Arg1> 967inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(Arg1), 968 Arg1 arg1) { 969 return new internal::MethodClosure1<Class, Arg1>(object, method, false, arg1); 970} 971 972// See Closure. 973template <typename Arg1, typename Arg2> 974inline Closure* NewCallback(void (*function)(Arg1, Arg2), 975 Arg1 arg1, Arg2 arg2) { 976 return new internal::FunctionClosure2<Arg1, Arg2>( 977 function, true, arg1, arg2); 978} 979 980// See Closure. 981template <typename Arg1, typename Arg2> 982inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2), 983 Arg1 arg1, Arg2 arg2) { 984 return new internal::FunctionClosure2<Arg1, Arg2>( 985 function, false, arg1, arg2); 986} 987 988// See Closure. 989template <typename Class, typename Arg1, typename Arg2> 990inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, Arg2), 991 Arg1 arg1, Arg2 arg2) { 992 return new internal::MethodClosure2<Class, Arg1, Arg2>( 993 object, method, true, arg1, arg2); 994} 995 996// See Closure. 997template <typename Class, typename Arg1, typename Arg2> 998inline Closure* NewPermanentCallback( 999 Class* object, void (Class::*method)(Arg1, Arg2), 1000 Arg1 arg1, Arg2 arg2) { 1001 return new internal::MethodClosure2<Class, Arg1, Arg2>( 1002 object, method, false, arg1, arg2); 1003} 1004 1005// A function which does nothing. Useful for creating no-op callbacks, e.g.: 1006// Closure* nothing = NewCallback(&DoNothing); 1007void LIBPROTOBUF_EXPORT DoNothing(); 1008 1009// =================================================================== 1010// emulates google3/base/mutex.h 1011 1012namespace internal { 1013 1014// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T 1015// may hold a mutex at a given time. If T attempts to Lock() the same Mutex 1016// while holding it, T will deadlock. 1017class LIBPROTOBUF_EXPORT Mutex { 1018 public: 1019 // Create a Mutex that is not held by anybody. 1020 Mutex(); 1021 1022 // Destructor 1023 ~Mutex(); 1024 1025 // Block if necessary until this Mutex is free, then acquire it exclusively. 1026 void Lock(); 1027 1028 // Release this Mutex. Caller must hold it exclusively. 1029 void Unlock(); 1030 1031 // Crash if this Mutex is not held exclusively by this thread. 1032 // May fail to crash when it should; will never crash when it should not. 1033 void AssertHeld(); 1034 1035 private: 1036 struct Internal; 1037 Internal* mInternal; 1038 1039 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex); 1040}; 1041 1042// MutexLock(mu) acquires mu when constructed and releases it when destroyed. 1043class LIBPROTOBUF_EXPORT MutexLock { 1044 public: 1045 explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); } 1046 ~MutexLock() { this->mu_->Unlock(); } 1047 private: 1048 Mutex *const mu_; 1049 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock); 1050}; 1051 1052// TODO(kenton): Implement these? Hard to implement portably. 1053typedef MutexLock ReaderMutexLock; 1054typedef MutexLock WriterMutexLock; 1055 1056// MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL. 1057class LIBPROTOBUF_EXPORT MutexLockMaybe { 1058 public: 1059 explicit MutexLockMaybe(Mutex *mu) : 1060 mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } } 1061 ~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } } 1062 private: 1063 Mutex *const mu_; 1064 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe); 1065}; 1066 1067} // namespace internal 1068 1069// We made these internal so that they would show up as such in the docs, 1070// but we don't want to stick "internal::" in front of them everywhere. 1071using internal::Mutex; 1072using internal::MutexLock; 1073using internal::ReaderMutexLock; 1074using internal::WriterMutexLock; 1075using internal::MutexLockMaybe; 1076 1077// =================================================================== 1078// from google3/base/type_traits.h 1079 1080namespace internal { 1081 1082// Specified by TR1 [4.7.4] Pointer modifications. 1083template<typename T> struct remove_pointer { typedef T type; }; 1084template<typename T> struct remove_pointer<T*> { typedef T type; }; 1085template<typename T> struct remove_pointer<T* const> { typedef T type; }; 1086template<typename T> struct remove_pointer<T* volatile> { typedef T type; }; 1087template<typename T> struct remove_pointer<T* const volatile> { 1088 typedef T type; }; 1089 1090// =================================================================== 1091 1092// Checks if the buffer contains structurally-valid UTF-8. Implemented in 1093// structurally_valid.cc. 1094LIBPROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len); 1095 1096} // namespace internal 1097 1098// =================================================================== 1099// Shutdown support. 1100 1101// Shut down the entire protocol buffers library, deleting all static-duration 1102// objects allocated by the library or by generated .pb.cc files. 1103// 1104// There are two reasons you might want to call this: 1105// * You use a draconian definition of "memory leak" in which you expect 1106// every single malloc() to have a corresponding free(), even for objects 1107// which live until program exit. 1108// * You are writing a dynamically-loaded library which needs to clean up 1109// after itself when the library is unloaded. 1110// 1111// It is safe to call this multiple times. However, it is not safe to use 1112// any other part of the protocol buffers library after 1113// ShutdownProtobufLibrary() has been called. 1114LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary(); 1115 1116namespace internal { 1117 1118// Register a function to be called when ShutdownProtocolBuffers() is called. 1119LIBPROTOBUF_EXPORT void OnShutdown(void (*func)()); 1120 1121} // namespace internal 1122 1123} // namespace protobuf 1124} // namespace google 1125 1126#endif // GOOGLE_PROTOBUF_COMMON_H__ 1127