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