Initial import of v2.0.0beta
[protobuf.git] / src / google / protobuf / stubs / common.h
blob189909fd26c9db9a4b38290c56296ea2066097a2
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.
3 // http://code.google.com/p/protobuf/
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
17 // Author: kenton@google.com (Kenton Varda) and others
19 // Contains basic types and utilities used by the rest of the library.
21 #ifndef GOOGLE_PROTOBUF_COMMON_H__
22 #define GOOGLE_PROTOBUF_COMMON_H__
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <cstddef>
27 #include <string>
28 #include <string.h>
29 #ifndef _MSC_VER
30 #include <stdint.h>
31 #endif
33 namespace std {}
35 namespace google {
36 namespace protobuf {
38 using namespace std; // Don't do this at home, kids.
40 #undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS
41 #define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName) \
42 TypeName(const TypeName&); \
43 void operator=(const TypeName&)
45 #ifdef _MSC_VER
46 #ifdef LIBPROTOBUF_EXPORTS
47 #define LIBPROTOBUF_EXPORT __declspec(dllexport)
48 #else
49 #define LIBPROTOBUF_EXPORT __declspec(dllimport)
50 #endif
51 #ifdef LIBPROTOC_EXPORTS
52 #define LIBPROTOC_EXPORT __declspec(dllexport)
53 #else
54 #define LIBPROTOC_EXPORT __declspec(dllimport)
55 #endif
56 #else
57 #define LIBPROTOBUF_EXPORT
58 #define LIBPROTOC_EXPORT
59 #endif
61 namespace internal {
63 // Some of these constants are macros rather than const ints so that they can
64 // be used in #if directives.
66 // The current version, represented as a single integer to make comparison
67 // easier: major * 10^6 + minor * 10^3 + micro
68 #define GOOGLE_PROTOBUF_VERSION 2000000
70 // The minimum library version which works with the current version of the
71 // headers.
72 #define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 2000000
74 // The minimum header version which works with the current version of
75 // the library. This constant should only be used by protoc's C++ code
76 // generator.
77 static const int kMinHeaderVersionForLibrary = 2000000;
79 // The minimum protoc version which works with the current version of the
80 // headers.
81 #define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 2000000
83 // The minimum header version which works with the current version of
84 // protoc. This constant should only be used in VerifyVersion().
85 static const int kMinHeaderVersionForProtoc = 2000000;
87 // Verifies that the headers and libraries are compatible. Use the macro
88 // below to call this.
89 void LIBPROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion,
90 const char* filename);
92 // Converts a numeric version number to a string.
93 string LIBPROTOBUF_EXPORT VersionString(int version);
95 } // namespace internal
97 // Place this macro in your main() function (or somewhere before you attempt
98 // to use the protobuf library) to verify that the version you link against
99 // matches the headers you compiled against. If a version mismatch is
100 // detected, the process will abort.
101 #define GOOGLE_PROTOBUF_VERIFY_VERSION \
102 ::google::protobuf::internal::VerifyVersion( \
103 GOOGLE_PROTOBUF_VERSION, GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION, \
104 __FILE__)
106 // ===================================================================
107 // from google3/base/port.h
109 typedef unsigned int uint;
111 #ifdef _MSC_VER
112 typedef __int8 int8;
113 typedef __int16 int16;
114 typedef __int32 int32;
115 typedef __int64 int64;
117 typedef unsigned __int8 uint8;
118 typedef unsigned __int16 uint16;
119 typedef unsigned __int32 uint32;
120 typedef unsigned __int64 uint64;
121 #else
122 typedef int8_t int8;
123 typedef int16_t int16;
124 typedef int32_t int32;
125 typedef int64_t int64;
127 typedef uint8_t uint8;
128 typedef uint16_t uint16;
129 typedef uint32_t uint32;
130 typedef uint64_t uint64;
131 #endif
133 // long long macros to be used because gcc and vc++ use different suffixes,
134 // and different size specifiers in format strings
135 #undef GOOGLE_LONGLONG
136 #undef GOOGLE_ULONGLONG
137 #undef GOOGLE_LL_FORMAT
139 #ifdef _MSC_VER
140 #define GOOGLE_LONGLONG(x) x##I64
141 #define GOOGLE_ULONGLONG(x) x##UI64
142 #define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...)
143 #else
144 #define GOOGLE_LONGLONG(x) x##LL
145 #define GOOGLE_ULONGLONG(x) x##ULL
146 #define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also.
147 #endif
149 static const int32 kint32max = 0x7FFFFFFF;
150 static const int32 kint32min = -kint32min - 1;
151 static const int64 kint64max = GOOGLE_LONGLONG(0x7FFFFFFFFFFFFFFF);
152 static const int64 kint64min = -kint64max - 1;
153 static const uint32 kuint32max = 0xFFFFFFFFu;
154 static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
156 #undef GOOGLE_ATTRIBUTE_ALWAYS_INLINE
157 #if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
158 // For functions we want to force inline.
159 // Introduced in gcc 3.1.
160 #define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline))
161 #else
162 // Other compilers will have to figure it out for themselves.
163 #define GOOGLE_ATTRIBUTE_ALWAYS_INLINE
164 #endif
166 // ===================================================================
167 // from google3/base/basictypes.h
169 // The GOOGLE_ARRAYSIZE(arr) macro returns the # of elements in an array arr.
170 // The expression is a compile-time constant, and therefore can be
171 // used in defining new arrays, for example.
173 // GOOGLE_ARRAYSIZE catches a few type errors. If you see a compiler error
175 // "warning: division by zero in ..."
177 // when using GOOGLE_ARRAYSIZE, you are (wrongfully) giving it a pointer.
178 // You should only use GOOGLE_ARRAYSIZE on statically allocated arrays.
180 // The following comments are on the implementation details, and can
181 // be ignored by the users.
183 // ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in
184 // the array) and sizeof(*(arr)) (the # of bytes in one array
185 // element). If the former is divisible by the latter, perhaps arr is
186 // indeed an array, in which case the division result is the # of
187 // elements in the array. Otherwise, arr cannot possibly be an array,
188 // and we generate a compiler error to prevent the code from
189 // compiling.
191 // Since the size of bool is implementation-defined, we need to cast
192 // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
193 // result has type size_t.
195 // This macro is not perfect as it wrongfully accepts certain
196 // pointers, namely where the pointer size is divisible by the pointee
197 // size. Since all our code has to go through a 32-bit compiler,
198 // where a pointer is 4 bytes, this means all pointers to a type whose
199 // size is 3 or greater than 4 will be (righteously) rejected.
201 // Kudos to Jorg Brown for this simple and elegant implementation.
203 #undef GOOGLE_ARRAYSIZE
204 #define GOOGLE_ARRAYSIZE(a) \
205 ((sizeof(a) / sizeof(*(a))) / \
206 static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
208 namespace internal {
210 // Use implicit_cast as a safe version of static_cast or const_cast
211 // for upcasting in the type hierarchy (i.e. casting a pointer to Foo
212 // to a pointer to SuperclassOfFoo or casting a pointer to Foo to
213 // a const pointer to Foo).
214 // When you use implicit_cast, the compiler checks that the cast is safe.
215 // Such explicit implicit_casts are necessary in surprisingly many
216 // situations where C++ demands an exact type match instead of an
217 // argument type convertable to a target type.
219 // The From type can be inferred, so the preferred syntax for using
220 // implicit_cast is the same as for static_cast etc.:
222 // implicit_cast<ToType>(expr)
224 // implicit_cast would have been part of the C++ standard library,
225 // but the proposal was submitted too late. It will probably make
226 // its way into the language in the future.
227 template<typename To, typename From>
228 inline To implicit_cast(From const &f) {
229 return f;
232 // When you upcast (that is, cast a pointer from type Foo to type
233 // SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
234 // always succeed. When you downcast (that is, cast a pointer from
235 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
236 // how do you know the pointer is really of type SubclassOfFoo? It
237 // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
238 // when you downcast, you should use this macro. In debug mode, we
239 // use dynamic_cast<> to double-check the downcast is legal (we die
240 // if it's not). In normal mode, we do the efficient static_cast<>
241 // instead. Thus, it's important to test in debug mode to make sure
242 // the cast is legal!
243 // This is the only place in the code we should use dynamic_cast<>.
244 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
245 // do RTTI (eg code like this:
246 // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
247 // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
248 // You should design the code some other way not to need this.
250 template<typename To, typename From> // use like this: down_cast<T*>(foo);
251 inline To down_cast(From* f) { // so we only accept pointers
252 // Ensures that To is a sub-type of From *. This test is here only
253 // for compile-time type checking, and has no overhead in an
254 // optimized build at run-time, as it will be optimized away
255 // completely.
256 if (false) {
257 implicit_cast<From*, To>(0);
260 assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only!
261 return static_cast<To>(f);
264 } // namespace internal
266 // We made these internal so that they would show up as such in the docs,
267 // but we don't want to stick "internal::" in front of them everywhere.
268 using internal::implicit_cast;
269 using internal::down_cast;
271 // The COMPILE_ASSERT macro can be used to verify that a compile time
272 // expression is true. For example, you could use it to verify the
273 // size of a static array:
275 // COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES,
276 // content_type_names_incorrect_size);
278 // or to make sure a struct is smaller than a certain size:
280 // COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
282 // The second argument to the macro is the name of the variable. If
283 // the expression is false, most compilers will issue a warning/error
284 // containing the name of the variable.
286 namespace internal {
288 template <bool>
289 struct CompileAssert {
292 } // namespace internal
294 #undef GOOGLE_COMPILE_ASSERT
295 #define GOOGLE_COMPILE_ASSERT(expr, msg) \
296 typedef ::google::protobuf::internal::CompileAssert<(bool(expr))> \
297 msg[bool(expr) ? 1 : -1]
299 // Implementation details of COMPILE_ASSERT:
301 // - COMPILE_ASSERT works by defining an array type that has -1
302 // elements (and thus is invalid) when the expression is false.
304 // - The simpler definition
306 // #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
308 // does not work, as gcc supports variable-length arrays whose sizes
309 // are determined at run-time (this is gcc's extension and not part
310 // of the C++ standard). As a result, gcc fails to reject the
311 // following code with the simple definition:
313 // int foo;
314 // COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
315 // // not a compile-time constant.
317 // - By using the type CompileAssert<(bool(expr))>, we ensures that
318 // expr is a compile-time constant. (Template arguments must be
319 // determined at compile-time.)
321 // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
322 // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written
324 // CompileAssert<bool(expr)>
326 // instead, these compilers will refuse to compile
328 // COMPILE_ASSERT(5 > 0, some_message);
330 // (They seem to think the ">" in "5 > 0" marks the end of the
331 // template argument list.)
333 // - The array size is (bool(expr) ? 1 : -1), instead of simply
335 // ((expr) ? 1 : -1).
337 // This is to avoid running into a bug in MS VC 7.1, which
338 // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
340 // ===================================================================
341 // from google3/base/scoped_ptr.h
343 namespace internal {
345 // This is an implementation designed to match the anticipated future TR2
346 // implementation of the scoped_ptr class, and its closely-related brethren,
347 // scoped_array, scoped_ptr_malloc, and make_scoped_ptr.
349 template <class C> class scoped_ptr;
350 template <class C> class scoped_array;
352 // A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
353 // automatically deletes the pointer it holds (if any).
354 // That is, scoped_ptr<T> owns the T object that it points to.
355 // Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
357 // The size of a scoped_ptr is small:
358 // sizeof(scoped_ptr<C>) == sizeof(C*)
359 template <class C>
360 class scoped_ptr {
361 public:
363 // The element type
364 typedef C element_type;
366 // Constructor. Defaults to intializing with NULL.
367 // There is no way to create an uninitialized scoped_ptr.
368 // The input parameter must be allocated with new.
369 explicit scoped_ptr(C* p = NULL) : ptr_(p) { }
371 // Destructor. If there is a C object, delete it.
372 // We don't need to test ptr_ == NULL because C++ does that for us.
373 ~scoped_ptr() {
374 enum { type_must_be_complete = sizeof(C) };
375 delete ptr_;
378 // Reset. Deletes the current owned object, if any.
379 // Then takes ownership of a new object, if given.
380 // this->reset(this->get()) works.
381 void reset(C* p = NULL) {
382 if (p != ptr_) {
383 enum { type_must_be_complete = sizeof(C) };
384 delete ptr_;
385 ptr_ = p;
389 // Accessors to get the owned object.
390 // operator* and operator-> will assert() if there is no current object.
391 C& operator*() const {
392 assert(ptr_ != NULL);
393 return *ptr_;
395 C* operator->() const {
396 assert(ptr_ != NULL);
397 return ptr_;
399 C* get() const { return ptr_; }
401 // Comparison operators.
402 // These return whether two scoped_ptr refer to the same object, not just to
403 // two different but equal objects.
404 bool operator==(C* p) const { return ptr_ == p; }
405 bool operator!=(C* p) const { return ptr_ != p; }
407 // Swap two scoped pointers.
408 void swap(scoped_ptr& p2) {
409 C* tmp = ptr_;
410 ptr_ = p2.ptr_;
411 p2.ptr_ = tmp;
414 // Release a pointer.
415 // The return value is the current pointer held by this object.
416 // If this object holds a NULL pointer, the return value is NULL.
417 // After this operation, this object will hold a NULL pointer,
418 // and will not own the object any more.
419 C* release() {
420 C* retVal = ptr_;
421 ptr_ = NULL;
422 return retVal;
425 private:
426 C* ptr_;
428 // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't
429 // make sense, and if C2 == C, it still doesn't make sense because you should
430 // never have the same object owned by two different scoped_ptrs.
431 template <class C2> bool operator==(scoped_ptr<C2> const& p2) const;
432 template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const;
434 // Disallow evil constructors
435 scoped_ptr(const scoped_ptr&);
436 void operator=(const scoped_ptr&);
439 // scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate
440 // with new [] and the destructor deletes objects with delete [].
442 // As with scoped_ptr<C>, a scoped_array<C> either points to an object
443 // or is NULL. A scoped_array<C> owns the object that it points to.
445 // Size: sizeof(scoped_array<C>) == sizeof(C*)
446 template <class C>
447 class scoped_array {
448 public:
450 // The element type
451 typedef C element_type;
453 // Constructor. Defaults to intializing with NULL.
454 // There is no way to create an uninitialized scoped_array.
455 // The input parameter must be allocated with new [].
456 explicit scoped_array(C* p = NULL) : array_(p) { }
458 // Destructor. If there is a C object, delete it.
459 // We don't need to test ptr_ == NULL because C++ does that for us.
460 ~scoped_array() {
461 enum { type_must_be_complete = sizeof(C) };
462 delete[] array_;
465 // Reset. Deletes the current owned object, if any.
466 // Then takes ownership of a new object, if given.
467 // this->reset(this->get()) works.
468 void reset(C* p = NULL) {
469 if (p != array_) {
470 enum { type_must_be_complete = sizeof(C) };
471 delete[] array_;
472 array_ = p;
476 // Get one element of the current object.
477 // Will assert() if there is no current object, or index i is negative.
478 C& operator[](std::ptrdiff_t i) const {
479 assert(i >= 0);
480 assert(array_ != NULL);
481 return array_[i];
484 // Get a pointer to the zeroth element of the current object.
485 // If there is no current object, return NULL.
486 C* get() const {
487 return array_;
490 // Comparison operators.
491 // These return whether two scoped_array refer to the same object, not just to
492 // two different but equal objects.
493 bool operator==(C* p) const { return array_ == p; }
494 bool operator!=(C* p) const { return array_ != p; }
496 // Swap two scoped arrays.
497 void swap(scoped_array& p2) {
498 C* tmp = array_;
499 array_ = p2.array_;
500 p2.array_ = tmp;
503 // Release an array.
504 // The return value is the current pointer held by this object.
505 // If this object holds a NULL pointer, the return value is NULL.
506 // After this operation, this object will hold a NULL pointer,
507 // and will not own the object any more.
508 C* release() {
509 C* retVal = array_;
510 array_ = NULL;
511 return retVal;
514 private:
515 C* array_;
517 // Forbid comparison of different scoped_array types.
518 template <class C2> bool operator==(scoped_array<C2> const& p2) const;
519 template <class C2> bool operator!=(scoped_array<C2> const& p2) const;
521 // Disallow evil constructors
522 scoped_array(const scoped_array&);
523 void operator=(const scoped_array&);
526 } // namespace internal
528 // We made these internal so that they would show up as such in the docs,
529 // but we don't want to stick "internal::" in front of them everywhere.
530 using internal::scoped_ptr;
531 using internal::scoped_array;
533 // ===================================================================
534 // emulates google3/base/logging.h
536 enum LogLevel {
537 LOGLEVEL_INFO, // Informational. This is never actually used by
538 // libprotobuf.
539 LOGLEVEL_WARNING, // Warns about issues that, although not technically a
540 // problem now, could cause problems in the future. For
541 // example, a // warning will be printed when parsing a
542 // message that is near the message size limit.
543 LOGLEVEL_ERROR, // An error occurred which should never happen during
544 // normal use.
545 LOGLEVEL_FATAL, // An error occurred from which the library cannot
546 // recover. This usually indicates a programming error
547 // in the code which calls the library, especially when
548 // compiled in debug mode.
550 #ifdef NDEBUG
551 LOGLEVEL_DFATAL = LOGLEVEL_ERROR
552 #else
553 LOGLEVEL_DFATAL = LOGLEVEL_FATAL
554 #endif
557 namespace internal {
559 class LogFinisher;
561 class LIBPROTOBUF_EXPORT LogMessage {
562 public:
563 LogMessage(LogLevel level, const char* filename, int line);
564 ~LogMessage();
566 LogMessage& operator<<(const string& value);
567 LogMessage& operator<<(const char* value);
568 LogMessage& operator<<(char value);
569 LogMessage& operator<<(int value);
570 LogMessage& operator<<(uint value);
571 LogMessage& operator<<(double value);
573 private:
574 friend class LogFinisher;
575 void Finish();
577 LogLevel level_;
578 const char* filename_;
579 int line_;
580 string message_;
583 // Used to make the entire "LOG(BLAH) << etc." expression have a void return
584 // type and print a newline after each message.
585 class LIBPROTOBUF_EXPORT LogFinisher {
586 public:
587 void operator=(LogMessage& other);
590 } // namespace internal
592 // Undef everything in case we're being mixed with some other Google library
593 // which already defined them itself. Presumably all Google libraries will
594 // support the same syntax for these so it should not be a big deal if they
595 // end up using our definitions instead.
596 #undef GOOGLE_LOG
597 #undef GOOGLE_LOG_IF
599 #undef GOOGLE_CHECK
600 #undef GOOGLE_CHECK_EQ
601 #undef GOOGLE_CHECK_NE
602 #undef GOOGLE_CHECK_LT
603 #undef GOOGLE_CHECK_LE
604 #undef GOOGLE_CHECK_GT
605 #undef GOOGLE_CHECK_GE
607 #undef GOOGLE_DLOG
608 #undef GOOGLE_DCHECK
609 #undef GOOGLE_DCHECK_EQ
610 #undef GOOGLE_DCHECK_NE
611 #undef GOOGLE_DCHECK_LT
612 #undef GOOGLE_DCHECK_LE
613 #undef GOOGLE_DCHECK_GT
614 #undef GOOGLE_DCHECK_GE
616 #define GOOGLE_LOG(LEVEL) \
617 ::google::protobuf::internal::LogFinisher() = \
618 ::google::protobuf::internal::LogMessage( \
619 ::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__)
620 #define GOOGLE_LOG_IF(LEVEL, CONDITION) \
621 !(CONDITION) ? (void)0 : GOOGLE_LOG(LEVEL)
623 #define GOOGLE_CHECK(EXPRESSION) \
624 GOOGLE_LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": "
625 #define GOOGLE_CHECK_EQ(A, B) GOOGLE_CHECK(A == B)
626 #define GOOGLE_CHECK_NE(A, B) GOOGLE_CHECK(A != B)
627 #define GOOGLE_CHECK_LT(A, B) GOOGLE_CHECK(A < B)
628 #define GOOGLE_CHECK_LE(A, B) GOOGLE_CHECK(A <= B)
629 #define GOOGLE_CHECK_GT(A, B) GOOGLE_CHECK(A > B)
630 #define GOOGLE_CHECK_GE(A, B) GOOGLE_CHECK(A >= B)
632 #ifdef NDEBUG
634 #define GOOGLE_DLOG GOOGLE_LOG_IF(false, INFO)
636 #define GOOGLE_DCHECK(EXPRESSION) while(false) GOOGLE_CHECK(EXPRESSION)
637 #define GOOGLE_DCHECK_EQ(A, B) GOOGLE_DCHECK(A == B)
638 #define GOOGLE_DCHECK_NE(A, B) GOOGLE_DCHECK(A != B)
639 #define GOOGLE_DCHECK_LT(A, B) GOOGLE_DCHECK(A < B)
640 #define GOOGLE_DCHECK_LE(A, B) GOOGLE_DCHECK(A <= B)
641 #define GOOGLE_DCHECK_GT(A, B) GOOGLE_DCHECK(A > B)
642 #define GOOGLE_DCHECK_GE(A, B) GOOGLE_DCHECK(A >= B)
644 #else // NDEBUG
646 #define GOOGLE_DLOG GOOGLE_LOG
648 #define GOOGLE_DCHECK GOOGLE_CHECK
649 #define GOOGLE_DCHECK_EQ GOOGLE_CHECK_EQ
650 #define GOOGLE_DCHECK_NE GOOGLE_CHECK_NE
651 #define GOOGLE_DCHECK_LT GOOGLE_CHECK_LT
652 #define GOOGLE_DCHECK_LE GOOGLE_CHECK_LE
653 #define GOOGLE_DCHECK_GT GOOGLE_CHECK_GT
654 #define GOOGLE_DCHECK_GE GOOGLE_CHECK_GE
656 #endif // !NDEBUG
658 typedef void LogHandler(LogLevel level, const char* filename, int line,
659 const string& message);
661 // The protobuf library sometimes writes warning and error messages to
662 // stderr. These messages are primarily useful for developers, but may
663 // also help end users figure out a problem. If you would prefer that
664 // these messages be sent somewhere other than stderr, call SetLogHandler()
665 // to set your own handler. This returns the old handler. Set the handler
666 // to NULL to ignore log messages (but see also LogSilencer, below).
668 // Obviously, SetLogHandler is not thread-safe. You should only call it
669 // at initialization time, and probably not from library code. If you
670 // simply want to suppress log messages temporarily (e.g. because you
671 // have some code that tends to trigger them frequently and you know
672 // the warnings are not important to you), use the LogSilencer class
673 // below.
674 LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func);
676 // Create a LogSilencer if you want to temporarily suppress all log
677 // messages. As long as any LogSilencer objects exist, non-fatal
678 // log messages will be discarded (the current LogHandler will *not*
679 // be called). Constructing a LogSilencer is thread-safe. You may
680 // accidentally suppress log messages occurring in another thread, but
681 // since messages are generally for debugging purposes only, this isn't
682 // a big deal. If you want to intercept log messages, use SetLogHandler().
683 class LIBPROTOBUF_EXPORT LogSilencer {
684 public:
685 LogSilencer();
686 ~LogSilencer();
689 // ===================================================================
690 // emulates google3/base/callback.h
692 // Abstract interface for a callback. When calling an RPC, you must provide
693 // a Closure to call when the procedure completes. See the Service interface
694 // in service.h.
696 // To automatically construct a Closure which calls a particular function or
697 // method with a particular set of parameters, use the NewCallback() function.
698 // Example:
699 // void FooDone(const FooResponse* response) {
700 // ...
701 // }
703 // void CallFoo() {
704 // ...
705 // // When done, call FooDone() and pass it a pointer to the response.
706 // Closure* callback = NewCallback(&FooDone, response);
707 // // Make the call.
708 // service->Foo(controller, request, response, callback);
709 // }
711 // Example that calls a method:
712 // class Handler {
713 // public:
714 // ...
716 // void FooDone(const FooResponse* response) {
717 // ...
718 // }
720 // void CallFoo() {
721 // ...
722 // // When done, call FooDone() and pass it a pointer to the response.
723 // Closure* callback = NewCallback(this, &Handler::FooDone, response);
724 // // Make the call.
725 // service->Foo(controller, request, response, callback);
726 // }
727 // };
729 // Currently NewCallback() supports binding zero, one, or two arguments.
731 // Callbacks created with NewCallback() automatically delete themselves when
732 // executed. They should be used when a callback is to be called exactly
733 // once (usually the case with RPC callbacks). If a callback may be called
734 // a different number of times (including zero), create it with
735 // NewPermanentCallback() instead. You are then responsible for deleting the
736 // callback (using the "delete" keyword as normal).
738 // Note that NewCallback() is a bit touchy regarding argument types. Generally,
739 // the values you provide for the parameter bindings must exactly match the
740 // types accepted by the callback function. For example:
741 // void Foo(string s);
742 // NewCallback(&Foo, "foo"); // WON'T WORK: const char* != string
743 // NewCallback(&Foo, string("foo")); // WORKS
744 // Also note that the arguments cannot be references:
745 // void Foo(const string& s);
746 // string my_str;
747 // NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes.
748 // However, correctly-typed pointers will work just fine.
749 class LIBPROTOBUF_EXPORT Closure {
750 public:
751 Closure() {}
752 virtual ~Closure();
754 virtual void Run() = 0;
756 private:
757 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Closure);
760 namespace internal {
762 class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure {
763 public:
764 typedef void (*FunctionType)();
766 FunctionClosure0(FunctionType function, bool self_deleting)
767 : function_(function), self_deleting_(self_deleting) {}
768 ~FunctionClosure0();
770 void Run() {
771 function_();
772 if (self_deleting_) delete this;
775 private:
776 FunctionType function_;
777 bool self_deleting_;
780 template <typename Class>
781 class MethodClosure0 : public Closure {
782 public:
783 typedef void (Class::*MethodType)();
785 MethodClosure0(Class* object, MethodType method, bool self_deleting)
786 : object_(object), method_(method), self_deleting_(self_deleting) {}
787 ~MethodClosure0() {}
789 void Run() {
790 (object_->*method_)();
791 if (self_deleting_) delete this;
794 private:
795 Class* object_;
796 MethodType method_;
797 bool self_deleting_;
800 template <typename Arg1>
801 class FunctionClosure1 : public Closure {
802 public:
803 typedef void (*FunctionType)(Arg1 arg1);
805 FunctionClosure1(FunctionType function, bool self_deleting,
806 Arg1 arg1)
807 : function_(function), self_deleting_(self_deleting),
808 arg1_(arg1) {}
809 ~FunctionClosure1() {}
811 void Run() {
812 function_(arg1_);
813 if (self_deleting_) delete this;
816 private:
817 FunctionType function_;
818 bool self_deleting_;
819 Arg1 arg1_;
822 template <typename Class, typename Arg1>
823 class MethodClosure1 : public Closure {
824 public:
825 typedef void (Class::*MethodType)(Arg1 arg1);
827 MethodClosure1(Class* object, MethodType method, bool self_deleting,
828 Arg1 arg1)
829 : object_(object), method_(method), self_deleting_(self_deleting),
830 arg1_(arg1) {}
831 ~MethodClosure1() {}
833 void Run() {
834 (object_->*method_)(arg1_);
835 if (self_deleting_) delete this;
838 private:
839 Class* object_;
840 MethodType method_;
841 bool self_deleting_;
842 Arg1 arg1_;
845 template <typename Arg1, typename Arg2>
846 class FunctionClosure2 : public Closure {
847 public:
848 typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2);
850 FunctionClosure2(FunctionType function, bool self_deleting,
851 Arg1 arg1, Arg2 arg2)
852 : function_(function), self_deleting_(self_deleting),
853 arg1_(arg1), arg2_(arg2) {}
854 ~FunctionClosure2() {}
856 void Run() {
857 function_(arg1_, arg2_);
858 if (self_deleting_) delete this;
861 private:
862 FunctionType function_;
863 bool self_deleting_;
864 Arg1 arg1_;
865 Arg2 arg2_;
868 template <typename Class, typename Arg1, typename Arg2>
869 class MethodClosure2 : public Closure {
870 public:
871 typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2);
873 MethodClosure2(Class* object, MethodType method, bool self_deleting,
874 Arg1 arg1, Arg2 arg2)
875 : object_(object), method_(method), self_deleting_(self_deleting),
876 arg1_(arg1), arg2_(arg2) {}
877 ~MethodClosure2() {}
879 void Run() {
880 (object_->*method_)(arg1_, arg2_);
881 if (self_deleting_) delete this;
884 private:
885 Class* object_;
886 MethodType method_;
887 bool self_deleting_;
888 Arg1 arg1_;
889 Arg2 arg2_;
892 } // namespace internal
894 // See Closure.
895 inline Closure* NewCallback(void (*function)()) {
896 return new internal::FunctionClosure0(function, true);
899 // See Closure.
900 inline Closure* NewPermanentCallback(void (*function)()) {
901 return new internal::FunctionClosure0(function, false);
904 // See Closure.
905 template <typename Class>
906 inline Closure* NewCallback(Class* object, void (Class::*method)()) {
907 return new internal::MethodClosure0<Class>(object, method, true);
910 // See Closure.
911 template <typename Class>
912 inline Closure* NewPermanentCallback(Class* object, void (Class::*method)()) {
913 return new internal::MethodClosure0<Class>(object, method, false);
916 // See Closure.
917 template <typename Arg1>
918 inline Closure* NewCallback(void (*function)(Arg1),
919 Arg1 arg1) {
920 return new internal::FunctionClosure1<Arg1>(function, true, arg1);
923 // See Closure.
924 template <typename Arg1>
925 inline Closure* NewPermanentCallback(void (*function)(Arg1),
926 Arg1 arg1) {
927 return new internal::FunctionClosure1<Arg1>(function, false, arg1);
930 // See Closure.
931 template <typename Class, typename Arg1>
932 inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1),
933 Arg1 arg1) {
934 return new internal::MethodClosure1<Class, Arg1>(object, method, true, arg1);
937 // See Closure.
938 template <typename Class, typename Arg1>
939 inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(Arg1),
940 Arg1 arg1) {
941 return new internal::MethodClosure1<Class, Arg1>(object, method, false, arg1);
944 // See Closure.
945 template <typename Arg1, typename Arg2>
946 inline Closure* NewCallback(void (*function)(Arg1, Arg2),
947 Arg1 arg1, Arg2 arg2) {
948 return new internal::FunctionClosure2<Arg1, Arg2>(
949 function, true, arg1, arg2);
952 // See Closure.
953 template <typename Arg1, typename Arg2>
954 inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2),
955 Arg1 arg1, Arg2 arg2) {
956 return new internal::FunctionClosure2<Arg1, Arg2>(
957 function, false, arg1, arg2);
960 // See Closure.
961 template <typename Class, typename Arg1, typename Arg2>
962 inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, Arg2),
963 Arg1 arg1, Arg2 arg2) {
964 return new internal::MethodClosure2<Class, Arg1, Arg2>(
965 object, method, true, arg1, arg2);
968 // See Closure.
969 template <typename Class, typename Arg1, typename Arg2>
970 inline Closure* NewPermanentCallback(
971 Class* object, void (Class::*method)(Arg1, Arg2),
972 Arg1 arg1, Arg2 arg2) {
973 return new internal::MethodClosure2<Class, Arg1, Arg2>(
974 object, method, false, arg1, arg2);
977 // A function which does nothing. Useful for creating no-op callbacks, e.g.:
978 // Closure* nothing = NewCallback(&DoNothing);
979 void LIBPROTOBUF_EXPORT DoNothing();
981 // ===================================================================
982 // emulates google3/base/mutex.h
984 namespace internal {
986 // A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T
987 // may hold a mutex at a given time. If T attempts to Lock() the same Mutex
988 // while holding it, T will deadlock.
989 class LIBPROTOBUF_EXPORT Mutex {
990 public:
991 // Create a Mutex that is not held by anybody.
992 Mutex();
994 // Destructor
995 ~Mutex();
997 // Block if necessary until this Mutex is free, then acquire it exclusively.
998 void Lock();
1000 // Release this Mutex. Caller must hold it exclusively.
1001 void Unlock();
1003 // Crash if this Mutex is not held exclusively by this thread.
1004 // May fail to crash when it should; will never crash when it should not.
1005 void AssertHeld();
1007 private:
1008 struct Internal;
1009 Internal* mInternal;
1011 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex);
1014 // MutexLock(mu) acquires mu when constructed and releases it when destroyed.
1015 class LIBPROTOBUF_EXPORT MutexLock {
1016 public:
1017 explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); }
1018 ~MutexLock() { this->mu_->Unlock(); }
1019 private:
1020 Mutex *const mu_;
1021 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock);
1024 // MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL.
1025 class LIBPROTOBUF_EXPORT MutexLockMaybe {
1026 public:
1027 explicit MutexLockMaybe(Mutex *mu) :
1028 mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } }
1029 ~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } }
1030 private:
1031 Mutex *const mu_;
1032 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe);
1035 } // namespace internal
1037 // We made these internal so that they would show up as such in the docs,
1038 // but we don't want to stick "internal::" in front of them everywhere.
1039 using internal::Mutex;
1040 using internal::MutexLock;
1041 using internal::MutexLockMaybe;
1043 // ===================================================================
1044 // from google3/base/type_traits.h
1046 namespace internal {
1048 // Specified by TR1 [4.7.4] Pointer modifications.
1049 template<typename T> struct remove_pointer { typedef T type; };
1050 template<typename T> struct remove_pointer<T*> { typedef T type; };
1051 template<typename T> struct remove_pointer<T* const> { typedef T type; };
1052 template<typename T> struct remove_pointer<T* volatile> { typedef T type; };
1053 template<typename T> struct remove_pointer<T* const volatile> {
1054 typedef T type; };
1056 } // namespace internal
1058 } // namespace protobuf
1059 } // namespace google
1061 #endif // GOOGLE_PROTOBUF_COMMON_H__