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 2003000 87 88// The minimum library version which works with the current version of the 89// headers. 90#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 2003000 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 = 2003000; 96 97// The minimum protoc version which works with the current version of the 98// headers. 99#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 2003000 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 = 2003000; 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// ------------------------------------------------------------------- 175// Annotations: Some parts of the code have been annotated in ways that might 176// be useful to some compilers or tools, but are not supported universally. 177// You can #define these annotations yourself if the default implementation 178// is not right for you. 179 180#ifndef GOOGLE_ATTRIBUTE_ALWAYS_INLINE 181#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) 182// For functions we want to force inline. 183// Introduced in gcc 3.1. 184#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline)) 185#else 186// Other compilers will have to figure it out for themselves. 187#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE 188#endif 189#endif 190 191#ifndef GOOGLE_ATTRIBUTE_DEPRECATED 192#ifdef __GNUC__ 193// If the method/variable/type is used anywhere, produce a warning. 194#define GOOGLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated)) 195#else 196#define GOOGLE_ATTRIBUTE_DEPRECATED 197#endif 198#endif 199 200#ifndef GOOGLE_PREDICT_TRUE 201#ifdef __GNUC__ 202// Provided at least since GCC 3.0. 203#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) 204#else 205#define GOOGLE_PREDICT_TRUE 206#endif 207#endif 208 209// Delimits a block of code which may write to memory which is simultaneously 210// written by other threads, but which has been determined to be thread-safe 211// (e.g. because it is an idempotent write). 212#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN 213#define GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN() 214#endif 215#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_END 216#define GOOGLE_SAFE_CONCURRENT_WRITES_END() 217#endif 218 219// =================================================================== 220// from google3/base/basictypes.h 221 222// The GOOGLE_ARRAYSIZE(arr) macro returns the # of elements in an array arr. 223// The expression is a compile-time constant, and therefore can be 224// used in defining new arrays, for example. 225// 226// GOOGLE_ARRAYSIZE catches a few type errors. If you see a compiler error 227// 228// "warning: division by zero in ..." 229// 230// when using GOOGLE_ARRAYSIZE, you are (wrongfully) giving it a pointer. 231// You should only use GOOGLE_ARRAYSIZE on statically allocated arrays. 232// 233// The following comments are on the implementation details, and can 234// be ignored by the users. 235// 236// ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in 237// the array) and sizeof(*(arr)) (the # of bytes in one array 238// element). If the former is divisible by the latter, perhaps arr is 239// indeed an array, in which case the division result is the # of 240// elements in the array. Otherwise, arr cannot possibly be an array, 241// and we generate a compiler error to prevent the code from 242// compiling. 243// 244// Since the size of bool is implementation-defined, we need to cast 245// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final 246// result has type size_t. 247// 248// This macro is not perfect as it wrongfully accepts certain 249// pointers, namely where the pointer size is divisible by the pointee 250// size. Since all our code has to go through a 32-bit compiler, 251// where a pointer is 4 bytes, this means all pointers to a type whose 252// size is 3 or greater than 4 will be (righteously) rejected. 253// 254// Kudos to Jorg Brown for this simple and elegant implementation. 255 256#undef GOOGLE_ARRAYSIZE 257#define GOOGLE_ARRAYSIZE(a) \ 258 ((sizeof(a) / sizeof(*(a))) / \ 259 static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) 260 261namespace internal { 262 263// Use implicit_cast as a safe version of static_cast or const_cast 264// for upcasting in the type hierarchy (i.e. casting a pointer to Foo 265// to a pointer to SuperclassOfFoo or casting a pointer to Foo to 266// a const pointer to Foo). 267// When you use implicit_cast, the compiler checks that the cast is safe. 268// Such explicit implicit_casts are necessary in surprisingly many 269// situations where C++ demands an exact type match instead of an 270// argument type convertable to a target type. 271// 272// The From type can be inferred, so the preferred syntax for using 273// implicit_cast is the same as for static_cast etc.: 274// 275// implicit_cast<ToType>(expr) 276// 277// implicit_cast would have been part of the C++ standard library, 278// but the proposal was submitted too late. It will probably make 279// its way into the language in the future. 280template<typename To, typename From> 281inline To implicit_cast(From const &f) { 282 return f; 283} 284 285// When you upcast (that is, cast a pointer from type Foo to type 286// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts 287// always succeed. When you downcast (that is, cast a pointer from 288// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because 289// how do you know the pointer is really of type SubclassOfFoo? It 290// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, 291// when you downcast, you should use this macro. In debug mode, we 292// use dynamic_cast<> to double-check the downcast is legal (we die 293// if it's not). In normal mode, we do the efficient static_cast<> 294// instead. Thus, it's important to test in debug mode to make sure 295// the cast is legal! 296// This is the only place in the code we should use dynamic_cast<>. 297// In particular, you SHOULDN'T be using dynamic_cast<> in order to 298// do RTTI (eg code like this: 299// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); 300// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); 301// You should design the code some other way not to need this. 302 303template<typename To, typename From> // use like this: down_cast<T*>(foo); 304inline To down_cast(From* f) { // so we only accept pointers 305 // Ensures that To is a sub-type of From *. This test is here only 306 // for compile-time type checking, and has no overhead in an 307 // optimized build at run-time, as it will be optimized away 308 // completely. 309 if (false) { 310 implicit_cast<From*, To>(0); 311 } 312 313#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI) 314 assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only! 315#endif 316 return static_cast<To>(f); 317} 318 319} // namespace internal 320 321// We made these internal so that they would show up as such in the docs, 322// but we don't want to stick "internal::" in front of them everywhere. 323using internal::implicit_cast; 324using internal::down_cast; 325 326// The COMPILE_ASSERT macro can be used to verify that a compile time 327// expression is true. For example, you could use it to verify the 328// size of a static array: 329// 330// COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, 331// content_type_names_incorrect_size); 332// 333// or to make sure a struct is smaller than a certain size: 334// 335// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); 336// 337// The second argument to the macro is the name of the variable. If 338// the expression is false, most compilers will issue a warning/error 339// containing the name of the variable. 340 341namespace internal { 342 343template <bool> 344struct CompileAssert { 345}; 346 347} // namespace internal 348 349#undef GOOGLE_COMPILE_ASSERT 350#define GOOGLE_COMPILE_ASSERT(expr, msg) \ 351 typedef ::google::protobuf::internal::CompileAssert<(bool(expr))> \ 352 msg[bool(expr) ? 1 : -1] 353 354// Implementation details of COMPILE_ASSERT: 355// 356// - COMPILE_ASSERT works by defining an array type that has -1 357// elements (and thus is invalid) when the expression is false. 358// 359// - The simpler definition 360// 361// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] 362// 363// does not work, as gcc supports variable-length arrays whose sizes 364// are determined at run-time (this is gcc's extension and not part 365// of the C++ standard). As a result, gcc fails to reject the 366// following code with the simple definition: 367// 368// int foo; 369// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is 370// // not a compile-time constant. 371// 372// - By using the type CompileAssert<(bool(expr))>, we ensures that 373// expr is a compile-time constant. (Template arguments must be 374// determined at compile-time.) 375// 376// - The outter parentheses in CompileAssert<(bool(expr))> are necessary 377// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written 378// 379// CompileAssert<bool(expr)> 380// 381// instead, these compilers will refuse to compile 382// 383// COMPILE_ASSERT(5 > 0, some_message); 384// 385// (They seem to think the ">" in "5 > 0" marks the end of the 386// template argument list.) 387// 388// - The array size is (bool(expr) ? 1 : -1), instead of simply 389// 390// ((expr) ? 1 : -1). 391// 392// This is to avoid running into a bug in MS VC 7.1, which 393// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. 394 395// =================================================================== 396// from google3/base/scoped_ptr.h 397 398namespace internal { 399 400// This is an implementation designed to match the anticipated future TR2 401// implementation of the scoped_ptr class, and its closely-related brethren, 402// scoped_array, scoped_ptr_malloc, and make_scoped_ptr. 403 404template <class C> class scoped_ptr; 405template <class C> class scoped_array; 406 407// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T> 408// automatically deletes the pointer it holds (if any). 409// That is, scoped_ptr<T> owns the T object that it points to. 410// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object. 411// 412// The size of a scoped_ptr is small: 413// sizeof(scoped_ptr<C>) == sizeof(C*) 414template <class C> 415class scoped_ptr { 416 public: 417 418 // The element type 419 typedef C element_type; 420 421 // Constructor. Defaults to intializing with NULL. 422 // There is no way to create an uninitialized scoped_ptr. 423 // The input parameter must be allocated with new. 424 explicit scoped_ptr(C* p = NULL) : ptr_(p) { } 425 426 // Destructor. If there is a C object, delete it. 427 // We don't need to test ptr_ == NULL because C++ does that for us. 428 ~scoped_ptr() { 429 enum { type_must_be_complete = sizeof(C) }; 430 delete ptr_; 431 } 432 433 // Reset. Deletes the current owned object, if any. 434 // Then takes ownership of a new object, if given. 435 // this->reset(this->get()) works. 436 void reset(C* p = NULL) { 437 if (p != ptr_) { 438 enum { type_must_be_complete = sizeof(C) }; 439 delete ptr_; 440 ptr_ = p; 441 } 442 } 443 444 // Accessors to get the owned object. 445 // operator* and operator-> will assert() if there is no current object. 446 C& operator*() const { 447 assert(ptr_ != NULL); 448 return *ptr_; 449 } 450 C* operator->() const { 451 assert(ptr_ != NULL); 452 return ptr_; 453 } 454 C* get() const { return ptr_; } 455 456 // Comparison operators. 457 // These return whether two scoped_ptr refer to the same object, not just to 458 // two different but equal objects. 459 bool operator==(C* p) const { return ptr_ == p; } 460 bool operator!=(C* p) const { return ptr_ != p; } 461 462 // Swap two scoped pointers. 463 void swap(scoped_ptr& p2) { 464 C* tmp = ptr_; 465 ptr_ = p2.ptr_; 466 p2.ptr_ = tmp; 467 } 468 469 // Release a pointer. 470 // The return value is the current pointer held by this object. 471 // If this object holds a NULL pointer, the return value is NULL. 472 // After this operation, this object will hold a NULL pointer, 473 // and will not own the object any more. 474 C* release() { 475 C* retVal = ptr_; 476 ptr_ = NULL; 477 return retVal; 478 } 479 480 private: 481 C* ptr_; 482 483 // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't 484 // make sense, and if C2 == C, it still doesn't make sense because you should 485 // never have the same object owned by two different scoped_ptrs. 486 template <class C2> bool operator==(scoped_ptr<C2> const& p2) const; 487 template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const; 488 489 // Disallow evil constructors 490 scoped_ptr(const scoped_ptr&); 491 void operator=(const scoped_ptr&); 492}; 493 494// scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate 495// with new [] and the destructor deletes objects with delete []. 496// 497// As with scoped_ptr<C>, a scoped_array<C> either points to an object 498// or is NULL. A scoped_array<C> owns the object that it points to. 499// 500// Size: sizeof(scoped_array<C>) == sizeof(C*) 501template <class C> 502class scoped_array { 503 public: 504 505 // The element type 506 typedef C element_type; 507 508 // Constructor. Defaults to intializing with NULL. 509 // There is no way to create an uninitialized scoped_array. 510 // The input parameter must be allocated with new []. 511 explicit scoped_array(C* p = NULL) : array_(p) { } 512 513 // Destructor. If there is a C object, delete it. 514 // We don't need to test ptr_ == NULL because C++ does that for us. 515 ~scoped_array() { 516 enum { type_must_be_complete = sizeof(C) }; 517 delete[] array_; 518 } 519 520 // Reset. Deletes the current owned object, if any. 521 // Then takes ownership of a new object, if given. 522 // this->reset(this->get()) works. 523 void reset(C* p = NULL) { 524 if (p != array_) { 525 enum { type_must_be_complete = sizeof(C) }; 526 delete[] array_; 527 array_ = p; 528 } 529 } 530 531 // Get one element of the current object. 532 // Will assert() if there is no current object, or index i is negative. 533 C& operator[](std::ptrdiff_t i) const { 534 assert(i >= 0); 535 assert(array_ != NULL); 536 return array_[i]; 537 } 538 539 // Get a pointer to the zeroth element of the current object. 540 // If there is no current object, return NULL. 541 C* get() const { 542 return array_; 543 } 544 545 // Comparison operators. 546 // These return whether two scoped_array refer to the same object, not just to 547 // two different but equal objects. 548 bool operator==(C* p) const { return array_ == p; } 549 bool operator!=(C* p) const { return array_ != p; } 550 551 // Swap two scoped arrays. 552 void swap(scoped_array& p2) { 553 C* tmp = array_; 554 array_ = p2.array_; 555 p2.array_ = tmp; 556 } 557 558 // Release an array. 559 // The return value is the current pointer held by this object. 560 // If this object holds a NULL pointer, the return value is NULL. 561 // After this operation, this object will hold a NULL pointer, 562 // and will not own the object any more. 563 C* release() { 564 C* retVal = array_; 565 array_ = NULL; 566 return retVal; 567 } 568 569 private: 570 C* array_; 571 572 // Forbid comparison of different scoped_array types. 573 template <class C2> bool operator==(scoped_array<C2> const& p2) const; 574 template <class C2> bool operator!=(scoped_array<C2> const& p2) const; 575 576 // Disallow evil constructors 577 scoped_array(const scoped_array&); 578 void operator=(const scoped_array&); 579}; 580 581} // namespace internal 582 583// We made these internal so that they would show up as such in the docs, 584// but we don't want to stick "internal::" in front of them everywhere. 585using internal::scoped_ptr; 586using internal::scoped_array; 587 588// =================================================================== 589// emulates google3/base/logging.h 590 591enum LogLevel { 592 LOGLEVEL_INFO, // Informational. This is never actually used by 593 // libprotobuf. 594 LOGLEVEL_WARNING, // Warns about issues that, although not technically a 595 // problem now, could cause problems in the future. For 596 // example, a // warning will be printed when parsing a 597 // message that is near the message size limit. 598 LOGLEVEL_ERROR, // An error occurred which should never happen during 599 // normal use. 600 LOGLEVEL_FATAL, // An error occurred from which the library cannot 601 // recover. This usually indicates a programming error 602 // in the code which calls the library, especially when 603 // compiled in debug mode. 604 605#ifdef NDEBUG 606 LOGLEVEL_DFATAL = LOGLEVEL_ERROR 607#else 608 LOGLEVEL_DFATAL = LOGLEVEL_FATAL 609#endif 610}; 611 612namespace internal { 613 614class LogFinisher; 615 616class LIBPROTOBUF_EXPORT LogMessage { 617 public: 618 LogMessage(LogLevel level, const char* filename, int line); 619 ~LogMessage(); 620 621 LogMessage& operator<<(const string& value); 622 LogMessage& operator<<(const char* value); 623 LogMessage& operator<<(char value); 624 LogMessage& operator<<(int value); 625 LogMessage& operator<<(uint value); 626 LogMessage& operator<<(long value); 627 LogMessage& operator<<(unsigned long value); 628 LogMessage& operator<<(double value); 629 630 private: 631 friend class LogFinisher; 632 void Finish(); 633 634 LogLevel level_; 635 const char* filename_; 636 int line_; 637 string message_; 638}; 639 640// Used to make the entire "LOG(BLAH) << etc." expression have a void return 641// type and print a newline after each message. 642class LIBPROTOBUF_EXPORT LogFinisher { 643 public: 644 void operator=(LogMessage& other); 645}; 646 647} // namespace internal 648 649// Undef everything in case we're being mixed with some other Google library 650// which already defined them itself. Presumably all Google libraries will 651// support the same syntax for these so it should not be a big deal if they 652// end up using our definitions instead. 653#undef GOOGLE_LOG 654#undef GOOGLE_LOG_IF 655 656#undef GOOGLE_CHECK 657#undef GOOGLE_CHECK_EQ 658#undef GOOGLE_CHECK_NE 659#undef GOOGLE_CHECK_LT 660#undef GOOGLE_CHECK_LE 661#undef GOOGLE_CHECK_GT 662#undef GOOGLE_CHECK_GE 663 664#undef GOOGLE_DLOG 665#undef GOOGLE_DCHECK 666#undef GOOGLE_DCHECK_EQ 667#undef GOOGLE_DCHECK_NE 668#undef GOOGLE_DCHECK_LT 669#undef GOOGLE_DCHECK_LE 670#undef GOOGLE_DCHECK_GT 671#undef GOOGLE_DCHECK_GE 672 673#define GOOGLE_LOG(LEVEL) \ 674 ::google::protobuf::internal::LogFinisher() = \ 675 ::google::protobuf::internal::LogMessage( \ 676 ::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__) 677#define GOOGLE_LOG_IF(LEVEL, CONDITION) \ 678 !(CONDITION) ? (void)0 : GOOGLE_LOG(LEVEL) 679 680#define GOOGLE_CHECK(EXPRESSION) \ 681 GOOGLE_LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": " 682#define GOOGLE_CHECK_EQ(A, B) GOOGLE_CHECK((A) == (B)) 683#define GOOGLE_CHECK_NE(A, B) GOOGLE_CHECK((A) != (B)) 684#define GOOGLE_CHECK_LT(A, B) GOOGLE_CHECK((A) < (B)) 685#define GOOGLE_CHECK_LE(A, B) GOOGLE_CHECK((A) <= (B)) 686#define GOOGLE_CHECK_GT(A, B) GOOGLE_CHECK((A) > (B)) 687#define GOOGLE_CHECK_GE(A, B) GOOGLE_CHECK((A) >= (B)) 688 689#ifdef NDEBUG 690 691#define GOOGLE_DLOG GOOGLE_LOG_IF(INFO, false) 692 693#define GOOGLE_DCHECK(EXPRESSION) while(false) GOOGLE_CHECK(EXPRESSION) 694#define GOOGLE_DCHECK_EQ(A, B) GOOGLE_DCHECK((A) == (B)) 695#define GOOGLE_DCHECK_NE(A, B) GOOGLE_DCHECK((A) != (B)) 696#define GOOGLE_DCHECK_LT(A, B) GOOGLE_DCHECK((A) < (B)) 697#define GOOGLE_DCHECK_LE(A, B) GOOGLE_DCHECK((A) <= (B)) 698#define GOOGLE_DCHECK_GT(A, B) GOOGLE_DCHECK((A) > (B)) 699#define GOOGLE_DCHECK_GE(A, B) GOOGLE_DCHECK((A) >= (B)) 700 701#else // NDEBUG 702 703#define GOOGLE_DLOG GOOGLE_LOG 704 705#define GOOGLE_DCHECK GOOGLE_CHECK 706#define GOOGLE_DCHECK_EQ GOOGLE_CHECK_EQ 707#define GOOGLE_DCHECK_NE GOOGLE_CHECK_NE 708#define GOOGLE_DCHECK_LT GOOGLE_CHECK_LT 709#define GOOGLE_DCHECK_LE GOOGLE_CHECK_LE 710#define GOOGLE_DCHECK_GT GOOGLE_CHECK_GT 711#define GOOGLE_DCHECK_GE GOOGLE_CHECK_GE 712 713#endif // !NDEBUG 714 715typedef void LogHandler(LogLevel level, const char* filename, int line, 716 const string& message); 717 718// The protobuf library sometimes writes warning and error messages to 719// stderr. These messages are primarily useful for developers, but may 720// also help end users figure out a problem. If you would prefer that 721// these messages be sent somewhere other than stderr, call SetLogHandler() 722// to set your own handler. This returns the old handler. Set the handler 723// to NULL to ignore log messages (but see also LogSilencer, below). 724// 725// Obviously, SetLogHandler is not thread-safe. You should only call it 726// at initialization time, and probably not from library code. If you 727// simply want to suppress log messages temporarily (e.g. because you 728// have some code that tends to trigger them frequently and you know 729// the warnings are not important to you), use the LogSilencer class 730// below. 731LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func); 732 733// Create a LogSilencer if you want to temporarily suppress all log 734// messages. As long as any LogSilencer objects exist, non-fatal 735// log messages will be discarded (the current LogHandler will *not* 736// be called). Constructing a LogSilencer is thread-safe. You may 737// accidentally suppress log messages occurring in another thread, but 738// since messages are generally for debugging purposes only, this isn't 739// a big deal. If you want to intercept log messages, use SetLogHandler(). 740class LIBPROTOBUF_EXPORT LogSilencer { 741 public: 742 LogSilencer(); 743 ~LogSilencer(); 744}; 745 746// =================================================================== 747// emulates google3/base/callback.h 748 749// Abstract interface for a callback. When calling an RPC, you must provide 750// a Closure to call when the procedure completes. See the Service interface 751// in service.h. 752// 753// To automatically construct a Closure which calls a particular function or 754// method with a particular set of parameters, use the NewCallback() function. 755// Example: 756// void FooDone(const FooResponse* response) { 757// ... 758// } 759// 760// void CallFoo() { 761// ... 762// // When done, call FooDone() and pass it a pointer to the response. 763// Closure* callback = NewCallback(&FooDone, response); 764// // Make the call. 765// service->Foo(controller, request, response, callback); 766// } 767// 768// Example that calls a method: 769// class Handler { 770// public: 771// ... 772// 773// void FooDone(const FooResponse* response) { 774// ... 775// } 776// 777// void CallFoo() { 778// ... 779// // When done, call FooDone() and pass it a pointer to the response. 780// Closure* callback = NewCallback(this, &Handler::FooDone, response); 781// // Make the call. 782// service->Foo(controller, request, response, callback); 783// } 784// }; 785// 786// Currently NewCallback() supports binding zero, one, or two arguments. 787// 788// Callbacks created with NewCallback() automatically delete themselves when 789// executed. They should be used when a callback is to be called exactly 790// once (usually the case with RPC callbacks). If a callback may be called 791// a different number of times (including zero), create it with 792// NewPermanentCallback() instead. You are then responsible for deleting the 793// callback (using the "delete" keyword as normal). 794// 795// Note that NewCallback() is a bit touchy regarding argument types. Generally, 796// the values you provide for the parameter bindings must exactly match the 797// types accepted by the callback function. For example: 798// void Foo(string s); 799// NewCallback(&Foo, "foo"); // WON'T WORK: const char* != string 800// NewCallback(&Foo, string("foo")); // WORKS 801// Also note that the arguments cannot be references: 802// void Foo(const string& s); 803// string my_str; 804// NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes. 805// However, correctly-typed pointers will work just fine. 806class LIBPROTOBUF_EXPORT Closure { 807 public: 808 Closure() {} 809 virtual ~Closure(); 810 811 virtual void Run() = 0; 812 813 private: 814 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Closure); 815}; 816 817namespace internal { 818 819class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure { 820 public: 821 typedef void (*FunctionType)(); 822 823 FunctionClosure0(FunctionType function, bool self_deleting) 824 : function_(function), self_deleting_(self_deleting) {} 825 ~FunctionClosure0(); 826 827 void Run() { 828 function_(); 829 if (self_deleting_) delete this; 830 } 831 832 private: 833 FunctionType function_; 834 bool self_deleting_; 835}; 836 837template <typename Class> 838class MethodClosure0 : public Closure { 839 public: 840 typedef void (Class::*MethodType)(); 841 842 MethodClosure0(Class* object, MethodType method, bool self_deleting) 843 : object_(object), method_(method), self_deleting_(self_deleting) {} 844 ~MethodClosure0() {} 845 846 void Run() { 847 (object_->*method_)(); 848 if (self_deleting_) delete this; 849 } 850 851 private: 852 Class* object_; 853 MethodType method_; 854 bool self_deleting_; 855}; 856 857template <typename Arg1> 858class FunctionClosure1 : public Closure { 859 public: 860 typedef void (*FunctionType)(Arg1 arg1); 861 862 FunctionClosure1(FunctionType function, bool self_deleting, 863 Arg1 arg1) 864 : function_(function), self_deleting_(self_deleting), 865 arg1_(arg1) {} 866 ~FunctionClosure1() {} 867 868 void Run() { 869 function_(arg1_); 870 if (self_deleting_) delete this; 871 } 872 873 private: 874 FunctionType function_; 875 bool self_deleting_; 876 Arg1 arg1_; 877}; 878 879template <typename Class, typename Arg1> 880class MethodClosure1 : public Closure { 881 public: 882 typedef void (Class::*MethodType)(Arg1 arg1); 883 884 MethodClosure1(Class* object, MethodType method, bool self_deleting, 885 Arg1 arg1) 886 : object_(object), method_(method), self_deleting_(self_deleting), 887 arg1_(arg1) {} 888 ~MethodClosure1() {} 889 890 void Run() { 891 (object_->*method_)(arg1_); 892 if (self_deleting_) delete this; 893 } 894 895 private: 896 Class* object_; 897 MethodType method_; 898 bool self_deleting_; 899 Arg1 arg1_; 900}; 901 902template <typename Arg1, typename Arg2> 903class FunctionClosure2 : public Closure { 904 public: 905 typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2); 906 907 FunctionClosure2(FunctionType function, bool self_deleting, 908 Arg1 arg1, Arg2 arg2) 909 : function_(function), self_deleting_(self_deleting), 910 arg1_(arg1), arg2_(arg2) {} 911 ~FunctionClosure2() {} 912 913 void Run() { 914 function_(arg1_, arg2_); 915 if (self_deleting_) delete this; 916 } 917 918 private: 919 FunctionType function_; 920 bool self_deleting_; 921 Arg1 arg1_; 922 Arg2 arg2_; 923}; 924 925template <typename Class, typename Arg1, typename Arg2> 926class MethodClosure2 : public Closure { 927 public: 928 typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2); 929 930 MethodClosure2(Class* object, MethodType method, bool self_deleting, 931 Arg1 arg1, Arg2 arg2) 932 : object_(object), method_(method), self_deleting_(self_deleting), 933 arg1_(arg1), arg2_(arg2) {} 934 ~MethodClosure2() {} 935 936 void Run() { 937 (object_->*method_)(arg1_, arg2_); 938 if (self_deleting_) delete this; 939 } 940 941 private: 942 Class* object_; 943 MethodType method_; 944 bool self_deleting_; 945 Arg1 arg1_; 946 Arg2 arg2_; 947}; 948 949} // namespace internal 950 951// See Closure. 952inline Closure* NewCallback(void (*function)()) { 953 return new internal::FunctionClosure0(function, true); 954} 955 956// See Closure. 957inline Closure* NewPermanentCallback(void (*function)()) { 958 return new internal::FunctionClosure0(function, false); 959} 960 961// See Closure. 962template <typename Class> 963inline Closure* NewCallback(Class* object, void (Class::*method)()) { 964 return new internal::MethodClosure0<Class>(object, method, true); 965} 966 967// See Closure. 968template <typename Class> 969inline Closure* NewPermanentCallback(Class* object, void (Class::*method)()) { 970 return new internal::MethodClosure0<Class>(object, method, false); 971} 972 973// See Closure. 974template <typename Arg1> 975inline Closure* NewCallback(void (*function)(Arg1), 976 Arg1 arg1) { 977 return new internal::FunctionClosure1<Arg1>(function, true, arg1); 978} 979 980// See Closure. 981template <typename Arg1> 982inline Closure* NewPermanentCallback(void (*function)(Arg1), 983 Arg1 arg1) { 984 return new internal::FunctionClosure1<Arg1>(function, false, arg1); 985} 986 987// See Closure. 988template <typename Class, typename Arg1> 989inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1), 990 Arg1 arg1) { 991 return new internal::MethodClosure1<Class, Arg1>(object, method, true, arg1); 992} 993 994// See Closure. 995template <typename Class, typename Arg1> 996inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(Arg1), 997 Arg1 arg1) { 998 return new internal::MethodClosure1<Class, Arg1>(object, method, false, arg1); 999} 1000 1001// See Closure. 1002template <typename Arg1, typename Arg2> 1003inline Closure* NewCallback(void (*function)(Arg1, Arg2), 1004 Arg1 arg1, Arg2 arg2) { 1005 return new internal::FunctionClosure2<Arg1, Arg2>( 1006 function, true, arg1, arg2); 1007} 1008 1009// See Closure. 1010template <typename Arg1, typename Arg2> 1011inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2), 1012 Arg1 arg1, Arg2 arg2) { 1013 return new internal::FunctionClosure2<Arg1, Arg2>( 1014 function, false, arg1, arg2); 1015} 1016 1017// See Closure. 1018template <typename Class, typename Arg1, typename Arg2> 1019inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, Arg2), 1020 Arg1 arg1, Arg2 arg2) { 1021 return new internal::MethodClosure2<Class, Arg1, Arg2>( 1022 object, method, true, arg1, arg2); 1023} 1024 1025// See Closure. 1026template <typename Class, typename Arg1, typename Arg2> 1027inline Closure* NewPermanentCallback( 1028 Class* object, void (Class::*method)(Arg1, Arg2), 1029 Arg1 arg1, Arg2 arg2) { 1030 return new internal::MethodClosure2<Class, Arg1, Arg2>( 1031 object, method, false, arg1, arg2); 1032} 1033 1034// A function which does nothing. Useful for creating no-op callbacks, e.g.: 1035// Closure* nothing = NewCallback(&DoNothing); 1036void LIBPROTOBUF_EXPORT DoNothing(); 1037 1038// =================================================================== 1039// emulates google3/base/mutex.h 1040 1041namespace internal { 1042 1043// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T 1044// may hold a mutex at a given time. If T attempts to Lock() the same Mutex 1045// while holding it, T will deadlock. 1046class LIBPROTOBUF_EXPORT Mutex { 1047 public: 1048 // Create a Mutex that is not held by anybody. 1049 Mutex(); 1050 1051 // Destructor 1052 ~Mutex(); 1053 1054 // Block if necessary until this Mutex is free, then acquire it exclusively. 1055 void Lock(); 1056 1057 // Release this Mutex. Caller must hold it exclusively. 1058 void Unlock(); 1059 1060 // Crash if this Mutex is not held exclusively by this thread. 1061 // May fail to crash when it should; will never crash when it should not. 1062 void AssertHeld(); 1063 1064 private: 1065 struct Internal; 1066 Internal* mInternal; 1067 1068 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex); 1069}; 1070 1071// MutexLock(mu) acquires mu when constructed and releases it when destroyed. 1072class LIBPROTOBUF_EXPORT MutexLock { 1073 public: 1074 explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); } 1075 ~MutexLock() { this->mu_->Unlock(); } 1076 private: 1077 Mutex *const mu_; 1078 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock); 1079}; 1080 1081// TODO(kenton): Implement these? Hard to implement portably. 1082typedef MutexLock ReaderMutexLock; 1083typedef MutexLock WriterMutexLock; 1084 1085// MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL. 1086class LIBPROTOBUF_EXPORT MutexLockMaybe { 1087 public: 1088 explicit MutexLockMaybe(Mutex *mu) : 1089 mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } } 1090 ~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } } 1091 private: 1092 Mutex *const mu_; 1093 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe); 1094}; 1095 1096} // namespace internal 1097 1098// We made these internal so that they would show up as such in the docs, 1099// but we don't want to stick "internal::" in front of them everywhere. 1100using internal::Mutex; 1101using internal::MutexLock; 1102using internal::ReaderMutexLock; 1103using internal::WriterMutexLock; 1104using internal::MutexLockMaybe; 1105 1106// =================================================================== 1107// from google3/base/type_traits.h 1108 1109namespace internal { 1110 1111// Specified by TR1 [4.7.4] Pointer modifications. 1112template<typename T> struct remove_pointer { typedef T type; }; 1113template<typename T> struct remove_pointer<T*> { typedef T type; }; 1114template<typename T> struct remove_pointer<T* const> { typedef T type; }; 1115template<typename T> struct remove_pointer<T* volatile> { typedef T type; }; 1116template<typename T> struct remove_pointer<T* const volatile> { 1117 typedef T type; }; 1118 1119// =================================================================== 1120 1121// Checks if the buffer contains structurally-valid UTF-8. Implemented in 1122// structurally_valid.cc. 1123LIBPROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len); 1124 1125} // namespace internal 1126 1127// =================================================================== 1128// Shutdown support. 1129 1130// Shut down the entire protocol buffers library, deleting all static-duration 1131// objects allocated by the library or by generated .pb.cc files. 1132// 1133// There are two reasons you might want to call this: 1134// * You use a draconian definition of "memory leak" in which you expect 1135// every single malloc() to have a corresponding free(), even for objects 1136// which live until program exit. 1137// * You are writing a dynamically-loaded library which needs to clean up 1138// after itself when the library is unloaded. 1139// 1140// It is safe to call this multiple times. However, it is not safe to use 1141// any other part of the protocol buffers library after 1142// ShutdownProtobufLibrary() has been called. 1143LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary(); 1144 1145namespace internal { 1146 1147// Register a function to be called when ShutdownProtocolBuffers() is called. 1148LIBPROTOBUF_EXPORT void OnShutdown(void (*func)()); 1149 1150} // namespace internal 1151 1152} // namespace protobuf 1153} // namespace google 1154 1155#endif // GOOGLE_PROTOBUF_COMMON_H__ 1156