HELLO·Android
系统源代码
IT资讯
技术文章
我的收藏
注册
登录
-
我收藏的文章
创建代码块
我的代码块
我的账号
Oreo
|
8.0.0_r4
下载
查看原文件
收藏
根目录
external
protobuf
ruby
ext
google
protobuf_c
upb.h
// Amalgamated source file /* ** Defs are upb's internal representation of the constructs that can appear ** in a .proto file: ** ** - upb::MessageDef (upb_msgdef): describes a "message" construct. ** - upb::FieldDef (upb_fielddef): describes a message field. ** - upb::FileDef (upb_filedef): describes a .proto file and its defs. ** - upb::EnumDef (upb_enumdef): describes an enum. ** - upb::OneofDef (upb_oneofdef): describes a oneof. ** - upb::Def (upb_def): base class of all the others. ** ** TODO: definitions of services. ** ** Like upb_refcounted objects, defs are mutable only until frozen, and are ** only thread-safe once frozen. ** ** This is a mixed C/C++ interface that offers a full API to both languages. ** See the top-level README for more information. */ #ifndef UPB_DEF_H_ #define UPB_DEF_H_ /* ** upb::RefCounted (upb_refcounted) ** ** A refcounting scheme that supports circular refs. It accomplishes this by ** partitioning the set of objects into groups such that no cycle spans groups; ** we can then reference-count the group as a whole and ignore refs within the ** group. When objects are mutable, these groups are computed very ** conservatively; we group any objects that have ever had a link between them. ** When objects are frozen, we compute strongly-connected components which ** allows us to be precise and only group objects that are actually cyclic. ** ** This is a mixed C/C++ interface that offers a full API to both languages. ** See the top-level README for more information. */ #ifndef UPB_REFCOUNTED_H_ #define UPB_REFCOUNTED_H_ /* ** upb_table ** ** This header is INTERNAL-ONLY! Its interfaces are not public or stable! ** This file defines very fast int->upb_value (inttable) and string->upb_value ** (strtable) hash tables. ** ** The table uses chained scatter with Brent's variation (inspired by the Lua ** implementation of hash tables). The hash function for strings is Austin ** Appleby's "MurmurHash." ** ** The inttable uses uintptr_t as its key, which guarantees it can be used to ** store pointers or integers of at least 32 bits (upb isn't really useful on ** systems where sizeof(void*) < 4). ** ** The table must be homogenous (all values of the same type). In debug ** mode, we check this on insert and lookup. */ #ifndef UPB_TABLE_H_ #define UPB_TABLE_H_ #include
#include
#include
/* ** This file contains shared definitions that are widely used across upb. ** ** This is a mixed C/C++ interface that offers a full API to both languages. ** See the top-level README for more information. */ #ifndef UPB_H_ #define UPB_H_ #include
#include
#include
#include
#ifdef __cplusplus namespace upb { class Allocator; class Arena; class Environment; class ErrorSpace; class Status; template
class InlinedArena; template
class InlinedEnvironment; } #endif /* UPB_INLINE: inline if possible, emit standalone code if required. */ #ifdef __cplusplus #define UPB_INLINE inline #elif defined (__GNUC__) #define UPB_INLINE static __inline__ #else #define UPB_INLINE static #endif /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler * doesn't provide these preprocessor symbols. */ #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #define UPB_BIG_ENDIAN #endif /* Macros for function attributes on compilers that support them. */ #ifdef __GNUC__ #define UPB_FORCEINLINE __inline__ __attribute__((always_inline)) #define UPB_NOINLINE __attribute__((noinline)) #define UPB_NORETURN __attribute__((__noreturn__)) #else /* !defined(__GNUC__) */ #define UPB_FORCEINLINE #define UPB_NOINLINE #define UPB_NORETURN #endif /* A few hacky workarounds for functions not in C89. * For internal use only! * TODO(haberman): fix these by including our own implementations, or finding * another workaround. */ #ifdef __GNUC__ #define _upb_snprintf __builtin_snprintf #define _upb_vsnprintf __builtin_vsnprintf #define _upb_va_copy(a, b) __va_copy(a, b) #elif __STDC_VERSION__ >= 199901L /* C99 versions. */ #define _upb_snprintf snprintf #define _upb_vsnprintf vsnprintf #define _upb_va_copy(a, b) va_copy(a, b) #else #error Need implementations of [v]snprintf and va_copy #endif #if ((defined(__cplusplus) && __cplusplus >= 201103L) || \ defined(__GXX_EXPERIMENTAL_CXX0X__)) && !defined(UPB_NO_CXX11) #define UPB_CXX11 #endif /* UPB_DISALLOW_COPY_AND_ASSIGN() * UPB_DISALLOW_POD_OPS() * * Declare these in the "private" section of a C++ class to forbid copy/assign * or all POD ops (construct, destruct, copy, assign) on that class. */ #ifdef UPB_CXX11 #include
#define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \ class_name(const class_name&) = delete; \ void operator=(const class_name&) = delete; #define UPB_DISALLOW_POD_OPS(class_name, full_class_name) \ class_name() = delete; \ ~class_name() = delete; \ UPB_DISALLOW_COPY_AND_ASSIGN(class_name) #define UPB_ASSERT_STDLAYOUT(type) \ static_assert(std::is_standard_layout
::value, \ #type " must be standard layout"); #define UPB_FINAL final #else /* !defined(UPB_CXX11) */ #define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \ class_name(const class_name&); \ void operator=(const class_name&); #define UPB_DISALLOW_POD_OPS(class_name, full_class_name) \ class_name(); \ ~class_name(); \ UPB_DISALLOW_COPY_AND_ASSIGN(class_name) #define UPB_ASSERT_STDLAYOUT(type) #define UPB_FINAL #endif /* UPB_DECLARE_TYPE() * UPB_DECLARE_DERIVED_TYPE() * UPB_DECLARE_DERIVED_TYPE2() * * Macros for declaring C and C++ types both, including inheritance. * The inheritance doesn't use real C++ inheritance, to stay compatible with C. * * These macros also provide upcasts: * - in C: types-specific functions (ie. upb_foo_upcast(foo)) * - in C++: upb::upcast(foo) along with implicit conversions * * Downcasts are not provided, but upb/def.h defines downcasts for upb::Def. */ #define UPB_C_UPCASTS(ty, base) \ UPB_INLINE base *ty ## _upcast_mutable(ty *p) { return (base*)p; } \ UPB_INLINE const base *ty ## _upcast(const ty *p) { return (const base*)p; } #define UPB_C_UPCASTS2(ty, base, base2) \ UPB_C_UPCASTS(ty, base) \ UPB_INLINE base2 *ty ## _upcast2_mutable(ty *p) { return (base2*)p; } \ UPB_INLINE const base2 *ty ## _upcast2(const ty *p) { return (const base2*)p; } #ifdef __cplusplus #define UPB_BEGIN_EXTERN_C extern "C" { #define UPB_END_EXTERN_C } #define UPB_PRIVATE_FOR_CPP private: #define UPB_DECLARE_TYPE(cppname, cname) typedef cppname cname; #define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \ UPB_DECLARE_TYPE(cppname, cname) \ UPB_C_UPCASTS(cname, cbase) \ namespace upb { \ template <> \ class Pointer
: public PointerBase
{ \ public: \ explicit Pointer(cppname* ptr) \ : PointerBase
(ptr) {} \ }; \ template <> \ class Pointer
\ : public PointerBase
{ \ public: \ explicit Pointer(const cppname* ptr) \ : PointerBase
(ptr) {} \ }; \ } #define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, cname, cbase, \ cbase2) \ UPB_DECLARE_TYPE(cppname, cname) \ UPB_C_UPCASTS2(cname, cbase, cbase2) \ namespace upb { \ template <> \ class Pointer
: public PointerBase2
{ \ public: \ explicit Pointer(cppname* ptr) \ : PointerBase2
(ptr) {} \ }; \ template <> \ class Pointer
\ : public PointerBase2
{ \ public: \ explicit Pointer(const cppname* ptr) \ : PointerBase2
(ptr) {} \ }; \ } #else /* !defined(__cplusplus) */ #define UPB_BEGIN_EXTERN_C #define UPB_END_EXTERN_C #define UPB_PRIVATE_FOR_CPP #define UPB_DECLARE_TYPE(cppname, cname) \ struct cname; \ typedef struct cname cname; #define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \ UPB_DECLARE_TYPE(cppname, cname) \ UPB_C_UPCASTS(cname, cbase) #define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, \ cname, cbase, cbase2) \ UPB_DECLARE_TYPE(cppname, cname) \ UPB_C_UPCASTS2(cname, cbase, cbase2) #endif /* defined(__cplusplus) */ #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y)) #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y)) #define UPB_UNUSED(var) (void)var /* For asserting something about a variable when the variable is not used for * anything else. This prevents "unused variable" warnings when compiling in * debug mode. */ #define UPB_ASSERT_VAR(var, predicate) UPB_UNUSED(var); assert(predicate) /* Generic function type. */ typedef void upb_func(); /* C++ Casts ******************************************************************/ #ifdef __cplusplus namespace upb { template
class Pointer; /* Casts to a subclass. The caller must know that cast is correct; an * incorrect cast will throw an assertion failure in debug mode. * * Example: * upb::Def* def = GetDef(); * // Assert-fails if this was not actually a MessageDef. * upb::MessgeDef* md = upb::down_cast
(def); * * Note that downcasts are only defined for some types (at the moment you can * only downcast from a upb::Def to a specific Def type). */ template
To down_cast(From* f); /* Casts to a subclass. If the class does not actually match the given To type, * returns NULL. * * Example: * upb::Def* def = GetDef(); * // md will be NULL if this was not actually a MessageDef. * upb::MessgeDef* md = upb::down_cast
(def); * * Note that dynamic casts are only defined for some types (at the moment you * can only downcast from a upb::Def to a specific Def type).. */ template
To dyn_cast(From* f); /* Casts to any base class, or the type itself (ie. can be a no-op). * * Example: * upb::MessageDef* md = GetDef(); * // This will fail to compile if this wasn't actually a base class. * upb::Def* def = upb::upcast(md); */ template
inline Pointer
upcast(T *f) { return Pointer
(f); } /* Attempt upcast to specific base class. * * Example: * upb::MessageDef* md = GetDef(); * upb::upcast_to
(md)->MethodOnDef(); */ template
inline T* upcast_to(F *f) { return static_cast
(upcast(f)); } /* PointerBase
: implementation detail of upb::upcast(). * It is implicitly convertable to pointers to the Base class(es). */ template
class PointerBase { public: explicit PointerBase(T* ptr) : ptr_(ptr) {} operator T*() { return ptr_; } operator Base*() { return (Base*)ptr_; } private: T* ptr_; }; template
class PointerBase2 : public PointerBase
{ public: explicit PointerBase2(T* ptr) : PointerBase
(ptr) {} operator Base2*() { return Pointer
(*this); } }; } #endif /* upb::ErrorSpace ************************************************************/ /* A upb::ErrorSpace represents some domain of possible error values. This lets * upb::Status attach specific error codes to operations, like POSIX/C errno, * Win32 error codes, etc. Clients who want to know the very specific error * code can check the error space and then know the type of the integer code. * * NOTE: upb::ErrorSpace is currently not used and should be considered * experimental. It is important primarily in cases where upb is performing * I/O, but upb doesn't currently have any components that do this. */ UPB_DECLARE_TYPE(upb::ErrorSpace, upb_errorspace) #ifdef __cplusplus class upb::ErrorSpace { #else struct upb_errorspace { #endif const char *name; }; /* upb::Status ****************************************************************/ /* upb::Status represents a success or failure status and error message. * It owns no resources and allocates no memory, so it should work * even in OOM situations. */ UPB_DECLARE_TYPE(upb::Status, upb_status) /* The maximum length of an error message before it will get truncated. */ #define UPB_STATUS_MAX_MESSAGE 128 UPB_BEGIN_EXTERN_C const char *upb_status_errmsg(const upb_status *status); bool upb_ok(const upb_status *status); upb_errorspace *upb_status_errspace(const upb_status *status); int upb_status_errcode(const upb_status *status); /* Any of the functions that write to a status object allow status to be NULL, * to support use cases where the function's caller does not care about the * status message. */ void upb_status_clear(upb_status *status); void upb_status_seterrmsg(upb_status *status, const char *msg); void upb_status_seterrf(upb_status *status, const char *fmt, ...); void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args); void upb_status_copy(upb_status *to, const upb_status *from); UPB_END_EXTERN_C #ifdef __cplusplus class upb::Status { public: Status() { upb_status_clear(this); } /* Returns true if there is no error. */ bool ok() const { return upb_ok(this); } /* Optional error space and code, useful if the caller wants to * programmatically check the specific kind of error. */ ErrorSpace* error_space() { return upb_status_errspace(this); } int error_code() const { return upb_status_errcode(this); } /* The returned string is invalidated by any other call into the status. */ const char *error_message() const { return upb_status_errmsg(this); } /* The error message will be truncated if it is longer than * UPB_STATUS_MAX_MESSAGE-4. */ void SetErrorMessage(const char* msg) { upb_status_seterrmsg(this, msg); } void SetFormattedErrorMessage(const char* fmt, ...) { va_list args; va_start(args, fmt); upb_status_vseterrf(this, fmt, args); va_end(args); } /* Resets the status to a successful state with no message. */ void Clear() { upb_status_clear(this); } void CopyFrom(const Status& other) { upb_status_copy(this, &other); } private: UPB_DISALLOW_COPY_AND_ASSIGN(Status) #else struct upb_status { #endif bool ok_; /* Specific status code defined by some error space (optional). */ int code_; upb_errorspace *error_space_; /* TODO(haberman): add file/line of error? */ /* Error message; NULL-terminated. */ char msg[UPB_STATUS_MAX_MESSAGE]; }; #define UPB_STATUS_INIT {true, 0, NULL, {0}} /** Built-in error spaces. ****************************************************/ /* Errors raised by upb that we want to be able to detect programmatically. */ typedef enum { UPB_NOMEM /* Can't reuse ENOMEM because it is POSIX, not ISO C. */ } upb_errcode_t; extern upb_errorspace upb_upberr; void upb_upberr_setoom(upb_status *s); /* Since errno is defined by standard C, we define an error space for it in * core upb. Other error spaces should be defined in other, platform-specific * modules. */ extern upb_errorspace upb_errnoerr; /** upb::Allocator ************************************************************/ /* A upb::Allocator is a possibly-stateful allocator object. * * It could either be an arena allocator (which doesn't require individual * free() calls) or a regular malloc() (which does). The client must therefore * free memory unless it knows that the allocator is an arena allocator. */ UPB_DECLARE_TYPE(upb::Allocator, upb_alloc) /* A malloc()/free() function. * If "size" is 0 then the function acts like free(), otherwise it acts like * realloc(). Only "oldsize" bytes from a previous allocation are preserved. */ typedef void *upb_alloc_func(upb_alloc *alloc, void *ptr, size_t oldsize, size_t size); #ifdef __cplusplus class upb::Allocator UPB_FINAL { public: Allocator() {} private: UPB_DISALLOW_COPY_AND_ASSIGN(Allocator) public: #else struct upb_alloc { #endif /* __cplusplus */ upb_alloc_func *func; }; UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) { assert(size > 0); return alloc->func(alloc, NULL, 0, size); } UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize, size_t size) { assert(size > 0); return alloc->func(alloc, ptr, oldsize, size); } UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) { alloc->func(alloc, ptr, 0, 0); } /* The global allocator used by upb. Uses the standard malloc()/free(). */ extern upb_alloc upb_alloc_global; /* Functions that hard-code the global malloc. * * We still get benefit because we can put custom logic into our global * allocator, like injecting out-of-memory faults in debug/testing builds. */ UPB_INLINE void *upb_gmalloc(size_t size) { return upb_malloc(&upb_alloc_global, size); } UPB_INLINE void *upb_grealloc(void *ptr, size_t oldsize, size_t size) { return upb_realloc(&upb_alloc_global, ptr, oldsize, size); } UPB_INLINE void upb_gfree(void *ptr) { upb_free(&upb_alloc_global, ptr); } /* upb::Arena *****************************************************************/ /* upb::Arena is a specific allocator implementation that uses arena allocation. * The user provides an allocator that will be used to allocate the underlying * arena blocks. Arenas by nature do not require the individual allocations * to be freed. However the Arena does allow users to register cleanup * functions that will run when the arena is destroyed. * * A upb::Arena is *not* thread-safe. * * You could write a thread-safe arena allocator that satisfies the * upb::Allocator interface, but it would not be as efficient for the * single-threaded case. */ UPB_DECLARE_TYPE(upb::Arena, upb_arena) typedef void upb_cleanup_func(void *ud); #define UPB_ARENA_BLOCK_OVERHEAD (sizeof(size_t)*4) UPB_BEGIN_EXTERN_C void upb_arena_init(upb_arena *a); void upb_arena_init2(upb_arena *a, void *mem, size_t n, upb_alloc *alloc); void upb_arena_uninit(upb_arena *a); upb_alloc *upb_arena_alloc(upb_arena *a); bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud); size_t upb_arena_bytesallocated(const upb_arena *a); void upb_arena_setnextblocksize(upb_arena *a, size_t size); void upb_arena_setmaxblocksize(upb_arena *a, size_t size); UPB_END_EXTERN_C #ifdef __cplusplus class upb::Arena { public: /* A simple arena with no initial memory block and the default allocator. */ Arena() { upb_arena_init(this); } /* Constructs an arena with the given initial block which allocates blocks * with the given allocator. The given allocator must outlive the Arena. * * If you pass NULL for the allocator it will default to the global allocator * upb_alloc_global, and NULL/0 for the initial block will cause there to be * no initial block. */ Arena(void *mem, size_t len, Allocator* a) { upb_arena_init2(this, mem, len, a); } ~Arena() { upb_arena_uninit(this); } /* Sets the size of the next block the Arena will request (unless the * requested allocation is larger). Each block will double in size until the * max limit is reached. */ void SetNextBlockSize(size_t size) { upb_arena_setnextblocksize(this, size); } /* Sets the maximum block size. No blocks larger than this will be requested * from the underlying allocator unless individual arena allocations are * larger. */ void SetMaxBlockSize(size_t size) { upb_arena_setmaxblocksize(this, size); } /* Allows this arena to be used as a generic allocator. * * The arena does not need free() calls so when using Arena as an allocator * it is safe to skip them. However they are no-ops so there is no harm in * calling free() either. */ Allocator* allocator() { return upb_arena_alloc(this); } /* Add a cleanup function to run when the arena is destroyed. * Returns false on out-of-memory. */ bool AddCleanup(upb_cleanup_func* func, void* ud) { return upb_arena_addcleanup(this, func, ud); } /* Total number of bytes that have been allocated. It is undefined what * Realloc() does to this counter. */ size_t BytesAllocated() const { return upb_arena_bytesallocated(this); } private: UPB_DISALLOW_COPY_AND_ASSIGN(Arena) #else struct upb_arena { #endif /* __cplusplus */ /* We implement the allocator interface. * This must be the first member of upb_arena! */ upb_alloc alloc; /* Allocator to allocate arena blocks. We are responsible for freeing these * when we are destroyed. */ upb_alloc *block_alloc; size_t bytes_allocated; size_t next_block_size; size_t max_block_size; /* Linked list of blocks. Points to an arena_block, defined in env.c */ void *block_head; /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */ void *cleanup_head; /* For future expansion, since the size of this struct is exposed to users. */ void *future1; void *future2; }; /* upb::Environment ***********************************************************/ /* A upb::Environment provides a means for injecting malloc and an * error-reporting callback into encoders/decoders. This allows them to be * independent of nearly all assumptions about their actual environment. * * It is also a container for allocating the encoders/decoders themselves that * insulates clients from knowing their actual size. This provides ABI * compatibility even if the size of the objects change. And this allows the * structure definitions to be in the .c files instead of the .h files, making * the .h files smaller and more readable. * * We might want to consider renaming this to "Pipeline" if/when the concept of * a pipeline element becomes more formalized. */ UPB_DECLARE_TYPE(upb::Environment, upb_env) /* A function that receives an error report from an encoder or decoder. The * callback can return true to request that the error should be recovered, but * if the error is not recoverable this has no effect. */ typedef bool upb_error_func(void *ud, const upb_status *status); UPB_BEGIN_EXTERN_C void upb_env_init(upb_env *e); void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc); void upb_env_uninit(upb_env *e); void upb_env_initonly(upb_env *e); upb_arena *upb_env_arena(upb_env *e); bool upb_env_ok(const upb_env *e); void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud); /* Convenience wrappers around the methods of the contained arena. */ void upb_env_reporterrorsto(upb_env *e, upb_status *s); bool upb_env_reporterror(upb_env *e, const upb_status *s); void *upb_env_malloc(upb_env *e, size_t size); void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size); void upb_env_free(upb_env *e, void *ptr); bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud); size_t upb_env_bytesallocated(const upb_env *e); UPB_END_EXTERN_C #ifdef __cplusplus class upb::Environment { public: /* The given Arena must outlive this environment. */ Environment() { upb_env_initonly(this); } Environment(void *mem, size_t len, Allocator *a) : arena_(mem, len, a) { upb_env_initonly(this); } Arena* arena() { return upb_env_arena(this); } /* Set a custom error reporting function. */ void SetErrorFunction(upb_error_func* func, void* ud) { upb_env_seterrorfunc(this, func, ud); } /* Set the error reporting function to simply copy the status to the given * status and abort. */ void ReportErrorsTo(Status* status) { upb_env_reporterrorsto(this, status); } /* Returns true if all allocations and AddCleanup() calls have succeeded, * and no errors were reported with ReportError() (except ones that recovered * successfully). */ bool ok() const { return upb_env_ok(this); } /* Reports an error to this environment's callback, returning true if * the caller should try to recover. */ bool ReportError(const Status* status) { return upb_env_reporterror(this, status); } private: UPB_DISALLOW_COPY_AND_ASSIGN(Environment) #else struct upb_env { #endif /* __cplusplus */ upb_arena arena_; upb_error_func *error_func_; void *error_ud_; bool ok_; }; /* upb::InlinedArena **********************************************************/ /* upb::InlinedEnvironment ****************************************************/ /* upb::InlinedArena and upb::InlinedEnvironment seed their arenas with a * predefined amount of memory. No heap memory will be allocated until the * initial block is exceeded. * * These types only exist in C++ */ #ifdef __cplusplus template
class upb::InlinedArena : public upb::Arena { public: InlinedArena() : Arena(initial_block_, N, NULL) {} explicit InlinedArena(Allocator* a) : Arena(initial_block_, N, a) {} private: UPB_DISALLOW_COPY_AND_ASSIGN(InlinedArena) char initial_block_[N + UPB_ARENA_BLOCK_OVERHEAD]; }; template
class upb::InlinedEnvironment : public upb::Environment { public: InlinedEnvironment() : Environment(initial_block_, N, NULL) {} explicit InlinedEnvironment(Allocator *a) : Environment(initial_block_, N, a) {} private: UPB_DISALLOW_COPY_AND_ASSIGN(InlinedEnvironment) char initial_block_[N + UPB_ARENA_BLOCK_OVERHEAD]; }; #endif /* __cplusplus */ #endif /* UPB_H_ */ #ifdef __cplusplus extern "C" { #endif /* upb_value ******************************************************************/ /* A tagged union (stored untagged inside the table) so that we can check that * clients calling table accessors are correctly typed without having to have * an explosion of accessors. */ typedef enum { UPB_CTYPE_INT32 = 1, UPB_CTYPE_INT64 = 2, UPB_CTYPE_UINT32 = 3, UPB_CTYPE_UINT64 = 4, UPB_CTYPE_BOOL = 5, UPB_CTYPE_CSTR = 6, UPB_CTYPE_PTR = 7, UPB_CTYPE_CONSTPTR = 8, UPB_CTYPE_FPTR = 9 } upb_ctype_t; typedef struct { uint64_t val; #ifndef NDEBUG /* In debug mode we carry the value type around also so we can check accesses * to be sure the right member is being read. */ upb_ctype_t ctype; #endif } upb_value; #ifdef NDEBUG #define SET_TYPE(dest, val) UPB_UNUSED(val) #else #define SET_TYPE(dest, val) dest = val #endif /* Like strdup(), which isn't always available since it's not ANSI C. */ char *upb_strdup(const char *s, upb_alloc *a); /* Variant that works with a length-delimited rather than NULL-delimited string, * as supported by strtable. */ char *upb_strdup2(const char *s, size_t len, upb_alloc *a); UPB_INLINE char *upb_gstrdup(const char *s) { return upb_strdup(s, &upb_alloc_global); } UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val, upb_ctype_t ctype) { v->val = val; SET_TYPE(v->ctype, ctype); } UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) { upb_value ret; _upb_value_setval(&ret, val, ctype); return ret; } /* For each value ctype, define the following set of functions: * * // Get/set an int32 from a upb_value. * int32_t upb_value_getint32(upb_value val); * void upb_value_setint32(upb_value *val, int32_t cval); * * // Construct a new upb_value from an int32. * upb_value upb_value_int32(int32_t val); */ #define FUNCS(name, membername, type_t, converter, proto_type) \ UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \ val->val = (converter)cval; \ SET_TYPE(val->ctype, proto_type); \ } \ UPB_INLINE upb_value upb_value_ ## name(type_t val) { \ upb_value ret; \ upb_value_set ## name(&ret, val); \ return ret; \ } \ UPB_INLINE type_t upb_value_get ## name(upb_value val) { \ assert(val.ctype == proto_type); \ return (type_t)(converter)val.val; \ } FUNCS(int32, int32, int32_t, int32_t, UPB_CTYPE_INT32) FUNCS(int64, int64, int64_t, int64_t, UPB_CTYPE_INT64) FUNCS(uint32, uint32, uint32_t, uint32_t, UPB_CTYPE_UINT32) FUNCS(uint64, uint64, uint64_t, uint64_t, UPB_CTYPE_UINT64) FUNCS(bool, _bool, bool, bool, UPB_CTYPE_BOOL) FUNCS(cstr, cstr, char*, uintptr_t, UPB_CTYPE_CSTR) FUNCS(ptr, ptr, void*, uintptr_t, UPB_CTYPE_PTR) FUNCS(constptr, constptr, const void*, uintptr_t, UPB_CTYPE_CONSTPTR) FUNCS(fptr, fptr, upb_func*, uintptr_t, UPB_CTYPE_FPTR) #undef FUNCS #undef SET_TYPE /* upb_tabkey *****************************************************************/ /* Either: * 1. an actual integer key, or * 2. a pointer to a string prefixed by its uint32_t length, owned by us. * * ...depending on whether this is a string table or an int table. We would * make this a union of those two types, but C89 doesn't support statically * initializing a non-first union member. */ typedef uintptr_t upb_tabkey; #define UPB_TABKEY_NUM(n) n #define UPB_TABKEY_NONE 0 /* The preprocessor isn't quite powerful enough to turn the compile-time string * length into a byte-wise string representation, so code generation needs to * help it along. * * "len1" is the low byte and len4 is the high byte. */ #ifdef UPB_BIG_ENDIAN #define UPB_TABKEY_STR(len1, len2, len3, len4, strval) \ (uintptr_t)(len4 len3 len2 len1 strval) #else #define UPB_TABKEY_STR(len1, len2, len3, len4, strval) \ (uintptr_t)(len1 len2 len3 len4 strval) #endif UPB_INLINE char *upb_tabstr(upb_tabkey key, uint32_t *len) { char* mem = (char*)key; if (len) memcpy(len, mem, sizeof(*len)); return mem + sizeof(*len); } /* upb_tabval *****************************************************************/ #ifdef __cplusplus /* Status initialization not supported. * * This separate definition is necessary because in C++, UINTPTR_MAX isn't * reliably available. */ typedef struct { uint64_t val; } upb_tabval; #else /* C -- supports static initialization, but to support static initialization of * both integers and points for both 32 and 64 bit targets, it takes a little * bit of doing. */ #if UINTPTR_MAX == 0xffffffffffffffffULL #define UPB_PTR_IS_64BITS #elif UINTPTR_MAX != 0xffffffff #error Could not determine how many bits pointers are. #endif typedef union { /* For static initialization. * * Unfortunately this ugliness is necessary -- it is the only way that we can, * with -std=c89 -pedantic, statically initialize this to either a pointer or * an integer on 32-bit platforms. */ struct { #ifdef UPB_PTR_IS_64BITS uintptr_t val; #else uintptr_t val1; uintptr_t val2; #endif } staticinit; /* The normal accessor that we use for everything at runtime. */ uint64_t val; } upb_tabval; #ifdef UPB_PTR_IS_64BITS #define UPB_TABVALUE_INT_INIT(v) {{v}} #define UPB_TABVALUE_EMPTY_INIT {{-1}} #else /* 32-bit pointers */ #ifdef UPB_BIG_ENDIAN #define UPB_TABVALUE_INT_INIT(v) {{0, v}} #define UPB_TABVALUE_EMPTY_INIT {{-1, -1}} #else #define UPB_TABVALUE_INT_INIT(v) {{v, 0}} #define UPB_TABVALUE_EMPTY_INIT {{-1, -1}} #endif #endif #define UPB_TABVALUE_PTR_INIT(v) UPB_TABVALUE_INT_INIT((uintptr_t)v) #undef UPB_PTR_IS_64BITS #endif /* __cplusplus */ /* upb_table ******************************************************************/ typedef struct _upb_tabent { upb_tabkey key; upb_tabval val; /* Internal chaining. This is const so we can create static initializers for * tables. We cast away const sometimes, but *only* when the containing * upb_table is known to be non-const. This requires a bit of care, but * the subtlety is confined to table.c. */ const struct _upb_tabent *next; } upb_tabent; typedef struct { size_t count; /* Number of entries in the hash part. */ size_t mask; /* Mask to turn hash value -> bucket. */ upb_ctype_t ctype; /* Type of all values. */ uint8_t size_lg2; /* Size of the hashtable part is 2^size_lg2 entries. */ /* Hash table entries. * Making this const isn't entirely accurate; what we really want is for it to * have the same const-ness as the table it's inside. But there's no way to * declare that in C. So we have to make it const so that we can statically * initialize const hash tables. Then we cast away const when we have to. */ const upb_tabent *entries; #ifndef NDEBUG /* This table's allocator. We make the user pass it in to every relevant * function and only use this to check it in debug mode. We do this solely * to keep upb_table as small as possible. This might seem slightly paranoid * but the plan is to use upb_table for all map fields and extension sets in * a forthcoming message representation, so there could be a lot of these. * If this turns out to be too annoying later, we can change it (since this * is an internal-only header file). */ upb_alloc *alloc; #endif } upb_table; #ifdef NDEBUG # define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \ {count, mask, ctype, size_lg2, entries} #else # ifdef UPB_DEBUG_REFS /* At the moment the only mutable tables we statically initialize are debug * ref tables. */ # define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \ {count, mask, ctype, size_lg2, entries, &upb_alloc_debugrefs} # else # define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \ {count, mask, ctype, size_lg2, entries, NULL} # endif #endif typedef struct { upb_table t; } upb_strtable; #define UPB_STRTABLE_INIT(count, mask, ctype, size_lg2, entries) \ {UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries)} #define UPB_EMPTY_STRTABLE_INIT(ctype) \ UPB_STRTABLE_INIT(0, 0, ctype, 0, NULL) typedef struct { upb_table t; /* For entries that don't fit in the array part. */ const upb_tabval *array; /* Array part of the table. See const note above. */ size_t array_size; /* Array part size. */ size_t array_count; /* Array part number of elements. */ } upb_inttable; #define UPB_INTTABLE_INIT(count, mask, ctype, size_lg2, ent, a, asize, acount) \ {UPB_TABLE_INIT(count, mask, ctype, size_lg2, ent), a, asize, acount} #define UPB_EMPTY_INTTABLE_INIT(ctype) \ UPB_INTTABLE_INIT(0, 0, ctype, 0, NULL, NULL, 0, 0) #define UPB_ARRAY_EMPTYENT -1 UPB_INLINE size_t upb_table_size(const upb_table *t) { if (t->size_lg2 == 0) return 0; else return 1 << t->size_lg2; } /* Internal-only functions, in .h file only out of necessity. */ UPB_INLINE bool upb_tabent_isempty(const upb_tabent *e) { return e->key == 0; } /* Used by some of the unit tests for generic hashing functionality. */ uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed); UPB_INLINE uintptr_t upb_intkey(uintptr_t key) { return key; } UPB_INLINE uint32_t upb_inthash(uintptr_t key) { return (uint32_t)key; } static const upb_tabent *upb_getentry(const upb_table *t, uint32_t hash) { return t->entries + (hash & t->mask); } UPB_INLINE bool upb_arrhas(upb_tabval key) { return key.val != (uint64_t)-1; } /* Initialize and uninitialize a table, respectively. If memory allocation * failed, false is returned that the table is uninitialized. */ bool upb_inttable_init2(upb_inttable *table, upb_ctype_t ctype, upb_alloc *a); bool upb_strtable_init2(upb_strtable *table, upb_ctype_t ctype, upb_alloc *a); void upb_inttable_uninit2(upb_inttable *table, upb_alloc *a); void upb_strtable_uninit2(upb_strtable *table, upb_alloc *a); UPB_INLINE bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype) { return upb_inttable_init2(table, ctype, &upb_alloc_global); } UPB_INLINE bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype) { return upb_strtable_init2(table, ctype, &upb_alloc_global); } UPB_INLINE void upb_inttable_uninit(upb_inttable *table) { upb_inttable_uninit2(table, &upb_alloc_global); } UPB_INLINE void upb_strtable_uninit(upb_strtable *table) { upb_strtable_uninit2(table, &upb_alloc_global); } /* Returns the number of values in the table. */ size_t upb_inttable_count(const upb_inttable *t); UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) { return t->t.count; } /* Inserts the given key into the hashtable with the given value. The key must * not already exist in the hash table. For string tables, the key must be * NULL-terminated, and the table will make an internal copy of the key. * Inttables must not insert a value of UINTPTR_MAX. * * If a table resize was required but memory allocation failed, false is * returned and the table is unchanged. */ bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val, upb_alloc *a); bool upb_strtable_insert3(upb_strtable *t, const char *key, size_t len, upb_value val, upb_alloc *a); UPB_INLINE bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) { return upb_inttable_insert2(t, key, val, &upb_alloc_global); } UPB_INLINE bool upb_strtable_insert2(upb_strtable *t, const char *key, size_t len, upb_value val) { return upb_strtable_insert3(t, key, len, val, &upb_alloc_global); } /* For NULL-terminated strings. */ UPB_INLINE bool upb_strtable_insert(upb_strtable *t, const char *key, upb_value val) { return upb_strtable_insert2(t, key, strlen(key), val); } /* Looks up key in this table, returning "true" if the key was found. * If v is non-NULL, copies the value for this key into *v. */ bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v); bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len, upb_value *v); /* For NULL-terminated strings. */ UPB_INLINE bool upb_strtable_lookup(const upb_strtable *t, const char *key, upb_value *v) { return upb_strtable_lookup2(t, key, strlen(key), v); } /* Removes an item from the table. Returns true if the remove was successful, * and stores the removed item in *val if non-NULL. */ bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val); bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len, upb_value *val, upb_alloc *alloc); UPB_INLINE bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len, upb_value *val) { return upb_strtable_remove3(t, key, len, val, &upb_alloc_global); } /* For NULL-terminated strings. */ UPB_INLINE bool upb_strtable_remove(upb_strtable *t, const char *key, upb_value *v) { return upb_strtable_remove2(t, key, strlen(key), v); } /* Updates an existing entry in an inttable. If the entry does not exist, * returns false and does nothing. Unlike insert/remove, this does not * invalidate iterators. */ bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val); /* Handy routines for treating an inttable like a stack. May not be mixed with * other insert/remove calls. */ bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a); upb_value upb_inttable_pop(upb_inttable *t); UPB_INLINE bool upb_inttable_push(upb_inttable *t, upb_value val) { return upb_inttable_push2(t, val, &upb_alloc_global); } /* Convenience routines for inttables with pointer keys. */ bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val, upb_alloc *a); bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val); bool upb_inttable_lookupptr( const upb_inttable *t, const void *key, upb_value *val); UPB_INLINE bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) { return upb_inttable_insertptr2(t, key, val, &upb_alloc_global); } /* Optimizes the table for the current set of entries, for both memory use and * lookup time. Client should call this after all entries have been inserted; * inserting more entries is legal, but will likely require a table resize. */ void upb_inttable_compact2(upb_inttable *t, upb_alloc *a); UPB_INLINE void upb_inttable_compact(upb_inttable *t) { upb_inttable_compact2(t, &upb_alloc_global); } /* A special-case inlinable version of the lookup routine for 32-bit * integers. */ UPB_INLINE bool upb_inttable_lookup32(const upb_inttable *t, uint32_t key, upb_value *v) { *v = upb_value_int32(0); /* Silence compiler warnings. */ if (key < t->array_size) { upb_tabval arrval = t->array[key]; if (upb_arrhas(arrval)) { _upb_value_setval(v, arrval.val, t->t.ctype); return true; } else { return false; } } else { const upb_tabent *e; if (t->t.entries == NULL) return false; for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) { if ((uint32_t)e->key == key) { _upb_value_setval(v, e->val.val, t->t.ctype); return true; } if (e->next == NULL) return false; } } } /* Exposed for testing only. */ bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a); /* Iterators ******************************************************************/ /* Iterators for int and string tables. We are subject to some kind of unusual * design constraints: * * For high-level languages: * - we must be able to guarantee that we don't crash or corrupt memory even if * the program accesses an invalidated iterator. * * For C++11 range-based for: * - iterators must be copyable * - iterators must be comparable * - it must be possible to construct an "end" value. * * Iteration order is undefined. * * Modifying the table invalidates iterators. upb_{str,int}table_done() is * guaranteed to work even on an invalidated iterator, as long as the table it * is iterating over has not been freed. Calling next() or accessing data from * an invalidated iterator yields unspecified elements from the table, but it is * guaranteed not to crash and to return real table elements (except when done() * is true). */ /* upb_strtable_iter **********************************************************/ /* upb_strtable_iter i; * upb_strtable_begin(&i, t); * for(; !upb_strtable_done(&i); upb_strtable_next(&i)) { * const char *key = upb_strtable_iter_key(&i); * const upb_value val = upb_strtable_iter_value(&i); * // ... * } */ typedef struct { const upb_strtable *t; size_t index; } upb_strtable_iter; void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t); void upb_strtable_next(upb_strtable_iter *i); bool upb_strtable_done(const upb_strtable_iter *i); const char *upb_strtable_iter_key(const upb_strtable_iter *i); size_t upb_strtable_iter_keylength(const upb_strtable_iter *i); upb_value upb_strtable_iter_value(const upb_strtable_iter *i); void upb_strtable_iter_setdone(upb_strtable_iter *i); bool upb_strtable_iter_isequal(const upb_strtable_iter *i1, const upb_strtable_iter *i2); /* upb_inttable_iter **********************************************************/ /* upb_inttable_iter i; * upb_inttable_begin(&i, t); * for(; !upb_inttable_done(&i); upb_inttable_next(&i)) { * uintptr_t key = upb_inttable_iter_key(&i); * upb_value val = upb_inttable_iter_value(&i); * // ... * } */ typedef struct { const upb_inttable *t; size_t index; bool array_part; } upb_inttable_iter; void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t); void upb_inttable_next(upb_inttable_iter *i); bool upb_inttable_done(const upb_inttable_iter *i); uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i); upb_value upb_inttable_iter_value(const upb_inttable_iter *i); void upb_inttable_iter_setdone(upb_inttable_iter *i); bool upb_inttable_iter_isequal(const upb_inttable_iter *i1, const upb_inttable_iter *i2); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* UPB_TABLE_H_ */ /* Reference tracking will check ref()/unref() operations to make sure the * ref ownership is correct. Where possible it will also make tools like * Valgrind attribute ref leaks to the code that took the leaked ref, not * the code that originally created the object. * * Enabling this requires the application to define upb_lock()/upb_unlock() * functions that acquire/release a global mutex (or #define UPB_THREAD_UNSAFE). * For this reason we don't enable it by default, even in debug builds. */ /* #define UPB_DEBUG_REFS */ #ifdef __cplusplus namespace upb { class RefCounted; template
class reffed_ptr; } #endif UPB_DECLARE_TYPE(upb::RefCounted, upb_refcounted) struct upb_refcounted_vtbl; #ifdef __cplusplus class upb::RefCounted { public: /* Returns true if the given object is frozen. */ bool IsFrozen() const; /* Increases the ref count, the new ref is owned by "owner" which must not * already own a ref (and should not itself be a refcounted object if the ref * could possibly be circular; see below). * Thread-safe iff "this" is frozen. */ void Ref(const void *owner) const; /* Release a ref that was acquired from upb_refcounted_ref() and collects any * objects it can. */ void Unref(const void *owner) const; /* Moves an existing ref from "from" to "to", without changing the overall * ref count. DonateRef(foo, NULL, owner) is the same as Ref(foo, owner), * but "to" may not be NULL. */ void DonateRef(const void *from, const void *to) const; /* Verifies that a ref to the given object is currently held by the given * owner. Only effective in UPB_DEBUG_REFS builds. */ void CheckRef(const void *owner) const; private: UPB_DISALLOW_POD_OPS(RefCounted, upb::RefCounted) #else struct upb_refcounted { #endif /* TODO(haberman): move the actual structure definition to structdefs.int.h. * The only reason they are here is because inline functions need to see the * definition of upb_handlers, which needs to see this definition. But we * can change the upb_handlers inline functions to deal in raw offsets * instead. */ /* A single reference count shared by all objects in the group. */ uint32_t *group; /* A singly-linked list of all objects in the group. */ upb_refcounted *next; /* Table of function pointers for this type. */ const struct upb_refcounted_vtbl *vtbl; /* Maintained only when mutable, this tracks the number of refs (but not * ref2's) to this object. *group should be the sum of all individual_count * in the group. */ uint32_t individual_count; bool is_frozen; #ifdef UPB_DEBUG_REFS upb_inttable *refs; /* Maps owner -> trackedref for incoming refs. */ upb_inttable *ref2s; /* Set of targets for outgoing ref2s. */ #endif }; #ifdef UPB_DEBUG_REFS extern upb_alloc upb_alloc_debugrefs; #define UPB_REFCOUNT_INIT(vtbl, refs, ref2s) \ {&static_refcount, NULL, vtbl, 0, true, refs, ref2s} #else #define UPB_REFCOUNT_INIT(vtbl, refs, ref2s) \ {&static_refcount, NULL, vtbl, 0, true} #endif UPB_BEGIN_EXTERN_C /* It is better to use tracked refs when possible, for the extra debugging * capability. But if this is not possible (because you don't have easy access * to a stable pointer value that is associated with the ref), you can pass * UPB_UNTRACKED_REF instead. */ extern const void *UPB_UNTRACKED_REF; /* Native C API. */ bool upb_refcounted_isfrozen(const upb_refcounted *r); void upb_refcounted_ref(const upb_refcounted *r, const void *owner); void upb_refcounted_unref(const upb_refcounted *r, const void *owner); void upb_refcounted_donateref( const upb_refcounted *r, const void *from, const void *to); void upb_refcounted_checkref(const upb_refcounted *r, const void *owner); #define UPB_REFCOUNTED_CMETHODS(type, upcastfunc) \ UPB_INLINE bool type ## _isfrozen(const type *v) { \ return upb_refcounted_isfrozen(upcastfunc(v)); \ } \ UPB_INLINE void type ## _ref(const type *v, const void *owner) { \ upb_refcounted_ref(upcastfunc(v), owner); \ } \ UPB_INLINE void type ## _unref(const type *v, const void *owner) { \ upb_refcounted_unref(upcastfunc(v), owner); \ } \ UPB_INLINE void type ## _donateref(const type *v, const void *from, const void *to) { \ upb_refcounted_donateref(upcastfunc(v), from, to); \ } \ UPB_INLINE void type ## _checkref(const type *v, const void *owner) { \ upb_refcounted_checkref(upcastfunc(v), owner); \ } #define UPB_REFCOUNTED_CPPMETHODS \ bool IsFrozen() const { \ return upb::upcast_to
(this)->IsFrozen(); \ } \ void Ref(const void *owner) const { \ return upb::upcast_to
(this)->Ref(owner); \ } \ void Unref(const void *owner) const { \ return upb::upcast_to
(this)->Unref(owner); \ } \ void DonateRef(const void *from, const void *to) const { \ return upb::upcast_to
(this)->DonateRef(from, to); \ } \ void CheckRef(const void *owner) const { \ return upb::upcast_to
(this)->CheckRef(owner); \ } /* Internal-to-upb Interface **************************************************/ typedef void upb_refcounted_visit(const upb_refcounted *r, const upb_refcounted *subobj, void *closure); struct upb_refcounted_vtbl { /* Must visit all subobjects that are currently ref'd via upb_refcounted_ref2. * Must be longjmp()-safe. */ void (*visit)(const upb_refcounted *r, upb_refcounted_visit *visit, void *c); /* Must free the object and release all references to other objects. */ void (*free)(upb_refcounted *r); }; /* Initializes the refcounted with a single ref for the given owner. Returns * false if memory could not be allocated. */ bool upb_refcounted_init(upb_refcounted *r, const struct upb_refcounted_vtbl *vtbl, const void *owner); /* Adds a ref from one refcounted object to another ("from" must not already * own a ref). These refs may be circular; cycles will be collected correctly * (if conservatively). These refs do not need to be freed in from's free() * function. */ void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from); /* Removes a ref that was acquired from upb_refcounted_ref2(), and collects any * object it can. This is only necessary when "from" no longer points to "r", * and not from from's "free" function. */ void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from); #define upb_ref2(r, from) \ upb_refcounted_ref2((const upb_refcounted*)r, (upb_refcounted*)from) #define upb_unref2(r, from) \ upb_refcounted_unref2((const upb_refcounted*)r, (upb_refcounted*)from) /* Freezes all mutable object reachable by ref2() refs from the given roots. * This will split refcounting groups into precise SCC groups, so that * refcounting of frozen objects can be more aggressive. If memory allocation * fails, or if more than 2**31 mutable objects are reachable from "roots", or * if the maximum depth of the graph exceeds "maxdepth", false is returned and * the objects are unchanged. * * After this operation succeeds, the objects are frozen/const, and may not be * used through non-const pointers. In particular, they may not be passed as * the second parameter of upb_refcounted_{ref,unref}2(). On the upside, all * operations on frozen refcounteds are threadsafe, and objects will be freed * at the precise moment that they become unreachable. * * Caller must own refs on each object in the "roots" list. */ bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s, int maxdepth); /* Shared by all compiled-in refcounted objects. */ extern uint32_t static_refcount; UPB_END_EXTERN_C #ifdef __cplusplus /* C++ Wrappers. */ namespace upb { inline bool RefCounted::IsFrozen() const { return upb_refcounted_isfrozen(this); } inline void RefCounted::Ref(const void *owner) const { upb_refcounted_ref(this, owner); } inline void RefCounted::Unref(const void *owner) const { upb_refcounted_unref(this, owner); } inline void RefCounted::DonateRef(const void *from, const void *to) const { upb_refcounted_donateref(this, from, to); } inline void RefCounted::CheckRef(const void *owner) const { upb_refcounted_checkref(this, owner); } } /* namespace upb */ #endif /* upb::reffed_ptr ************************************************************/ #ifdef __cplusplus #include
/* For std::swap(). */ /* Provides RAII semantics for upb refcounted objects. Each reffed_ptr owns a * ref on whatever object it points to (if any). */ template
class upb::reffed_ptr { public: reffed_ptr() : ptr_(NULL) {} /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */ template
reffed_ptr(U* val, const void* ref_donor = NULL) : ptr_(upb::upcast(val)) { if (ref_donor) { assert(ptr_); ptr_->DonateRef(ref_donor, this); } else if (ptr_) { ptr_->Ref(this); } } template
reffed_ptr(const reffed_ptr
& other) : ptr_(upb::upcast(other.get())) { if (ptr_) ptr_->Ref(this); } reffed_ptr(const reffed_ptr& other) : ptr_(upb::upcast(other.get())) { if (ptr_) ptr_->Ref(this); } ~reffed_ptr() { if (ptr_) ptr_->Unref(this); } template
reffed_ptr& operator=(const reffed_ptr
& other) { reset(other.get()); return *this; } reffed_ptr& operator=(const reffed_ptr& other) { reset(other.get()); return *this; } /* TODO(haberman): add C++11 move construction/assignment for greater * efficiency. */ void swap(reffed_ptr& other) { if (ptr_ == other.ptr_) { return; } if (ptr_) ptr_->DonateRef(this, &other); if (other.ptr_) other.ptr_->DonateRef(&other, this); std::swap(ptr_, other.ptr_); } T& operator*() const { assert(ptr_); return *ptr_; } T* operator->() const { assert(ptr_); return ptr_; } T* get() const { return ptr_; } /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */ template
void reset(U* ptr = NULL, const void* ref_donor = NULL) { reffed_ptr(ptr, ref_donor).swap(*this); } template
reffed_ptr
down_cast() { return reffed_ptr
(upb::down_cast
(get())); } template
reffed_ptr
dyn_cast() { return reffed_ptr
(upb::dyn_cast
(get())); } /* Plain release() is unsafe; if we were the only owner, it would leak the * object. Instead we provide this: */ T* ReleaseTo(const void* new_owner) { T* ret = NULL; ptr_->DonateRef(this, new_owner); std::swap(ret, ptr_); return ret; } private: T* ptr_; }; #endif /* __cplusplus */ #endif /* UPB_REFCOUNT_H_ */ #ifdef __cplusplus #include
#include
#include
namespace upb { class Def; class EnumDef; class FieldDef; class FileDef; class MessageDef; class OneofDef; } #endif UPB_DECLARE_DERIVED_TYPE(upb::Def, upb::RefCounted, upb_def, upb_refcounted) UPB_DECLARE_DERIVED_TYPE(upb::OneofDef, upb::RefCounted, upb_oneofdef, upb_refcounted) UPB_DECLARE_DERIVED_TYPE(upb::FileDef, upb::RefCounted, upb_filedef, upb_refcounted) /* The maximum message depth that the type graph can have. This is a resource * limit for the C stack since we sometimes need to recursively traverse the * graph. Cycles are ok; the traversal will stop when it detects a cycle, but * we must hit the cycle before the maximum depth is reached. * * If having a single static limit is too inflexible, we can add another variant * of Def::Freeze that allows specifying this as a parameter. */ #define UPB_MAX_MESSAGE_DEPTH 64 /* upb::Def: base class for top-level defs ***********************************/ /* All the different kind of defs that can be defined at the top-level and put * in a SymbolTable or appear in a FileDef::defs() list. This excludes some * defs (like oneofs and files). It only includes fields because they can be * defined as extensions. */ typedef enum { UPB_DEF_MSG, UPB_DEF_FIELD, UPB_DEF_ENUM, UPB_DEF_SERVICE, /* Not yet implemented. */ UPB_DEF_ANY = -1 /* Wildcard for upb_symtab_get*() */ } upb_deftype_t; #ifdef __cplusplus /* The base class of all defs. Its base is upb::RefCounted (use upb::upcast() * to convert). */ class upb::Def { public: typedef upb_deftype_t Type; Def* Dup(const void *owner) const; /* upb::RefCounted methods like Ref()/Unref(). */ UPB_REFCOUNTED_CPPMETHODS Type def_type() const; /* "fullname" is the def's fully-qualified name (eg. foo.bar.Message). */ const char *full_name() const; /* The final part of a def's name (eg. Message). */ const char *name() const; /* The def must be mutable. Caller retains ownership of fullname. Defs are * not required to have a name; if a def has no name when it is frozen, it * will remain an anonymous def. On failure, returns false and details in "s" * if non-NULL. */ bool set_full_name(const char* fullname, upb::Status* s); bool set_full_name(const std::string &fullname, upb::Status* s); /* The file in which this def appears. It is not necessary to add a def to a * file (and consequently the accessor may return NULL). Set this by calling * file->Add(def). */ FileDef* file() const; /* Freezes the given defs; this validates all constraints and marks the defs * as frozen (read-only). "defs" may not contain any fielddefs, but fields * of any msgdefs will be frozen. * * Symbolic references to sub-types and enum defaults must have already been * resolved. Any mutable defs reachable from any of "defs" must also be in * the list; more formally, "defs" must be a transitive closure of mutable * defs. * * After this operation succeeds, the finalized defs must only be accessed * through a const pointer! */ static bool Freeze(Def* const* defs, size_t n, Status* status); static bool Freeze(const std::vector
& defs, Status* status); private: UPB_DISALLOW_POD_OPS(Def, upb::Def) }; #endif /* __cplusplus */ UPB_BEGIN_EXTERN_C /* Native C API. */ upb_def *upb_def_dup(const upb_def *def, const void *owner); /* Include upb_refcounted methods like upb_def_ref()/upb_def_unref(). */ UPB_REFCOUNTED_CMETHODS(upb_def, upb_def_upcast) upb_deftype_t upb_def_type(const upb_def *d); const char *upb_def_fullname(const upb_def *d); const char *upb_def_name(const upb_def *d); const upb_filedef *upb_def_file(const upb_def *d); bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s); bool upb_def_freeze(upb_def *const *defs, size_t n, upb_status *s); /* Temporary API: for internal use only. */ bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s); UPB_END_EXTERN_C /* upb::Def casts *************************************************************/ #ifdef __cplusplus #define UPB_CPP_CASTS(cname, cpptype) \ namespace upb { \ template <> \ inline cpptype *down_cast
(Def * def) { \ return upb_downcast_##cname##_mutable(def); \ } \ template <> \ inline cpptype *dyn_cast
(Def * def) { \ return upb_dyncast_##cname##_mutable(def); \ } \ template <> \ inline const cpptype *down_cast
( \ const Def *def) { \ return upb_downcast_##cname(def); \ } \ template <> \ inline const cpptype *dyn_cast
(const Def *def) { \ return upb_dyncast_##cname(def); \ } \ template <> \ inline const cpptype *down_cast
(Def * def) { \ return upb_downcast_##cname(def); \ } \ template <> \ inline const cpptype *dyn_cast
(Def * def) { \ return upb_dyncast_##cname(def); \ } \ } /* namespace upb */ #else #define UPB_CPP_CASTS(cname, cpptype) #endif /* __cplusplus */ /* Dynamic casts, for determining if a def is of a particular type at runtime. * Downcasts, for when some wants to assert that a def is of a particular type. * These are only checked if we are building debug. */ #define UPB_DEF_CASTS(lower, upper, cpptype) \ UPB_INLINE const upb_##lower *upb_dyncast_##lower(const upb_def *def) { \ if (upb_def_type(def) != UPB_DEF_##upper) return NULL; \ return (upb_##lower *)def; \ } \ UPB_INLINE const upb_##lower *upb_downcast_##lower(const upb_def *def) { \ assert(upb_def_type(def) == UPB_DEF_##upper); \ return (const upb_##lower *)def; \ } \ UPB_INLINE upb_##lower *upb_dyncast_##lower##_mutable(upb_def *def) { \ return (upb_##lower *)upb_dyncast_##lower(def); \ } \ UPB_INLINE upb_##lower *upb_downcast_##lower##_mutable(upb_def *def) { \ return (upb_##lower *)upb_downcast_##lower(def); \ } \ UPB_CPP_CASTS(lower, cpptype) #define UPB_DEFINE_DEF(cppname, lower, upper, cppmethods, members) \ UPB_DEFINE_CLASS2(cppname, upb::Def, upb::RefCounted, cppmethods, \ members) \ UPB_DEF_CASTS(lower, upper, cppname) #define UPB_DECLARE_DEF_TYPE(cppname, lower, upper) \ UPB_DECLARE_DERIVED_TYPE2(cppname, upb::Def, upb::RefCounted, \ upb_ ## lower, upb_def, upb_refcounted) \ UPB_DEF_CASTS(lower, upper, cppname) UPB_DECLARE_DEF_TYPE(upb::FieldDef, fielddef, FIELD) UPB_DECLARE_DEF_TYPE(upb::MessageDef, msgdef, MSG) UPB_DECLARE_DEF_TYPE(upb::EnumDef, enumdef, ENUM) #undef UPB_DECLARE_DEF_TYPE #undef UPB_DEF_CASTS #undef UPB_CPP_CASTS /* upb::FieldDef **************************************************************/ /* The types a field can have. Note that this list is not identical to the * types defined in descriptor.proto, which gives INT32 and SINT32 separate * types (we distinguish the two with the "integer encoding" enum below). */ typedef enum { UPB_TYPE_FLOAT = 1, UPB_TYPE_DOUBLE = 2, UPB_TYPE_BOOL = 3, UPB_TYPE_STRING = 4, UPB_TYPE_BYTES = 5, UPB_TYPE_MESSAGE = 6, UPB_TYPE_ENUM = 7, /* Enum values are int32. */ UPB_TYPE_INT32 = 8, UPB_TYPE_UINT32 = 9, UPB_TYPE_INT64 = 10, UPB_TYPE_UINT64 = 11 } upb_fieldtype_t; /* The repeated-ness of each field; this matches descriptor.proto. */ typedef enum { UPB_LABEL_OPTIONAL = 1, UPB_LABEL_REQUIRED = 2, UPB_LABEL_REPEATED = 3 } upb_label_t; /* How integers should be encoded in serializations that offer multiple * integer encoding methods. */ typedef enum { UPB_INTFMT_VARIABLE = 1, UPB_INTFMT_FIXED = 2, UPB_INTFMT_ZIGZAG = 3 /* Only for signed types (INT32/INT64). */ } upb_intfmt_t; /* Descriptor types, as defined in descriptor.proto. */ typedef enum { UPB_DESCRIPTOR_TYPE_DOUBLE = 1, UPB_DESCRIPTOR_TYPE_FLOAT = 2, UPB_DESCRIPTOR_TYPE_INT64 = 3, UPB_DESCRIPTOR_TYPE_UINT64 = 4, UPB_DESCRIPTOR_TYPE_INT32 = 5, UPB_DESCRIPTOR_TYPE_FIXED64 = 6, UPB_DESCRIPTOR_TYPE_FIXED32 = 7, UPB_DESCRIPTOR_TYPE_BOOL = 8, UPB_DESCRIPTOR_TYPE_STRING = 9, UPB_DESCRIPTOR_TYPE_GROUP = 10, UPB_DESCRIPTOR_TYPE_MESSAGE = 11, UPB_DESCRIPTOR_TYPE_BYTES = 12, UPB_DESCRIPTOR_TYPE_UINT32 = 13, UPB_DESCRIPTOR_TYPE_ENUM = 14, UPB_DESCRIPTOR_TYPE_SFIXED32 = 15, UPB_DESCRIPTOR_TYPE_SFIXED64 = 16, UPB_DESCRIPTOR_TYPE_SINT32 = 17, UPB_DESCRIPTOR_TYPE_SINT64 = 18 } upb_descriptortype_t; typedef enum { UPB_SYNTAX_PROTO2 = 2, UPB_SYNTAX_PROTO3 = 3 } upb_syntax_t; /* Maximum field number allowed for FieldDefs. This is an inherent limit of the * protobuf wire format. */ #define UPB_MAX_FIELDNUMBER ((1 << 29) - 1) #ifdef __cplusplus /* A upb_fielddef describes a single field in a message. It is most often * found as a part of a upb_msgdef, but can also stand alone to represent * an extension. * * Its base class is upb::Def (use upb::upcast() to convert). */ class upb::FieldDef { public: typedef upb_fieldtype_t Type; typedef upb_label_t Label; typedef upb_intfmt_t IntegerFormat; typedef upb_descriptortype_t DescriptorType; /* These return true if the given value is a valid member of the enumeration. */ static bool CheckType(int32_t val); static bool CheckLabel(int32_t val); static bool CheckDescriptorType(int32_t val); static bool CheckIntegerFormat(int32_t val); /* These convert to the given enumeration; they require that the value is * valid. */ static Type ConvertType(int32_t val); static Label ConvertLabel(int32_t val); static DescriptorType ConvertDescriptorType(int32_t val); static IntegerFormat ConvertIntegerFormat(int32_t val); /* Returns NULL if memory allocation failed. */ static reffed_ptr
New(); /* Duplicates the given field, returning NULL if memory allocation failed. * When a fielddef is duplicated, the subdef (if any) is made symbolic if it * wasn't already. If the subdef is set but has no name (which is possible * since msgdefs are not required to have a name) the new fielddef's subdef * will be unset. */ FieldDef* Dup(const void* owner) const; /* upb::RefCounted methods like Ref()/Unref(). */ UPB_REFCOUNTED_CPPMETHODS /* Functionality from upb::Def. */ const char* full_name() const; bool type_is_set() const; /* set_[descriptor_]type() has been called? */ Type type() const; /* Requires that type_is_set() == true. */ Label label() const; /* Defaults to UPB_LABEL_OPTIONAL. */ const char* name() const; /* NULL if uninitialized. */ uint32_t number() const; /* Returns 0 if uninitialized. */ bool is_extension() const; /* Copies the JSON name for this field into the given buffer. Returns the * actual size of the JSON name, including the NULL terminator. If the * return value is 0, the JSON name is unset. If the return value is * greater than len, the JSON name was truncated. The buffer is always * NULL-terminated if len > 0. * * The JSON name always defaults to a camelCased version of the regular * name. However if the regular name is unset, the JSON name will be unset * also. */ size_t GetJsonName(char* buf, size_t len) const; /* Convenience version of the above function which copies the JSON name * into the given string, returning false if the name is not set. */ template
bool GetJsonName(T* str) { str->resize(GetJsonName(NULL, 0)); GetJsonName(&(*str)[0], str->size()); return str->size() > 0; } /* For UPB_TYPE_MESSAGE fields only where is_tag_delimited() == false, * indicates whether this field should have lazy parsing handlers that yield * the unparsed string for the submessage. * * TODO(haberman): I think we want to move this into a FieldOptions container * when we add support for custom options (the FieldOptions struct will * contain both regular FieldOptions like "lazy" *and* custom options). */ bool lazy() const; /* For non-string, non-submessage fields, this indicates whether binary * protobufs are encoded in packed or non-packed format. * * TODO(haberman): see note above about putting options like this into a * FieldOptions container. */ bool packed() const; /* An integer that can be used as an index into an array of fields for * whatever message this field belongs to. Guaranteed to be less than * f->containing_type()->field_count(). May only be accessed once the def has * been finalized. */ uint32_t index() const; /* The MessageDef to which this field belongs. * * If this field has been added to a MessageDef, that message can be retrieved * directly (this is always the case for frozen FieldDefs). * * If the field has not yet been added to a MessageDef, you can set the name * of the containing type symbolically instead. This is mostly useful for * extensions, where the extension is declared separately from the message. */ const MessageDef* containing_type() const; const char* containing_type_name(); /* The OneofDef to which this field belongs, or NULL if this field is not part * of a oneof. */ const OneofDef* containing_oneof() const; /* The field's type according to the enum in descriptor.proto. This is not * the same as UPB_TYPE_*, because it distinguishes between (for example) * INT32 and SINT32, whereas our "type" enum does not. This return of * descriptor_type() is a function of type(), integer_format(), and * is_tag_delimited(). Likewise set_descriptor_type() sets all three * appropriately. */ DescriptorType descriptor_type() const; /* Convenient field type tests. */ bool IsSubMessage() const; bool IsString() const; bool IsSequence() const; bool IsPrimitive() const; bool IsMap() const; /* Whether this field must be able to explicitly represent presence: * * * This is always false for repeated fields (an empty repeated field is * equivalent to a repeated field with zero entries). * * * This is always true for submessages. * * * For other fields, it depends on the message (see * MessageDef::SetPrimitivesHavePresence()) */ bool HasPresence() const; /* How integers are encoded. Only meaningful for integer types. * Defaults to UPB_INTFMT_VARIABLE, and is reset when "type" changes. */ IntegerFormat integer_format() const; /* Whether a submessage field is tag-delimited or not (if false, then * length-delimited). May only be set when type() == UPB_TYPE_MESSAGE. */ bool is_tag_delimited() const; /* Returns the non-string default value for this fielddef, which may either * be something the client set explicitly or the "default default" (0 for * numbers, empty for strings). The field's type indicates the type of the * returned value, except for enum fields that are still mutable. * * Requires that the given function matches the field's current type. */ int64_t default_int64() const; int32_t default_int32() const; uint64_t default_uint64() const; uint32_t default_uint32() const; bool default_bool() const; float default_float() const; double default_double() const; /* The resulting string is always NULL-terminated. If non-NULL, the length * will be stored in *len. */ const char *default_string(size_t* len) const; /* For frozen UPB_TYPE_ENUM fields, enum defaults can always be read as either * string or int32, and both of these methods will always return true. * * For mutable UPB_TYPE_ENUM fields, the story is a bit more complicated. * Enum defaults are unusual. They can be specified either as string or int32, * but to be valid the enum must have that value as a member. And if no * default is specified, the "default default" comes from the EnumDef. * * We allow reading the default as either an int32 or a string, but only if * we have a meaningful value to report. We have a meaningful value if it was * set explicitly, or if we could get the "default default" from the EnumDef. * Also if you explicitly set the name and we find the number in the EnumDef */ bool EnumHasStringDefault() const; bool EnumHasInt32Default() const; /* Submessage and enum fields must reference a "subdef", which is the * upb::MessageDef or upb::EnumDef that defines their type. Note that when * the FieldDef is mutable it may not have a subdef *yet*, but this function * still returns true to indicate that the field's type requires a subdef. */ bool HasSubDef() const; /* Returns the enum or submessage def for this field, if any. The field's * type must match (ie. you may only call enum_subdef() for fields where * type() == UPB_TYPE_ENUM). Returns NULL if the subdef has not been set or * is currently set symbolically. */ const EnumDef* enum_subdef() const; const MessageDef* message_subdef() const; /* Returns the generic subdef for this field. Requires that HasSubDef() (ie. * only works for UPB_TYPE_ENUM and UPB_TYPE_MESSAGE fields). */ const Def* subdef() const; /* Returns the symbolic name of the subdef. If the subdef is currently set * unresolved (ie. set symbolically) returns the symbolic name. If it has * been resolved to a specific subdef, returns the name from that subdef. */ const char* subdef_name() const; /* Setters (non-const methods), only valid for mutable FieldDefs! ***********/ bool set_full_name(const char* fullname, upb::Status* s); bool set_full_name(const std::string& fullname, upb::Status* s); /* This may only be called if containing_type() == NULL (ie. the field has not * been added to a message yet). */ bool set_containing_type_name(const char *name, Status* status); bool set_containing_type_name(const std::string& name, Status* status); /* Defaults to false. When we freeze, we ensure that this can only be true * for length-delimited message fields. Prior to freezing this can be true or * false with no restrictions. */ void set_lazy(bool lazy); /* Defaults to true. Sets whether this field is encoded in packed format. */ void set_packed(bool packed); /* "type" or "descriptor_type" MUST be set explicitly before the fielddef is * finalized. These setters require that the enum value is valid; if the * value did not come directly from an enum constant, the caller should * validate it first with the functions above (CheckFieldType(), etc). */ void set_type(Type type); void set_label(Label label); void set_descriptor_type(DescriptorType type); void set_is_extension(bool is_extension); /* "number" and "name" must be set before the FieldDef is added to a * MessageDef, and may not be set after that. * * "name" is the same as full_name()/set_full_name(), but since fielddefs * most often use simple, non-qualified names, we provide this accessor * also. Generally only extensions will want to think of this name as * fully-qualified. */ bool set_number(uint32_t number, upb::Status* s); bool set_name(const char* name, upb::Status* s); bool set_name(const std::string& name, upb::Status* s); /* Sets the JSON name to the given string. */ /* TODO(haberman): implement. Right now only default json_name (camelCase) * is supported. */ bool set_json_name(const char* json_name, upb::Status* s); bool set_json_name(const std::string& name, upb::Status* s); /* Clears the JSON name. This will make it revert to its default, which is * a camelCased version of the regular field name. */ void clear_json_name(); void set_integer_format(IntegerFormat format); bool set_tag_delimited(bool tag_delimited, upb::Status* s); /* Sets default value for the field. The call must exactly match the type * of the field. Enum fields may use either setint32 or setstring to set * the default numerically or symbolically, respectively, but symbolic * defaults must be resolved before finalizing (see ResolveEnumDefault()). * * Changing the type of a field will reset its default. */ void set_default_int64(int64_t val); void set_default_int32(int32_t val); void set_default_uint64(uint64_t val); void set_default_uint32(uint32_t val); void set_default_bool(bool val); void set_default_float(float val); void set_default_double(double val); bool set_default_string(const void *str, size_t len, Status *s); bool set_default_string(const std::string &str, Status *s); void set_default_cstr(const char *str, Status *s); /* Before a fielddef is frozen, its subdef may be set either directly (with a * upb::Def*) or symbolically. Symbolic refs must be resolved before the * containing msgdef can be frozen (see upb_resolve() above). upb always * guarantees that any def reachable from a live def will also be kept alive. * * Both methods require that upb_hassubdef(f) (so the type must be set prior * to calling these methods). Returns false if this is not the case, or if * the given subdef is not of the correct type. The subdef is reset if the * field's type is changed. The subdef can be set to NULL to clear it. */ bool set_subdef(const Def* subdef, Status* s); bool set_enum_subdef(const EnumDef* subdef, Status* s); bool set_message_subdef(const MessageDef* subdef, Status* s); bool set_subdef_name(const char* name, Status* s); bool set_subdef_name(const std::string &name, Status* s); private: UPB_DISALLOW_POD_OPS(FieldDef, upb::FieldDef) }; # endif /* defined(__cplusplus) */ UPB_BEGIN_EXTERN_C /* Native C API. */ upb_fielddef *upb_fielddef_new(const void *owner); upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner); /* Include upb_refcounted methods like upb_fielddef_ref(). */ UPB_REFCOUNTED_CMETHODS(upb_fielddef, upb_fielddef_upcast2) /* Methods from upb_def. */ const char *upb_fielddef_fullname(const upb_fielddef *f); bool upb_fielddef_setfullname(upb_fielddef *f, const char *fullname, upb_status *s); bool upb_fielddef_typeisset(const upb_fielddef *f); upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f); upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f); upb_label_t upb_fielddef_label(const upb_fielddef *f); uint32_t upb_fielddef_number(const upb_fielddef *f); const char *upb_fielddef_name(const upb_fielddef *f); bool upb_fielddef_isextension(const upb_fielddef *f); bool upb_fielddef_lazy(const upb_fielddef *f); bool upb_fielddef_packed(const upb_fielddef *f); size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len); const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f); const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f); upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f); const char *upb_fielddef_containingtypename(upb_fielddef *f); upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f); uint32_t upb_fielddef_index(const upb_fielddef *f); bool upb_fielddef_istagdelim(const upb_fielddef *f); bool upb_fielddef_issubmsg(const upb_fielddef *f); bool upb_fielddef_isstring(const upb_fielddef *f); bool upb_fielddef_isseq(const upb_fielddef *f); bool upb_fielddef_isprimitive(const upb_fielddef *f); bool upb_fielddef_ismap(const upb_fielddef *f); bool upb_fielddef_haspresence(const upb_fielddef *f); int64_t upb_fielddef_defaultint64(const upb_fielddef *f); int32_t upb_fielddef_defaultint32(const upb_fielddef *f); uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f); uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f); bool upb_fielddef_defaultbool(const upb_fielddef *f); float upb_fielddef_defaultfloat(const upb_fielddef *f); double upb_fielddef_defaultdouble(const upb_fielddef *f); const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len); bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f); bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f); bool upb_fielddef_hassubdef(const upb_fielddef *f); const upb_def *upb_fielddef_subdef(const upb_fielddef *f); const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f); const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f); const char *upb_fielddef_subdefname(const upb_fielddef *f); void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type); void upb_fielddef_setdescriptortype(upb_fielddef *f, int type); void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label); bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s); bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s); bool upb_fielddef_setjsonname(upb_fielddef *f, const char *name, upb_status *s); bool upb_fielddef_clearjsonname(upb_fielddef *f); bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name, upb_status *s); void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension); void upb_fielddef_setlazy(upb_fielddef *f, bool lazy); void upb_fielddef_setpacked(upb_fielddef *f, bool packed); void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt); void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim); void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t val); void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t val); void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t val); void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t val); void upb_fielddef_setdefaultbool(upb_fielddef *f, bool val); void upb_fielddef_setdefaultfloat(upb_fielddef *f, float val); void upb_fielddef_setdefaultdouble(upb_fielddef *f, double val); bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len, upb_status *s); void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str, upb_status *s); bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef, upb_status *s); bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef, upb_status *s); bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef, upb_status *s); bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name, upb_status *s); bool upb_fielddef_checklabel(int32_t label); bool upb_fielddef_checktype(int32_t type); bool upb_fielddef_checkdescriptortype(int32_t type); bool upb_fielddef_checkintfmt(int32_t fmt); UPB_END_EXTERN_C /* upb::MessageDef ************************************************************/ typedef upb_inttable_iter upb_msg_field_iter; typedef upb_strtable_iter upb_msg_oneof_iter; /* Well-known field tag numbers for map-entry messages. */ #define UPB_MAPENTRY_KEY 1 #define UPB_MAPENTRY_VALUE 2 #ifdef __cplusplus /* Structure that describes a single .proto message type. * * Its base class is upb::Def (use upb::upcast() to convert). */ class upb::MessageDef { public: /* Returns NULL if memory allocation failed. */ static reffed_ptr
New(); /* upb::RefCounted methods like Ref()/Unref(). */ UPB_REFCOUNTED_CPPMETHODS /* Functionality from upb::Def. */ const char* full_name() const; const char* name() const; bool set_full_name(const char* fullname, Status* s); bool set_full_name(const std::string& fullname, Status* s); /* Call to freeze this MessageDef. * WARNING: this will fail if this message has any unfrozen submessages! * Messages with cycles must be frozen as a batch using upb::Def::Freeze(). */ bool Freeze(Status* s); /* The number of fields that belong to the MessageDef. */ int field_count() const; /* The number of oneofs that belong to the MessageDef. */ int oneof_count() const; /* Adds a field (upb_fielddef object) to a msgdef. Requires that the msgdef * and the fielddefs are mutable. The fielddef's name and number must be * set, and the message may not already contain any field with this name or * number, and this fielddef may not be part of another message. In error * cases false is returned and the msgdef is unchanged. * * If the given field is part of a oneof, this call succeeds if and only if * that oneof is already part of this msgdef. (Note that adding a oneof to a * msgdef automatically adds all of its fields to the msgdef at the time that * the oneof is added, so it is usually more idiomatic to add the oneof's * fields first then add the oneof to the msgdef. This case is supported for * convenience.) * * If |f| is already part of this MessageDef, this method performs no action * and returns true (success). Thus, this method is idempotent. */ bool AddField(FieldDef* f, Status* s); bool AddField(const reffed_ptr
& f, Status* s); /* Adds a oneof (upb_oneofdef object) to a msgdef. Requires that the msgdef, * oneof, and any fielddefs are mutable, that the fielddefs contained in the * oneof do not have any name or number conflicts with existing fields in the * msgdef, and that the oneof's name is unique among all oneofs in the msgdef. * If the oneof is added successfully, all of its fields will be added * directly to the msgdef as well. In error cases, false is returned and the * msgdef is unchanged. */ bool AddOneof(OneofDef* o, Status* s); bool AddOneof(const reffed_ptr
& o, Status* s); upb_syntax_t syntax() const; /* Returns false if we don't support this syntax value. */ bool set_syntax(upb_syntax_t syntax); /* Set this to false to indicate that primitive fields should not have * explicit presence information associated with them. This will affect all * fields added to this message. Defaults to true. */ void SetPrimitivesHavePresence(bool have_presence); /* These return NULL if the field is not found. */ FieldDef* FindFieldByNumber(uint32_t number); FieldDef* FindFieldByName(const char *name, size_t len); const FieldDef* FindFieldByNumber(uint32_t number) const; const FieldDef* FindFieldByName(const char* name, size_t len) const; FieldDef* FindFieldByName(const char *name) { return FindFieldByName(name, strlen(name)); } const FieldDef* FindFieldByName(const char *name) const { return FindFieldByName(name, strlen(name)); } template
FieldDef* FindFieldByName(const T& str) { return FindFieldByName(str.c_str(), str.size()); } template
const FieldDef* FindFieldByName(const T& str) const { return FindFieldByName(str.c_str(), str.size()); } OneofDef* FindOneofByName(const char* name, size_t len); const OneofDef* FindOneofByName(const char* name, size_t len) const; OneofDef* FindOneofByName(const char* name) { return FindOneofByName(name, strlen(name)); } const OneofDef* FindOneofByName(const char* name) const { return FindOneofByName(name, strlen(name)); } template
OneofDef* FindOneofByName(const T& str) { return FindOneofByName(str.c_str(), str.size()); } template
const OneofDef* FindOneofByName(const T& str) const { return FindOneofByName(str.c_str(), str.size()); } /* Returns a new msgdef that is a copy of the given msgdef (and a copy of all * the fields) but with any references to submessages broken and replaced * with just the name of the submessage. Returns NULL if memory allocation * failed. * * TODO(haberman): which is more useful, keeping fields resolved or * unresolving them? If there's no obvious answer, Should this functionality * just be moved into symtab.c? */ MessageDef* Dup(const void* owner) const; /* Is this message a map entry? */ void setmapentry(bool map_entry); bool mapentry() const; /* Iteration over fields. The order is undefined. */ class field_iterator : public std::iterator
{ public: explicit field_iterator(MessageDef* md); static field_iterator end(MessageDef* md); void operator++(); FieldDef* operator*() const; bool operator!=(const field_iterator& other) const; bool operator==(const field_iterator& other) const; private: upb_msg_field_iter iter_; }; class const_field_iterator : public std::iterator
{ public: explicit const_field_iterator(const MessageDef* md); static const_field_iterator end(const MessageDef* md); void operator++(); const FieldDef* operator*() const; bool operator!=(const const_field_iterator& other) const; bool operator==(const const_field_iterator& other) const; private: upb_msg_field_iter iter_; }; /* Iteration over oneofs. The order is undefined. */ class oneof_iterator : public std::iterator
{ public: explicit oneof_iterator(MessageDef* md); static oneof_iterator end(MessageDef* md); void operator++(); OneofDef* operator*() const; bool operator!=(const oneof_iterator& other) const; bool operator==(const oneof_iterator& other) const; private: upb_msg_oneof_iter iter_; }; class const_oneof_iterator : public std::iterator
{ public: explicit const_oneof_iterator(const MessageDef* md); static const_oneof_iterator end(const MessageDef* md); void operator++(); const OneofDef* operator*() const; bool operator!=(const const_oneof_iterator& other) const; bool operator==(const const_oneof_iterator& other) const; private: upb_msg_oneof_iter iter_; }; class FieldAccessor { public: explicit FieldAccessor(MessageDef* msg) : msg_(msg) {} field_iterator begin() { return msg_->field_begin(); } field_iterator end() { return msg_->field_end(); } private: MessageDef* msg_; }; class ConstFieldAccessor { public: explicit ConstFieldAccessor(const MessageDef* msg) : msg_(msg) {} const_field_iterator begin() { return msg_->field_begin(); } const_field_iterator end() { return msg_->field_end(); } private: const MessageDef* msg_; }; class OneofAccessor { public: explicit OneofAccessor(MessageDef* msg) : msg_(msg) {} oneof_iterator begin() { return msg_->oneof_begin(); } oneof_iterator end() { return msg_->oneof_end(); } private: MessageDef* msg_; }; class ConstOneofAccessor { public: explicit ConstOneofAccessor(const MessageDef* msg) : msg_(msg) {} const_oneof_iterator begin() { return msg_->oneof_begin(); } const_oneof_iterator end() { return msg_->oneof_end(); } private: const MessageDef* msg_; }; field_iterator field_begin(); field_iterator field_end(); const_field_iterator field_begin() const; const_field_iterator field_end() const; oneof_iterator oneof_begin(); oneof_iterator oneof_end(); const_oneof_iterator oneof_begin() const; const_oneof_iterator oneof_end() const; FieldAccessor fields() { return FieldAccessor(this); } ConstFieldAccessor fields() const { return ConstFieldAccessor(this); } OneofAccessor oneofs() { return OneofAccessor(this); } ConstOneofAccessor oneofs() const { return ConstOneofAccessor(this); } private: UPB_DISALLOW_POD_OPS(MessageDef, upb::MessageDef) }; #endif /* __cplusplus */ UPB_BEGIN_EXTERN_C /* Returns NULL if memory allocation failed. */ upb_msgdef *upb_msgdef_new(const void *owner); /* Include upb_refcounted methods like upb_msgdef_ref(). */ UPB_REFCOUNTED_CMETHODS(upb_msgdef, upb_msgdef_upcast2) bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status); upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner); const char *upb_msgdef_fullname(const upb_msgdef *m); const char *upb_msgdef_name(const upb_msgdef *m); int upb_msgdef_numoneofs(const upb_msgdef *m); upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m); bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor, upb_status *s); bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor, upb_status *s); bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname, upb_status *s); void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry); bool upb_msgdef_mapentry(const upb_msgdef *m); bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax); /* Field lookup in a couple of different variations: * - itof = int to field * - ntof = name to field * - ntofz = name to field, null-terminated string. */ const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i); const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name, size_t len); int upb_msgdef_numfields(const upb_msgdef *m); UPB_INLINE const upb_fielddef *upb_msgdef_ntofz(const upb_msgdef *m, const char *name) { return upb_msgdef_ntof(m, name, strlen(name)); } UPB_INLINE upb_fielddef *upb_msgdef_itof_mutable(upb_msgdef *m, uint32_t i) { return (upb_fielddef*)upb_msgdef_itof(m, i); } UPB_INLINE upb_fielddef *upb_msgdef_ntof_mutable(upb_msgdef *m, const char *name, size_t len) { return (upb_fielddef *)upb_msgdef_ntof(m, name, len); } /* Oneof lookup: * - ntoo = name to oneof * - ntooz = name to oneof, null-terminated string. */ const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name, size_t len); int upb_msgdef_numoneofs(const upb_msgdef *m); UPB_INLINE const upb_oneofdef *upb_msgdef_ntooz(const upb_msgdef *m, const char *name) { return upb_msgdef_ntoo(m, name, strlen(name)); } UPB_INLINE upb_oneofdef *upb_msgdef_ntoo_mutable(upb_msgdef *m, const char *name, size_t len) { return (upb_oneofdef *)upb_msgdef_ntoo(m, name, len); } /* Lookup of either field or oneof by name. Returns whether either was found. * If the return is true, then the found def will be set, and the non-found * one set to NULL. */ bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len, const upb_fielddef **f, const upb_oneofdef **o); UPB_INLINE bool upb_msgdef_lookupnamez(const upb_msgdef *m, const char *name, const upb_fielddef **f, const upb_oneofdef **o) { return upb_msgdef_lookupname(m, name, strlen(name), f, o); } /* Iteration over fields and oneofs. For example: * * upb_msg_field_iter i; * for(upb_msg_field_begin(&i, m); * !upb_msg_field_done(&i); * upb_msg_field_next(&i)) { * upb_fielddef *f = upb_msg_iter_field(&i); * // ... * } * * For C we don't have separate iterators for const and non-const. * It is the caller's responsibility to cast the upb_fielddef* to * const if the upb_msgdef* is const. */ void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m); void upb_msg_field_next(upb_msg_field_iter *iter); bool upb_msg_field_done(const upb_msg_field_iter *iter); upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter); void upb_msg_field_iter_setdone(upb_msg_field_iter *iter); /* Similar to above, we also support iterating through the oneofs in a * msgdef. */ void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m); void upb_msg_oneof_next(upb_msg_oneof_iter *iter); bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter); upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter); void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter); UPB_END_EXTERN_C /* upb::EnumDef ***************************************************************/ typedef upb_strtable_iter upb_enum_iter; #ifdef __cplusplus /* Class that represents an enum. Its base class is upb::Def (convert with * upb::upcast()). */ class upb::EnumDef { public: /* Returns NULL if memory allocation failed. */ static reffed_ptr
New(); /* upb::RefCounted methods like Ref()/Unref(). */ UPB_REFCOUNTED_CPPMETHODS /* Functionality from upb::Def. */ const char* full_name() const; const char* name() const; bool set_full_name(const char* fullname, Status* s); bool set_full_name(const std::string& fullname, Status* s); /* Call to freeze this EnumDef. */ bool Freeze(Status* s); /* The value that is used as the default when no field default is specified. * If not set explicitly, the first value that was added will be used. * The default value must be a member of the enum. * Requires that value_count() > 0. */ int32_t default_value() const; /* Sets the default value. If this value is not valid, returns false and an * error message in status. */ bool set_default_value(int32_t val, Status* status); /* Returns the number of values currently defined in the enum. Note that * multiple names can refer to the same number, so this may be greater than * the total number of unique numbers. */ int value_count() const; /* Adds a single name/number pair to the enum. Fails if this name has * already been used by another value. */ bool AddValue(const char* name, int32_t num, Status* status); bool AddValue(const std::string& name, int32_t num, Status* status); /* Lookups from name to integer, returning true if found. */ bool FindValueByName(const char* name, int32_t* num) const; /* Finds the name corresponding to the given number, or NULL if none was * found. If more than one name corresponds to this number, returns the * first one that was added. */ const char* FindValueByNumber(int32_t num) const; /* Returns a new EnumDef with all the same values. The new EnumDef will be * owned by the given owner. */ EnumDef* Dup(const void* owner) const; /* Iteration over name/value pairs. The order is undefined. * Adding an enum val invalidates any iterators. * * TODO: make compatible with range-for, with elements as pairs? */ class Iterator { public: explicit Iterator(const EnumDef*); int32_t number(); const char *name(); bool Done(); void Next(); private: upb_enum_iter iter_; }; private: UPB_DISALLOW_POD_OPS(EnumDef, upb::EnumDef) }; #endif /* __cplusplus */ UPB_BEGIN_EXTERN_C /* Native C API. */ upb_enumdef *upb_enumdef_new(const void *owner); upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner); /* Include upb_refcounted methods like upb_enumdef_ref(). */ UPB_REFCOUNTED_CMETHODS(upb_enumdef, upb_enumdef_upcast2) bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status); /* From upb_def. */ const char *upb_enumdef_fullname(const upb_enumdef *e); const char *upb_enumdef_name(const upb_enumdef *e); bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname, upb_status *s); int32_t upb_enumdef_default(const upb_enumdef *e); bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s); int upb_enumdef_numvals(const upb_enumdef *e); bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num, upb_status *status); /* Enum lookups: * - ntoi: look up a name with specified length. * - ntoiz: look up a name provided as a null-terminated string. * - iton: look up an integer, returning the name as a null-terminated * string. */ bool upb_enumdef_ntoi(const upb_enumdef *e, const char *name, size_t len, int32_t *num); UPB_INLINE bool upb_enumdef_ntoiz(const upb_enumdef *e, const char *name, int32_t *num) { return upb_enumdef_ntoi(e, name, strlen(name), num); } const char *upb_enumdef_iton(const upb_enumdef *e, int32_t num); /* upb_enum_iter i; * for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) { * // ... * } */ void upb_enum_begin(upb_enum_iter *iter, const upb_enumdef *e); void upb_enum_next(upb_enum_iter *iter); bool upb_enum_done(upb_enum_iter *iter); const char *upb_enum_iter_name(upb_enum_iter *iter); int32_t upb_enum_iter_number(upb_enum_iter *iter); UPB_END_EXTERN_C /* upb::OneofDef **************************************************************/ typedef upb_inttable_iter upb_oneof_iter; #ifdef __cplusplus /* Class that represents a oneof. */ class upb::OneofDef { public: /* Returns NULL if memory allocation failed. */ static reffed_ptr
New(); /* upb::RefCounted methods like Ref()/Unref(). */ UPB_REFCOUNTED_CPPMETHODS /* Returns the MessageDef that owns this OneofDef. */ const MessageDef* containing_type() const; /* Returns the name of this oneof. This is the name used to look up the oneof * by name once added to a message def. */ const char* name() const; bool set_name(const char* name, Status* s); bool set_name(const std::string& name, Status* s); /* Returns the number of fields currently defined in the oneof. */ int field_count() const; /* Adds a field to the oneof. The field must not have been added to any other * oneof or msgdef. If the oneof is not yet part of a msgdef, then when the * oneof is eventually added to a msgdef, all fields added to the oneof will * also be added to the msgdef at that time. If the oneof is already part of a * msgdef, the field must either be a part of that msgdef already, or must not * be a part of any msgdef; in the latter case, the field is added to the * msgdef as a part of this operation. * * The field may only have an OPTIONAL label, never REQUIRED or REPEATED. * * If |f| is already part of this MessageDef, this method performs no action * and returns true (success). Thus, this method is idempotent. */ bool AddField(FieldDef* field, Status* s); bool AddField(const reffed_ptr
& field, Status* s); /* Looks up by name. */ const FieldDef* FindFieldByName(const char* name, size_t len) const; FieldDef* FindFieldByName(const char* name, size_t len); const FieldDef* FindFieldByName(const char* name) const { return FindFieldByName(name, strlen(name)); } FieldDef* FindFieldByName(const char* name) { return FindFieldByName(name, strlen(name)); } template
FieldDef* FindFieldByName(const T& str) { return FindFieldByName(str.c_str(), str.size()); } template
const FieldDef* FindFieldByName(const T& str) const { return FindFieldByName(str.c_str(), str.size()); } /* Looks up by tag number. */ const FieldDef* FindFieldByNumber(uint32_t num) const; /* Returns a new OneofDef with all the same fields. The OneofDef will be owned * by the given owner. */ OneofDef* Dup(const void* owner) const; /* Iteration over fields. The order is undefined. */ class iterator : public std::iterator
{ public: explicit iterator(OneofDef* md); static iterator end(OneofDef* md); void operator++(); FieldDef* operator*() const; bool operator!=(const iterator& other) const; bool operator==(const iterator& other) const; private: upb_oneof_iter iter_; }; class const_iterator : public std::iterator
{ public: explicit const_iterator(const OneofDef* md); static const_iterator end(const OneofDef* md); void operator++(); const FieldDef* operator*() const; bool operator!=(const const_iterator& other) const; bool operator==(const const_iterator& other) const; private: upb_oneof_iter iter_; }; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; private: UPB_DISALLOW_POD_OPS(OneofDef, upb::OneofDef) }; #endif /* __cplusplus */ UPB_BEGIN_EXTERN_C /* Native C API. */ upb_oneofdef *upb_oneofdef_new(const void *owner); upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner); /* Include upb_refcounted methods like upb_oneofdef_ref(). */ UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast) const char *upb_oneofdef_name(const upb_oneofdef *o); bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s); const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o); int upb_oneofdef_numfields(const upb_oneofdef *o); bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f, const void *ref_donor, upb_status *s); /* Oneof lookups: * - ntof: look up a field by name. * - ntofz: look up a field by name (as a null-terminated string). * - itof: look up a field by number. */ const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o, const char *name, size_t length); UPB_INLINE const upb_fielddef *upb_oneofdef_ntofz(const upb_oneofdef *o, const char *name) { return upb_oneofdef_ntof(o, name, strlen(name)); } const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num); /* upb_oneof_iter i; * for(upb_oneof_begin(&i, e); !upb_oneof_done(&i); upb_oneof_next(&i)) { * // ... * } */ void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o); void upb_oneof_next(upb_oneof_iter *iter); bool upb_oneof_done(upb_oneof_iter *iter); upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter); void upb_oneof_iter_setdone(upb_oneof_iter *iter); UPB_END_EXTERN_C /* upb::FileDef ***************************************************************/ #ifdef __cplusplus /* Class that represents a .proto file with some things defined in it. * * Many users won't care about FileDefs, but they are necessary if you want to * read the values of file-level options. */ class upb::FileDef { public: /* Returns NULL if memory allocation failed. */ static reffed_ptr
New(); /* upb::RefCounted methods like Ref()/Unref(). */ UPB_REFCOUNTED_CPPMETHODS /* Get/set name of the file (eg. "foo/bar.proto"). */ const char* name() const; bool set_name(const char* name, Status* s); bool set_name(const std::string& name, Status* s); /* Package name for definitions inside the file (eg. "foo.bar"). */ const char* package() const; bool set_package(const char* package, Status* s); /* Syntax for the file. Defaults to proto2. */ upb_syntax_t syntax() const; void set_syntax(upb_syntax_t syntax); /* Get the list of defs from the file. These are returned in the order that * they were added to the FileDef. */ int def_count() const; const Def* def(int index) const; Def* def(int index); /* Get the list of dependencies from the file. These are returned in the * order that they were added to the FileDef. */ int dependency_count() const; const FileDef* dependency(int index) const; /* Adds defs to this file. The def must not already belong to another * file. * * Note: this does *not* ensure that this def's name is unique in this file! * Use a SymbolTable if you want to check this property. Especially since * properly checking uniqueness would require a check across *all* files * (including dependencies). */ bool AddDef(Def* def, Status* s); bool AddMessage(MessageDef* m, Status* s); bool AddEnum(EnumDef* e, Status* s); bool AddExtension(FieldDef* f, Status* s); /* Adds a dependency of this file. */ bool AddDependency(const FileDef* file); /* Freezes this FileDef and all messages/enums under it. All subdefs must be * resolved and all messages/enums must validate. Returns true if this * succeeded. * * TODO(haberman): should we care whether the file's dependencies are frozen * already? */ bool Freeze(Status* s); private: UPB_DISALLOW_POD_OPS(FileDef, upb::FileDef) }; #endif UPB_BEGIN_EXTERN_C upb_filedef *upb_filedef_new(const void *owner); /* Include upb_refcounted methods like upb_msgdef_ref(). */ UPB_REFCOUNTED_CMETHODS(upb_filedef, upb_filedef_upcast) const char *upb_filedef_name(const upb_filedef *f); const char *upb_filedef_package(const upb_filedef *f); upb_syntax_t upb_filedef_syntax(const upb_filedef *f); size_t upb_filedef_defcount(const upb_filedef *f); size_t upb_filedef_depcount(const upb_filedef *f); const upb_def *upb_filedef_def(const upb_filedef *f, size_t i); const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i); bool upb_filedef_freeze(upb_filedef *f, upb_status *s); bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s); bool upb_filedef_setpackage(upb_filedef *f, const char *package, upb_status *s); bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax, upb_status *s); bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor, upb_status *s); bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep); UPB_INLINE bool upb_filedef_addmsg(upb_filedef *f, upb_msgdef *m, const void *ref_donor, upb_status *s) { return upb_filedef_adddef(f, upb_msgdef_upcast_mutable(m), ref_donor, s); } UPB_INLINE bool upb_filedef_addenum(upb_filedef *f, upb_enumdef *e, const void *ref_donor, upb_status *s) { return upb_filedef_adddef(f, upb_enumdef_upcast_mutable(e), ref_donor, s); } UPB_INLINE bool upb_filedef_addext(upb_filedef *file, upb_fielddef *f, const void *ref_donor, upb_status *s) { return upb_filedef_adddef(file, upb_fielddef_upcast_mutable(f), ref_donor, s); } UPB_INLINE upb_def *upb_filedef_mutabledef(upb_filedef *f, int i) { return (upb_def*)upb_filedef_def(f, i); } UPB_END_EXTERN_C #ifdef __cplusplus UPB_INLINE const char* upb_safecstr(const std::string& str) { assert(str.size() == std::strlen(str.c_str())); return str.c_str(); } /* Inline C++ wrappers. */ namespace upb { inline Def* Def::Dup(const void* owner) const { return upb_def_dup(this, owner); } inline Def::Type Def::def_type() const { return upb_def_type(this); } inline const char* Def::full_name() const { return upb_def_fullname(this); } inline const char* Def::name() const { return upb_def_name(this); } inline bool Def::set_full_name(const char* fullname, Status* s) { return upb_def_setfullname(this, fullname, s); } inline bool Def::set_full_name(const std::string& fullname, Status* s) { return upb_def_setfullname(this, upb_safecstr(fullname), s); } inline bool Def::Freeze(Def* const* defs, size_t n, Status* status) { return upb_def_freeze(defs, n, status); } inline bool Def::Freeze(const std::vector
& defs, Status* status) { return upb_def_freeze((Def* const*)&defs[0], defs.size(), status); } inline bool FieldDef::CheckType(int32_t val) { return upb_fielddef_checktype(val); } inline bool FieldDef::CheckLabel(int32_t val) { return upb_fielddef_checklabel(val); } inline bool FieldDef::CheckDescriptorType(int32_t val) { return upb_fielddef_checkdescriptortype(val); } inline bool FieldDef::CheckIntegerFormat(int32_t val) { return upb_fielddef_checkintfmt(val); } inline FieldDef::Type FieldDef::ConvertType(int32_t val) { assert(CheckType(val)); return static_cast
(val); } inline FieldDef::Label FieldDef::ConvertLabel(int32_t val) { assert(CheckLabel(val)); return static_cast
(val); } inline FieldDef::DescriptorType FieldDef::ConvertDescriptorType(int32_t val) { assert(CheckDescriptorType(val)); return static_cast
(val); } inline FieldDef::IntegerFormat FieldDef::ConvertIntegerFormat(int32_t val) { assert(CheckIntegerFormat(val)); return static_cast
(val); } inline reffed_ptr
FieldDef::New() { upb_fielddef *f = upb_fielddef_new(&f); return reffed_ptr
(f, &f); } inline FieldDef* FieldDef::Dup(const void* owner) const { return upb_fielddef_dup(this, owner); } inline const char* FieldDef::full_name() const { return upb_fielddef_fullname(this); } inline bool FieldDef::set_full_name(const char* fullname, Status* s) { return upb_fielddef_setfullname(this, fullname, s); } inline bool FieldDef::set_full_name(const std::string& fullname, Status* s) { return upb_fielddef_setfullname(this, upb_safecstr(fullname), s); } inline bool FieldDef::type_is_set() const { return upb_fielddef_typeisset(this); } inline FieldDef::Type FieldDef::type() const { return upb_fielddef_type(this); } inline FieldDef::DescriptorType FieldDef::descriptor_type() const { return upb_fielddef_descriptortype(this); } inline FieldDef::Label FieldDef::label() const { return upb_fielddef_label(this); } inline uint32_t FieldDef::number() const { return upb_fielddef_number(this); } inline const char* FieldDef::name() const { return upb_fielddef_name(this); } inline bool FieldDef::is_extension() const { return upb_fielddef_isextension(this); } inline size_t FieldDef::GetJsonName(char* buf, size_t len) const { return upb_fielddef_getjsonname(this, buf, len); } inline bool FieldDef::lazy() const { return upb_fielddef_lazy(this); } inline void FieldDef::set_lazy(bool lazy) { upb_fielddef_setlazy(this, lazy); } inline bool FieldDef::packed() const { return upb_fielddef_packed(this); } inline uint32_t FieldDef::index() const { return upb_fielddef_index(this); } inline void FieldDef::set_packed(bool packed) { upb_fielddef_setpacked(this, packed); } inline const MessageDef* FieldDef::containing_type() const { return upb_fielddef_containingtype(this); } inline const OneofDef* FieldDef::containing_oneof() const { return upb_fielddef_containingoneof(this); } inline const char* FieldDef::containing_type_name() { return upb_fielddef_containingtypename(this); } inline bool FieldDef::set_number(uint32_t number, Status* s) { return upb_fielddef_setnumber(this, number, s); } inline bool FieldDef::set_name(const char *name, Status* s) { return upb_fielddef_setname(this, name, s); } inline bool FieldDef::set_name(const std::string& name, Status* s) { return upb_fielddef_setname(this, upb_safecstr(name), s); } inline bool FieldDef::set_json_name(const char *name, Status* s) { return upb_fielddef_setjsonname(this, name, s); } inline bool FieldDef::set_json_name(const std::string& name, Status* s) { return upb_fielddef_setjsonname(this, upb_safecstr(name), s); } inline void FieldDef::clear_json_name() { upb_fielddef_clearjsonname(this); } inline bool FieldDef::set_containing_type_name(const char *name, Status* s) { return upb_fielddef_setcontainingtypename(this, name, s); } inline bool FieldDef::set_containing_type_name(const std::string &name, Status *s) { return upb_fielddef_setcontainingtypename(this, upb_safecstr(name), s); } inline void FieldDef::set_type(upb_fieldtype_t type) { upb_fielddef_settype(this, type); } inline void FieldDef::set_is_extension(bool is_extension) { upb_fielddef_setisextension(this, is_extension); } inline void FieldDef::set_descriptor_type(FieldDef::DescriptorType type) { upb_fielddef_setdescriptortype(this, type); } inline void FieldDef::set_label(upb_label_t label) { upb_fielddef_setlabel(this, label); } inline bool FieldDef::IsSubMessage() const { return upb_fielddef_issubmsg(this); } inline bool FieldDef::IsString() const { return upb_fielddef_isstring(this); } inline bool FieldDef::IsSequence() const { return upb_fielddef_isseq(this); } inline bool FieldDef::IsMap() const { return upb_fielddef_ismap(this); } inline int64_t FieldDef::default_int64() const { return upb_fielddef_defaultint64(this); } inline int32_t FieldDef::default_int32() const { return upb_fielddef_defaultint32(this); } inline uint64_t FieldDef::default_uint64() const { return upb_fielddef_defaultuint64(this); } inline uint32_t FieldDef::default_uint32() const { return upb_fielddef_defaultuint32(this); } inline bool FieldDef::default_bool() const { return upb_fielddef_defaultbool(this); } inline float FieldDef::default_float() const { return upb_fielddef_defaultfloat(this); } inline double FieldDef::default_double() const { return upb_fielddef_defaultdouble(this); } inline const char* FieldDef::default_string(size_t* len) const { return upb_fielddef_defaultstr(this, len); } inline void FieldDef::set_default_int64(int64_t value) { upb_fielddef_setdefaultint64(this, value); } inline void FieldDef::set_default_int32(int32_t value) { upb_fielddef_setdefaultint32(this, value); } inline void FieldDef::set_default_uint64(uint64_t value) { upb_fielddef_setdefaultuint64(this, value); } inline void FieldDef::set_default_uint32(uint32_t value) { upb_fielddef_setdefaultuint32(this, value); } inline void FieldDef::set_default_bool(bool value) { upb_fielddef_setdefaultbool(this, value); } inline void FieldDef::set_default_float(float value) { upb_fielddef_setdefaultfloat(this, value); } inline void FieldDef::set_default_double(double value) { upb_fielddef_setdefaultdouble(this, value); } inline bool FieldDef::set_default_string(const void *str, size_t len, Status *s) { return upb_fielddef_setdefaultstr(this, str, len, s); } inline bool FieldDef::set_default_string(const std::string& str, Status* s) { return upb_fielddef_setdefaultstr(this, str.c_str(), str.size(), s); } inline void FieldDef::set_default_cstr(const char* str, Status* s) { return upb_fielddef_setdefaultcstr(this, str, s); } inline bool FieldDef::HasSubDef() const { return upb_fielddef_hassubdef(this); } inline const Def* FieldDef::subdef() const { return upb_fielddef_subdef(this); } inline const MessageDef *FieldDef::message_subdef() const { return upb_fielddef_msgsubdef(this); } inline const EnumDef *FieldDef::enum_subdef() const { return upb_fielddef_enumsubdef(this); } inline const char* FieldDef::subdef_name() const { return upb_fielddef_subdefname(this); } inline bool FieldDef::set_subdef(const Def* subdef, Status* s) { return upb_fielddef_setsubdef(this, subdef, s); } inline bool FieldDef::set_enum_subdef(const EnumDef* subdef, Status* s) { return upb_fielddef_setenumsubdef(this, subdef, s); } inline bool FieldDef::set_message_subdef(const MessageDef* subdef, Status* s) { return upb_fielddef_setmsgsubdef(this, subdef, s); } inline bool FieldDef::set_subdef_name(const char* name, Status* s) { return upb_fielddef_setsubdefname(this, name, s); } inline bool FieldDef::set_subdef_name(const std::string& name, Status* s) { return upb_fielddef_setsubdefname(this, upb_safecstr(name), s); } inline reffed_ptr
MessageDef::New() { upb_msgdef *m = upb_msgdef_new(&m); return reffed_ptr
(m, &m); } inline const char *MessageDef::full_name() const { return upb_msgdef_fullname(this); } inline const char *MessageDef::name() const { return upb_msgdef_name(this); } inline upb_syntax_t MessageDef::syntax() const { return upb_msgdef_syntax(this); } inline bool MessageDef::set_full_name(const char* fullname, Status* s) { return upb_msgdef_setfullname(this, fullname, s); } inline bool MessageDef::set_full_name(const std::string& fullname, Status* s) { return upb_msgdef_setfullname(this, upb_safecstr(fullname), s); } inline bool MessageDef::set_syntax(upb_syntax_t syntax) { return upb_msgdef_setsyntax(this, syntax); } inline bool MessageDef::Freeze(Status* status) { return upb_msgdef_freeze(this, status); } inline int MessageDef::field_count() const { return upb_msgdef_numfields(this); } inline int MessageDef::oneof_count() const { return upb_msgdef_numoneofs(this); } inline bool MessageDef::AddField(upb_fielddef* f, Status* s) { return upb_msgdef_addfield(this, f, NULL, s); } inline bool MessageDef::AddField(const reffed_ptr
& f, Status* s) { return upb_msgdef_addfield(this, f.get(), NULL, s); } inline bool MessageDef::AddOneof(upb_oneofdef* o, Status* s) { return upb_msgdef_addoneof(this, o, NULL, s); } inline bool MessageDef::AddOneof(const reffed_ptr
& o, Status* s) { return upb_msgdef_addoneof(this, o.get(), NULL, s); } inline FieldDef* MessageDef::FindFieldByNumber(uint32_t number) { return upb_msgdef_itof_mutable(this, number); } inline FieldDef* MessageDef::FindFieldByName(const char* name, size_t len) { return upb_msgdef_ntof_mutable(this, name, len); } inline const FieldDef* MessageDef::FindFieldByNumber(uint32_t number) const { return upb_msgdef_itof(this, number); } inline const FieldDef *MessageDef::FindFieldByName(const char *name, size_t len) const { return upb_msgdef_ntof(this, name, len); } inline OneofDef* MessageDef::FindOneofByName(const char* name, size_t len) { return upb_msgdef_ntoo_mutable(this, name, len); } inline const OneofDef* MessageDef::FindOneofByName(const char* name, size_t len) const { return upb_msgdef_ntoo(this, name, len); } inline MessageDef* MessageDef::Dup(const void *owner) const { return upb_msgdef_dup(this, owner); } inline void MessageDef::setmapentry(bool map_entry) { upb_msgdef_setmapentry(this, map_entry); } inline bool MessageDef::mapentry() const { return upb_msgdef_mapentry(this); } inline MessageDef::field_iterator MessageDef::field_begin() { return field_iterator(this); } inline MessageDef::field_iterator MessageDef::field_end() { return field_iterator::end(this); } inline MessageDef::const_field_iterator MessageDef::field_begin() const { return const_field_iterator(this); } inline MessageDef::const_field_iterator MessageDef::field_end() const { return const_field_iterator::end(this); } inline MessageDef::oneof_iterator MessageDef::oneof_begin() { return oneof_iterator(this); } inline MessageDef::oneof_iterator MessageDef::oneof_end() { return oneof_iterator::end(this); } inline MessageDef::const_oneof_iterator MessageDef::oneof_begin() const { return const_oneof_iterator(this); } inline MessageDef::const_oneof_iterator MessageDef::oneof_end() const { return const_oneof_iterator::end(this); } inline MessageDef::field_iterator::field_iterator(MessageDef* md) { upb_msg_field_begin(&iter_, md); } inline MessageDef::field_iterator MessageDef::field_iterator::end( MessageDef* md) { MessageDef::field_iterator iter(md); upb_msg_field_iter_setdone(&iter.iter_); return iter; } inline FieldDef* MessageDef::field_iterator::operator*() const { return upb_msg_iter_field(&iter_); } inline void MessageDef::field_iterator::operator++() { return upb_msg_field_next(&iter_); } inline bool MessageDef::field_iterator::operator==( const field_iterator &other) const { return upb_inttable_iter_isequal(&iter_, &other.iter_); } inline bool MessageDef::field_iterator::operator!=( const field_iterator &other) const { return !(*this == other); } inline MessageDef::const_field_iterator::const_field_iterator( const MessageDef* md) { upb_msg_field_begin(&iter_, md); } inline MessageDef::const_field_iterator MessageDef::const_field_iterator::end( const MessageDef *md) { MessageDef::const_field_iterator iter(md); upb_msg_field_iter_setdone(&iter.iter_); return iter; } inline const FieldDef* MessageDef::const_field_iterator::operator*() const { return upb_msg_iter_field(&iter_); } inline void MessageDef::const_field_iterator::operator++() { return upb_msg_field_next(&iter_); } inline bool MessageDef::const_field_iterator::operator==( const const_field_iterator &other) const { return upb_inttable_iter_isequal(&iter_, &other.iter_); } inline bool MessageDef::const_field_iterator::operator!=( const const_field_iterator &other) const { return !(*this == other); } inline MessageDef::oneof_iterator::oneof_iterator(MessageDef* md) { upb_msg_oneof_begin(&iter_, md); } inline MessageDef::oneof_iterator MessageDef::oneof_iterator::end( MessageDef* md) { MessageDef::oneof_iterator iter(md); upb_msg_oneof_iter_setdone(&iter.iter_); return iter; } inline OneofDef* MessageDef::oneof_iterator::operator*() const { return upb_msg_iter_oneof(&iter_); } inline void MessageDef::oneof_iterator::operator++() { return upb_msg_oneof_next(&iter_); } inline bool MessageDef::oneof_iterator::operator==( const oneof_iterator &other) const { return upb_strtable_iter_isequal(&iter_, &other.iter_); } inline bool MessageDef::oneof_iterator::operator!=( const oneof_iterator &other) const { return !(*this == other); } inline MessageDef::const_oneof_iterator::const_oneof_iterator( const MessageDef* md) { upb_msg_oneof_begin(&iter_, md); } inline MessageDef::const_oneof_iterator MessageDef::const_oneof_iterator::end( const MessageDef *md) { MessageDef::const_oneof_iterator iter(md); upb_msg_oneof_iter_setdone(&iter.iter_); return iter; } inline const OneofDef* MessageDef::const_oneof_iterator::operator*() const { return upb_msg_iter_oneof(&iter_); } inline void MessageDef::const_oneof_iterator::operator++() { return upb_msg_oneof_next(&iter_); } inline bool MessageDef::const_oneof_iterator::operator==( const const_oneof_iterator &other) const { return upb_strtable_iter_isequal(&iter_, &other.iter_); } inline bool MessageDef::const_oneof_iterator::operator!=( const const_oneof_iterator &other) const { return !(*this == other); } inline reffed_ptr
EnumDef::New() { upb_enumdef *e = upb_enumdef_new(&e); return reffed_ptr
(e, &e); } inline const char* EnumDef::full_name() const { return upb_enumdef_fullname(this); } inline const char* EnumDef::name() const { return upb_enumdef_name(this); } inline bool EnumDef::set_full_name(const char* fullname, Status* s) { return upb_enumdef_setfullname(this, fullname, s); } inline bool EnumDef::set_full_name(const std::string& fullname, Status* s) { return upb_enumdef_setfullname(this, upb_safecstr(fullname), s); } inline bool EnumDef::Freeze(Status* status) { return upb_enumdef_freeze(this, status); } inline int32_t EnumDef::default_value() const { return upb_enumdef_default(this); } inline bool EnumDef::set_default_value(int32_t val, Status* status) { return upb_enumdef_setdefault(this, val, status); } inline int EnumDef::value_count() const { return upb_enumdef_numvals(this); } inline bool EnumDef::AddValue(const char* name, int32_t num, Status* status) { return upb_enumdef_addval(this, name, num, status); } inline bool EnumDef::AddValue(const std::string& name, int32_t num, Status* status) { return upb_enumdef_addval(this, upb_safecstr(name), num, status); } inline bool EnumDef::FindValueByName(const char* name, int32_t *num) const { return upb_enumdef_ntoiz(this, name, num); } inline const char* EnumDef::FindValueByNumber(int32_t num) const { return upb_enumdef_iton(this, num); } inline EnumDef* EnumDef::Dup(const void* owner) const { return upb_enumdef_dup(this, owner); } inline EnumDef::Iterator::Iterator(const EnumDef* e) { upb_enum_begin(&iter_, e); } inline int32_t EnumDef::Iterator::number() { return upb_enum_iter_number(&iter_); } inline const char* EnumDef::Iterator::name() { return upb_enum_iter_name(&iter_); } inline bool EnumDef::Iterator::Done() { return upb_enum_done(&iter_); } inline void EnumDef::Iterator::Next() { return upb_enum_next(&iter_); } inline reffed_ptr
OneofDef::New() { upb_oneofdef *o = upb_oneofdef_new(&o); return reffed_ptr
(o, &o); } inline const MessageDef* OneofDef::containing_type() const { return upb_oneofdef_containingtype(this); } inline const char* OneofDef::name() const { return upb_oneofdef_name(this); } inline bool OneofDef::set_name(const char* name, Status* s) { return upb_oneofdef_setname(this, name, s); } inline bool OneofDef::set_name(const std::string& name, Status* s) { return upb_oneofdef_setname(this, upb_safecstr(name), s); } inline int OneofDef::field_count() const { return upb_oneofdef_numfields(this); } inline bool OneofDef::AddField(FieldDef* field, Status* s) { return upb_oneofdef_addfield(this, field, NULL, s); } inline bool OneofDef::AddField(const reffed_ptr
& field, Status* s) { return upb_oneofdef_addfield(this, field.get(), NULL, s); } inline const FieldDef* OneofDef::FindFieldByName(const char* name, size_t len) const { return upb_oneofdef_ntof(this, name, len); } inline const FieldDef* OneofDef::FindFieldByNumber(uint32_t num) const { return upb_oneofdef_itof(this, num); } inline OneofDef::iterator OneofDef::begin() { return iterator(this); } inline OneofDef::iterator OneofDef::end() { return iterator::end(this); } inline OneofDef::const_iterator OneofDef::begin() const { return const_iterator(this); } inline OneofDef::const_iterator OneofDef::end() const { return const_iterator::end(this); } inline OneofDef::iterator::iterator(OneofDef* o) { upb_oneof_begin(&iter_, o); } inline OneofDef::iterator OneofDef::iterator::end(OneofDef* o) { OneofDef::iterator iter(o); upb_oneof_iter_setdone(&iter.iter_); return iter; } inline FieldDef* OneofDef::iterator::operator*() const { return upb_oneof_iter_field(&iter_); } inline void OneofDef::iterator::operator++() { return upb_oneof_next(&iter_); } inline bool OneofDef::iterator::operator==(const iterator &other) const { return upb_inttable_iter_isequal(&iter_, &other.iter_); } inline bool OneofDef::iterator::operator!=(const iterator &other) const { return !(*this == other); } inline OneofDef::const_iterator::const_iterator(const OneofDef* md) { upb_oneof_begin(&iter_, md); } inline OneofDef::const_iterator OneofDef::const_iterator::end( const OneofDef *md) { OneofDef::const_iterator iter(md); upb_oneof_iter_setdone(&iter.iter_); return iter; } inline const FieldDef* OneofDef::const_iterator::operator*() const { return upb_msg_iter_field(&iter_); } inline void OneofDef::const_iterator::operator++() { return upb_oneof_next(&iter_); } inline bool OneofDef::const_iterator::operator==( const const_iterator &other) const { return upb_inttable_iter_isequal(&iter_, &other.iter_); } inline bool OneofDef::const_iterator::operator!=( const const_iterator &other) const { return !(*this == other); } inline reffed_ptr
FileDef::New() { upb_filedef *f = upb_filedef_new(&f); return reffed_ptr
(f, &f); } inline const char* FileDef::name() const { return upb_filedef_name(this); } inline bool FileDef::set_name(const char* name, Status* s) { return upb_filedef_setname(this, name, s); } inline bool FileDef::set_name(const std::string& name, Status* s) { return upb_filedef_setname(this, upb_safecstr(name), s); } inline const char* FileDef::package() const { return upb_filedef_package(this); } inline bool FileDef::set_package(const char* package, Status* s) { return upb_filedef_setpackage(this, package, s); } inline int FileDef::def_count() const { return upb_filedef_defcount(this); } inline const Def* FileDef::def(int index) const { return upb_filedef_def(this, index); } inline Def* FileDef::def(int index) { return const_cast
(upb_filedef_def(this, index)); } inline int FileDef::dependency_count() const { return upb_filedef_depcount(this); } inline const FileDef* FileDef::dependency(int index) const { return upb_filedef_dep(this, index); } inline bool FileDef::AddDef(Def* def, Status* s) { return upb_filedef_adddef(this, def, NULL, s); } inline bool FileDef::AddMessage(MessageDef* m, Status* s) { return upb_filedef_addmsg(this, m, NULL, s); } inline bool FileDef::AddEnum(EnumDef* e, Status* s) { return upb_filedef_addenum(this, e, NULL, s); } inline bool FileDef::AddExtension(FieldDef* f, Status* s) { return upb_filedef_addext(this, f, NULL, s); } inline bool FileDef::AddDependency(const FileDef* file) { return upb_filedef_adddep(this, file); } } /* namespace upb */ #endif #endif /* UPB_DEF_H_ */ /* ** This file contains definitions of structs that should be considered private ** and NOT stable across versions of upb. ** ** The only reason they are declared here and not in .c files is to allow upb ** and the application (if desired) to embed statically-initialized instances ** of structures like defs. ** ** If you include this file, all guarantees of ABI compatibility go out the ** window! Any code that includes this file needs to recompile against the ** exact same version of upb that they are linking against. ** ** You also need to recompile if you change the value of the UPB_DEBUG_REFS ** flag. */ #ifndef UPB_STATICINIT_H_ #define UPB_STATICINIT_H_ #ifdef __cplusplus /* Because of how we do our typedefs, this header can't be included from C++. */ #error This file cannot be included from C++ #endif /* upb_refcounted *************************************************************/ /* upb_def ********************************************************************/ struct upb_def { upb_refcounted base; const char *fullname; const upb_filedef* file; char type; /* A upb_deftype_t (char to save space) */ /* Used as a flag during the def's mutable stage. Must be false unless * it is currently being used by a function on the stack. This allows * us to easily determine which defs were passed into the function's * current invocation. */ bool came_from_user; }; #define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \ { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false } /* upb_fielddef ***************************************************************/ struct upb_fielddef { upb_def base; union { int64_t sint; uint64_t uint; double dbl; float flt; void *bytes; } defaultval; union { const upb_msgdef *def; /* If !msg_is_symbolic. */ char *name; /* If msg_is_symbolic. */ } msg; union { const upb_def *def; /* If !subdef_is_symbolic. */ char *name; /* If subdef_is_symbolic. */ } sub; /* The msgdef or enumdef for this field, if upb_hassubdef(f). */ bool subdef_is_symbolic; bool msg_is_symbolic; const upb_oneofdef *oneof; bool default_is_string; bool type_is_set_; /* False until type is explicitly set. */ bool is_extension_; bool lazy_; bool packed_; upb_intfmt_t intfmt; bool tagdelim; upb_fieldtype_t type_; upb_label_t label_; uint32_t number_; uint32_t selector_base; /* Used to index into a upb::Handlers table. */ uint32_t index_; }; extern const struct upb_refcounted_vtbl upb_fielddef_vtbl; #define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \ packed, name, num, msgdef, subdef, selector_base, \ index, defaultval, refs, ref2s) \ { \ UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \ defaultval, {msgdef}, {subdef}, NULL, false, false, \ type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \ lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \ } /* upb_msgdef *****************************************************************/ struct upb_msgdef { upb_def base; size_t selector_count; uint32_t submsg_field_count; /* Tables for looking up fields by number and name. */ upb_inttable itof; /* int to field */ upb_strtable ntof; /* name to field/oneof */ /* Is this a map-entry message? */ bool map_entry; /* Whether this message has proto2 or proto3 semantics. */ upb_syntax_t syntax; /* TODO(haberman): proper extension ranges (there can be multiple). */ }; extern const struct upb_refcounted_vtbl upb_msgdef_vtbl; /* TODO: also support static initialization of the oneofs table. This will be * needed if we compile in descriptors that contain oneofs. */ #define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \ map_entry, syntax, refs, ref2s) \ { \ UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \ selector_count, submsg_field_count, itof, ntof, map_entry, syntax \ } /* upb_enumdef ****************************************************************/ struct upb_enumdef { upb_def base; upb_strtable ntoi; upb_inttable iton; int32_t defaultval; }; extern const struct upb_refcounted_vtbl upb_enumdef_vtbl; #define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \ { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \ iton, defaultval } /* upb_oneofdef ***************************************************************/ struct upb_oneofdef { upb_refcounted base; const char *name; upb_strtable ntof; upb_inttable itof; const upb_msgdef *parent; }; extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl; #define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \ { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), name, ntof, itof } /* upb_symtab *****************************************************************/ struct upb_symtab { upb_refcounted base; upb_strtable symtab; }; struct upb_filedef { upb_refcounted base; const char *name; const char *package; upb_syntax_t syntax; upb_inttable defs; upb_inttable deps; }; extern const struct upb_refcounted_vtbl upb_filedef_vtbl; #endif /* UPB_STATICINIT_H_ */ /* ** upb::Handlers (upb_handlers) ** ** A upb_handlers is like a virtual table for a upb_msgdef. Each field of the ** message can have associated functions that will be called when we are ** parsing or visiting a stream of data. This is similar to how handlers work ** in SAX (the Simple API for XML). ** ** The handlers have no idea where the data is coming from, so a single set of ** handlers could be used with two completely different data sources (for ** example, a parser and a visitor over in-memory objects). This decoupling is ** the most important feature of upb, because it allows parsers and serializers ** to be highly reusable. ** ** This is a mixed C/C++ interface that offers a full API to both languages. ** See the top-level README for more information. */ #ifndef UPB_HANDLERS_H #define UPB_HANDLERS_H #ifdef __cplusplus namespace upb { class BufferHandle; class BytesHandler; class HandlerAttributes; class Handlers; template
class Handler; template
struct CanonicalType; } /* namespace upb */ #endif UPB_DECLARE_TYPE(upb::BufferHandle, upb_bufhandle) UPB_DECLARE_TYPE(upb::BytesHandler, upb_byteshandler) UPB_DECLARE_TYPE(upb::HandlerAttributes, upb_handlerattr) UPB_DECLARE_DERIVED_TYPE(upb::Handlers, upb::RefCounted, upb_handlers, upb_refcounted) /* The maximum depth that the handler graph can have. This is a resource limit * for the C stack since we sometimes need to recursively traverse the graph. * Cycles are ok; the traversal will stop when it detects a cycle, but we must * hit the cycle before the maximum depth is reached. * * If having a single static limit is too inflexible, we can add another variant * of Handlers::Freeze that allows specifying this as a parameter. */ #define UPB_MAX_HANDLER_DEPTH 64 /* All the different types of handlers that can be registered. * Only needed for the advanced functions in upb::Handlers. */ typedef enum { UPB_HANDLER_INT32, UPB_HANDLER_INT64, UPB_HANDLER_UINT32, UPB_HANDLER_UINT64, UPB_HANDLER_FLOAT, UPB_HANDLER_DOUBLE, UPB_HANDLER_BOOL, UPB_HANDLER_STARTSTR, UPB_HANDLER_STRING, UPB_HANDLER_ENDSTR, UPB_HANDLER_STARTSUBMSG, UPB_HANDLER_ENDSUBMSG, UPB_HANDLER_STARTSEQ, UPB_HANDLER_ENDSEQ } upb_handlertype_t; #define UPB_HANDLER_MAX (UPB_HANDLER_ENDSEQ+1) #define UPB_BREAK NULL /* A convenient definition for when no closure is needed. */ extern char _upb_noclosure; #define UPB_NO_CLOSURE &_upb_noclosure /* A selector refers to a specific field handler in the Handlers object * (for example: the STARTSUBMSG handler for field "field15"). */ typedef int32_t upb_selector_t; UPB_BEGIN_EXTERN_C /* Forward-declares for C inline accessors. We need to declare these here * so we can "friend" them in the class declarations in C++. */ UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s); UPB_INLINE const void *upb_handlerattr_handlerdata(const upb_handlerattr *attr); UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h, upb_selector_t s); UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h); UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj, const void *type); UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf, size_t ofs); UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h); UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h); UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h); UPB_END_EXTERN_C /* Static selectors for upb::Handlers. */ #define UPB_STARTMSG_SELECTOR 0 #define UPB_ENDMSG_SELECTOR 1 #define UPB_STATIC_SELECTOR_COUNT 2 /* Static selectors for upb::BytesHandler. */ #define UPB_STARTSTR_SELECTOR 0 #define UPB_STRING_SELECTOR 1 #define UPB_ENDSTR_SELECTOR 2 typedef void upb_handlerfree(void *d); #ifdef __cplusplus /* A set of attributes that accompanies a handler's function pointer. */ class upb::HandlerAttributes { public: HandlerAttributes(); ~HandlerAttributes(); /* Sets the handler data that will be passed as the second parameter of the * handler. To free this pointer when the handlers are freed, call * Handlers::AddCleanup(). */ bool SetHandlerData(const void *handler_data); const void* handler_data() const; /* Use this to specify the type of the closure. This will be checked against * all other closure types for handler that use the same closure. * Registration will fail if this does not match all other non-NULL closure * types. */ bool SetClosureType(const void *closure_type); const void* closure_type() const; /* Use this to specify the type of the returned closure. Only used for * Start*{String,SubMessage,Sequence} handlers. This must match the closure * type of any handlers that use it (for example, the StringBuf handler must * match the closure returned from StartString). */ bool SetReturnClosureType(const void *return_closure_type); const void* return_closure_type() const; /* Set to indicate that the handler always returns "ok" (either "true" or a * non-NULL closure). This is a hint that can allow code generators to * generate more efficient code. */ bool SetAlwaysOk(bool always_ok); bool always_ok() const; private: friend UPB_INLINE const void * ::upb_handlerattr_handlerdata( const upb_handlerattr *attr); #else struct upb_handlerattr { #endif const void *handler_data_; const void *closure_type_; const void *return_closure_type_; bool alwaysok_; }; #define UPB_HANDLERATTR_INITIALIZER {NULL, NULL, NULL, false} typedef struct { upb_func *func; /* It is wasteful to include the entire attributes here: * * * Some of the information is redundant (like storing the closure type * separately for each handler that must match). * * Some of the info is only needed prior to freeze() (like closure types). * * alignment padding wastes a lot of space for alwaysok_. * * If/when the size and locality of handlers is an issue, we can optimize this * not to store the entire attr like this. We do not expose the table's * layout to allow this optimization in the future. */ upb_handlerattr attr; } upb_handlers_tabent; #ifdef __cplusplus /* Extra information about a buffer that is passed to a StringBuf handler. * TODO(haberman): allow the handle to be pinned so that it will outlive * the handler invocation. */ class upb::BufferHandle { public: BufferHandle(); ~BufferHandle(); /* The beginning of the buffer. This may be different than the pointer * passed to a StringBuf handler because the handler may receive data * that is from the middle or end of a larger buffer. */ const char* buffer() const; /* The offset within the attached object where this buffer begins. Only * meaningful if there is an attached object. */ size_t object_offset() const; /* Note that object_offset is the offset of "buf" within the attached * object. */ void SetBuffer(const char* buf, size_t object_offset); /* The BufferHandle can have an "attached object", which can be used to * tunnel through a pointer to the buffer's underlying representation. */ template
void SetAttachedObject(const T* obj); /* Returns NULL if the attached object is not of this type. */ template
const T* GetAttachedObject() const; private: friend UPB_INLINE void ::upb_bufhandle_init(upb_bufhandle *h); friend UPB_INLINE void ::upb_bufhandle_setobj(upb_bufhandle *h, const void *obj, const void *type); friend UPB_INLINE void ::upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf, size_t ofs); friend UPB_INLINE const void* ::upb_bufhandle_obj(const upb_bufhandle *h); friend UPB_INLINE const void* ::upb_bufhandle_objtype( const upb_bufhandle *h); friend UPB_INLINE const char* ::upb_bufhandle_buf(const upb_bufhandle *h); #else struct upb_bufhandle { #endif const char *buf_; const void *obj_; const void *objtype_; size_t objofs_; }; #ifdef __cplusplus /* A upb::Handlers object represents the set of handlers associated with a * message in the graph of messages. You can think of it as a big virtual * table with functions corresponding to all the events that can fire while * parsing or visiting a message of a specific type. * * Any handlers that are not set behave as if they had successfully consumed * the value. Any unset Start* handlers will propagate their closure to the * inner frame. * * The easiest way to create the *Handler objects needed by the Set* methods is * with the UpbBind() and UpbMakeHandler() macros; see below. */ class upb::Handlers { public: typedef upb_selector_t Selector; typedef upb_handlertype_t Type; typedef Handler
StartFieldHandler; typedef Handler
EndFieldHandler; typedef Handler
StartMessageHandler; typedef Handler
EndMessageHandler; typedef Handler
StartStringHandler; typedef Handler
StringHandler; template
struct ValueHandler { typedef Handler
H; }; typedef ValueHandler
::H Int32Handler; typedef ValueHandler
::H Int64Handler; typedef ValueHandler
::H UInt32Handler; typedef ValueHandler
::H UInt64Handler; typedef ValueHandler
::H FloatHandler; typedef ValueHandler
::H DoubleHandler; typedef ValueHandler
::H BoolHandler; /* Any function pointer can be converted to this and converted back to its * correct type. */ typedef void GenericFunction(); typedef void HandlersCallback(const void *closure, upb_handlers *h); /* Returns a new handlers object for the given frozen msgdef. * Returns NULL if memory allocation failed. */ static reffed_ptr
New(const MessageDef *m); /* Convenience function for registering a graph of handlers that mirrors the * graph of msgdefs for some message. For "m" and all its children a new set * of handlers will be created and the given callback will be invoked, * allowing the client to register handlers for this message. Note that any * subhandlers set by the callback will be overwritten. */ static reffed_ptr
NewFrozen(const MessageDef *m, HandlersCallback *callback, const void *closure); /* Functionality from upb::RefCounted. */ UPB_REFCOUNTED_CPPMETHODS /* All handler registration functions return bool to indicate success or * failure; details about failures are stored in this status object. If a * failure does occur, it must be cleared before the Handlers are frozen, * otherwise the freeze() operation will fail. The functions may *only* be * used while the Handlers are mutable. */ const Status* status(); void ClearError(); /* Call to freeze these Handlers. Requires that any SubHandlers are already * frozen. For cycles, you must use the static version below and freeze the * whole graph at once. */ bool Freeze(Status* s); /* Freezes the given set of handlers. You may not freeze a handler without * also freezing any handlers they point to. */ static bool Freeze(Handlers*const* handlers, int n, Status* s); static bool Freeze(const std::vector
& handlers, Status* s); /* Returns the msgdef associated with this handlers object. */ const MessageDef* message_def() const; /* Adds the given pointer and function to the list of cleanup functions that * will be run when these handlers are freed. If this pointer has previously * been registered, the function returns false and does nothing. */ bool AddCleanup(void *ptr, upb_handlerfree *cleanup); /* Sets the startmsg handler for the message, which is defined as follows: * * bool startmsg(MyType* closure) { * // Called when the message begins. Returns true if processing should * // continue. * return true; * } */ bool SetStartMessageHandler(const StartMessageHandler& handler); /* Sets the endmsg handler for the message, which is defined as follows: * * bool endmsg(MyType* closure, upb_status *status) { * // Called when processing of this message ends, whether in success or * // failure. "status" indicates the final status of processing, and * // can also be modified in-place to update the final status. * } */ bool SetEndMessageHandler(const EndMessageHandler& handler); /* Sets the value handler for the given field, which is defined as follows * (this is for an int32 field; other field types will pass their native * C/C++ type for "val"): * * bool OnValue(MyClosure* c, const MyHandlerData* d, int32_t val) { * // Called when the field's value is encountered. "d" contains * // whatever data was bound to this field when it was registered. * // Returns true if processing should continue. * return true; * } * * handers->SetInt32Handler(f, UpbBind(OnValue, new MyHandlerData(...))); * * The value type must exactly match f->type(). * For example, a handler that takes an int32_t parameter may only be used for * fields of type UPB_TYPE_INT32 and UPB_TYPE_ENUM. * * Returns false if the handler failed to register; in this case the cleanup * handler (if any) will be called immediately. */ bool SetInt32Handler (const FieldDef* f, const Int32Handler& h); bool SetInt64Handler (const FieldDef* f, const Int64Handler& h); bool SetUInt32Handler(const FieldDef* f, const UInt32Handler& h); bool SetUInt64Handler(const FieldDef* f, const UInt64Handler& h); bool SetFloatHandler (const FieldDef* f, const FloatHandler& h); bool SetDoubleHandler(const FieldDef* f, const DoubleHandler& h); bool SetBoolHandler (const FieldDef* f, const BoolHandler& h); /* Like the previous, but templated on the type on the value (ie. int32). * This is mostly useful to call from other templates. To call this you must * specify the template parameter explicitly, ie: * h->SetValueHandler
(f, UpbBind(MyHandler
, MyData)); */ template
bool SetValueHandler( const FieldDef *f, const typename ValueHandler
::Type>::H& handler); /* Sets handlers for a string field, which are defined as follows: * * MySubClosure* startstr(MyClosure* c, const MyHandlerData* d, * size_t size_hint) { * // Called when a string value begins. The return value indicates the * // closure for the string. "size_hint" indicates the size of the * // string if it is known, however if the string is length-delimited * // and the end-of-string is not available size_hint will be zero. * // This case is indistinguishable from the case where the size is * // known to be zero. * // * // TODO(haberman): is it important to distinguish these cases? * // If we had ssize_t as a type we could make -1 "unknown", but * // ssize_t is POSIX (not ANSI) and therefore less portable. * // In practice I suspect it won't be important to distinguish. * return closure; * } * * size_t str(MyClosure* closure, const MyHandlerData* d, * const char *str, size_t len) { * // Called for each buffer of string data; the multiple physical buffers * // are all part of the same logical string. The return value indicates * // how many bytes were consumed. If this number is less than "len", * // this will also indicate that processing should be halted for now, * // like returning false or UPB_BREAK from any other callback. If * // number is greater than "len", the excess bytes will be skipped over * // and not passed to the callback. * return len; * } * * bool endstr(MyClosure* c, const MyHandlerData* d) { * // Called when a string value ends. Return value indicates whether * // processing should continue. * return true; * } */ bool SetStartStringHandler(const FieldDef* f, const StartStringHandler& h); bool SetStringHandler(const FieldDef* f, const StringHandler& h); bool SetEndStringHandler(const FieldDef* f, const EndFieldHandler& h); /* Sets the startseq handler, which is defined as follows: * * MySubClosure *startseq(MyClosure* c, const MyHandlerData* d) { * // Called when a sequence (repeated field) begins. The returned * // pointer indicates the closure for the sequence (or UPB_BREAK * // to interrupt processing). * return closure; * } * * h->SetStartSequenceHandler(f, UpbBind(startseq, new MyHandlerData(...))); * * Returns "false" if "f" does not belong to this message or is not a * repeated field. */ bool SetStartSequenceHandler(const FieldDef* f, const StartFieldHandler& h); /* Sets the startsubmsg handler for the given field, which is defined as * follows: * * MySubClosure* startsubmsg(MyClosure* c, const MyHandlerData* d) { * // Called when a submessage begins. The returned pointer indicates the * // closure for the sequence (or UPB_BREAK to interrupt processing). * return closure; * } * * h->SetStartSubMessageHandler(f, UpbBind(startsubmsg, * new MyHandlerData(...))); * * Returns "false" if "f" does not belong to this message or is not a * submessage/group field. */ bool SetStartSubMessageHandler(const FieldDef* f, const StartFieldHandler& h); /* Sets the endsubmsg handler for the given field, which is defined as * follows: * * bool endsubmsg(MyClosure* c, const MyHandlerData* d) { * // Called when a submessage ends. Returns true to continue processing. * return true; * } * * Returns "false" if "f" does not belong to this message or is not a * submessage/group field. */ bool SetEndSubMessageHandler(const FieldDef *f, const EndFieldHandler &h); /* Starts the endsubseq handler for the given field, which is defined as * follows: * * bool endseq(MyClosure* c, const MyHandlerData* d) { * // Called when a sequence ends. Returns true continue processing. * return true; * } * * Returns "false" if "f" does not belong to this message or is not a * repeated field. */ bool SetEndSequenceHandler(const FieldDef* f, const EndFieldHandler& h); /* Sets or gets the object that specifies handlers for the given field, which * must be a submessage or group. Returns NULL if no handlers are set. */ bool SetSubHandlers(const FieldDef* f, const Handlers* sub); const Handlers* GetSubHandlers(const FieldDef* f) const; /* Equivalent to GetSubHandlers, but takes the STARTSUBMSG selector for the * field. */ const Handlers* GetSubHandlers(Selector startsubmsg) const; /* A selector refers to a specific field handler in the Handlers object * (for example: the STARTSUBMSG handler for field "field15"). * On success, returns true and stores the selector in "s". * If the FieldDef or Type are invalid, returns false. * The returned selector is ONLY valid for Handlers whose MessageDef * contains this FieldDef. */ static bool GetSelector(const FieldDef* f, Type type, Selector* s); /* Given a START selector of any kind, returns the corresponding END selector. */ static Selector GetEndSelector(Selector start_selector); /* Returns the function pointer for this handler. It is the client's * responsibility to cast to the correct function type before calling it. */ GenericFunction* GetHandler(Selector selector); /* Sets the given attributes to the attributes for this selector. */ bool GetAttributes(Selector selector, HandlerAttributes* attr); /* Returns the handler data that was registered with this handler. */ const void* GetHandlerData(Selector selector); /* Could add any of the following functions as-needed, with some minor * implementation changes: * * const FieldDef* GetFieldDef(Selector selector); * static bool IsSequence(Selector selector); */ private: UPB_DISALLOW_POD_OPS(Handlers, upb::Handlers) friend UPB_INLINE GenericFunction *::upb_handlers_gethandler( const upb_handlers *h, upb_selector_t s); friend UPB_INLINE const void *::upb_handlers_gethandlerdata( const upb_handlers *h, upb_selector_t s); #else struct upb_handlers { #endif upb_refcounted base; const upb_msgdef *msg; const upb_handlers **sub; const void *top_closure_type; upb_inttable cleanup_; upb_status status_; /* Used only when mutable. */ upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */ }; #ifdef __cplusplus namespace upb { /* Convenience macros for creating a Handler object that is wrapped with a * type-safe wrapper function that converts the "void*" parameters/returns * of the underlying C API into nice C++ function. * * Sample usage: * void OnValue1(MyClosure* c, const MyHandlerData* d, int32_t val) { * // do stuff ... * } * * // Handler that doesn't need any data bound to it. * void OnValue2(MyClosure* c, int32_t val) { * // do stuff ... * } * * // Handler that returns bool so it can return failure if necessary. * bool OnValue3(MyClosure* c, int32_t val) { * // do stuff ... * return ok; * } * * // Member function handler. * class MyClosure { * public: * void OnValue(int32_t val) { * // do stuff ... * } * }; * * // Takes ownership of the MyHandlerData. * handlers->SetInt32Handler(f1, UpbBind(OnValue1, new MyHandlerData(...))); * handlers->SetInt32Handler(f2, UpbMakeHandler(OnValue2)); * handlers->SetInt32Handler(f1, UpbMakeHandler(OnValue3)); * handlers->SetInt32Handler(f2, UpbMakeHandler(&MyClosure::OnValue)); */ #ifdef UPB_CXX11 /* In C++11, the "template" disambiguator can appear even outside templates, * so all calls can safely use this pair of macros. */ #define UpbMakeHandler(f) upb::MatchFunc(f).template GetFunc
() /* We have to be careful to only evaluate "d" once. */ #define UpbBind(f, d) upb::MatchFunc(f).template GetFunc
((d)) #else /* Prior to C++11, the "template" disambiguator may only appear inside a * template, so the regular macro must not use "template" */ #define UpbMakeHandler(f) upb::MatchFunc(f).GetFunc
() #define UpbBind(f, d) upb::MatchFunc(f).GetFunc
((d)) #endif /* UPB_CXX11 */ /* This macro must be used in C++98 for calls from inside a template. But we * define this variant in all cases; code that wants to be compatible with both * C++98 and C++11 should always use this macro when calling from a template. */ #define UpbMakeHandlerT(f) upb::MatchFunc(f).template GetFunc
() /* We have to be careful to only evaluate "d" once. */ #define UpbBindT(f, d) upb::MatchFunc(f).template GetFunc
((d)) /* Handler: a struct that contains the (handler, data, deleter) tuple that is * used to register all handlers. Users can Make() these directly but it's * more convenient to use the UpbMakeHandler/UpbBind macros above. */ template
class Handler { public: /* The underlying, handler function signature that upb uses internally. */ typedef T FuncPtr; /* Intentionally implicit. */ template
Handler(F func); ~Handler(); private: void AddCleanup(Handlers* h) const { if (cleanup_func_) { bool ok = h->AddCleanup(cleanup_data_, cleanup_func_); UPB_ASSERT_VAR(ok, ok); } } UPB_DISALLOW_COPY_AND_ASSIGN(Handler) friend class Handlers; FuncPtr handler_; mutable HandlerAttributes attr_; mutable bool registered_; void *cleanup_data_; upb_handlerfree *cleanup_func_; }; } /* namespace upb */ #endif /* __cplusplus */ UPB_BEGIN_EXTERN_C /* Native C API. */ /* Handler function typedefs. */ typedef bool upb_startmsg_handlerfunc(void *c, const void*); typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status); typedef void* upb_startfield_handlerfunc(void *c, const void *hd); typedef bool upb_endfield_handlerfunc(void *c, const void *hd); typedef bool upb_int32_handlerfunc(void *c, const void *hd, int32_t val); typedef bool upb_int64_handlerfunc(void *c, const void *hd, int64_t val); typedef bool upb_uint32_handlerfunc(void *c, const void *hd, uint32_t val); typedef bool upb_uint64_handlerfunc(void *c, const void *hd, uint64_t val); typedef bool upb_float_handlerfunc(void *c, const void *hd, float val); typedef bool upb_double_handlerfunc(void *c, const void *hd, double val); typedef bool upb_bool_handlerfunc(void *c, const void *hd, bool val); typedef void *upb_startstr_handlerfunc(void *c, const void *hd, size_t size_hint); typedef size_t upb_string_handlerfunc(void *c, const void *hd, const char *buf, size_t n, const upb_bufhandle* handle); /* upb_bufhandle */ size_t upb_bufhandle_objofs(const upb_bufhandle *h); /* upb_handlerattr */ void upb_handlerattr_init(upb_handlerattr *attr); void upb_handlerattr_uninit(upb_handlerattr *attr); bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd); bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type); const void *upb_handlerattr_closuretype(const upb_handlerattr *attr); bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr, const void *type); const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr); bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok); bool upb_handlerattr_alwaysok(const upb_handlerattr *attr); UPB_INLINE const void *upb_handlerattr_handlerdata( const upb_handlerattr *attr) { return attr->handler_data_; } /* upb_handlers */ typedef void upb_handlers_callback(const void *closure, upb_handlers *h); upb_handlers *upb_handlers_new(const upb_msgdef *m, const void *owner); const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m, const void *owner, upb_handlers_callback *callback, const void *closure); /* Include refcounted methods like upb_handlers_ref(). */ UPB_REFCOUNTED_CMETHODS(upb_handlers, upb_handlers_upcast) const upb_status *upb_handlers_status(upb_handlers *h); void upb_handlers_clearerr(upb_handlers *h); const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h); bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree); bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setint32(upb_handlers *h, const upb_fielddef *f, upb_int32_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setint64(upb_handlers *h, const upb_fielddef *f, upb_int64_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setuint32(upb_handlers *h, const upb_fielddef *f, upb_uint32_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setuint64(upb_handlers *h, const upb_fielddef *f, upb_uint64_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setfloat(upb_handlers *h, const upb_fielddef *f, upb_float_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setdouble(upb_handlers *h, const upb_fielddef *f, upb_double_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setbool(upb_handlers *h, const upb_fielddef *f, upb_bool_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setstartstr(upb_handlers *h, const upb_fielddef *f, upb_startstr_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setstring(upb_handlers *h, const upb_fielddef *f, upb_string_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setendstr(upb_handlers *h, const upb_fielddef *f, upb_endfield_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setstartseq(upb_handlers *h, const upb_fielddef *f, upb_startfield_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setstartsubmsg(upb_handlers *h, const upb_fielddef *f, upb_startfield_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setendsubmsg(upb_handlers *h, const upb_fielddef *f, upb_endfield_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setendseq(upb_handlers *h, const upb_fielddef *f, upb_endfield_handlerfunc *func, upb_handlerattr *attr); bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f, const upb_handlers *sub); const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h, const upb_fielddef *f); const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h, upb_selector_t sel); UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s) { return (upb_func *)h->table[s].func; } bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t s, upb_handlerattr *attr); UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h, upb_selector_t s) { return upb_handlerattr_handlerdata(&h->table[s].attr); } #ifdef __cplusplus /* Handler types for single fields. * Right now we only have one for TYPE_BYTES but ones for other types * should follow. * * These follow the same handlers protocol for fields of a message. */ class upb::BytesHandler { public: BytesHandler(); ~BytesHandler(); #else struct upb_byteshandler { #endif upb_handlers_tabent table[3]; }; void upb_byteshandler_init(upb_byteshandler *h); /* Caller must ensure that "d" outlives the handlers. * TODO(haberman): should this have a "freeze" operation? It's not necessary * for memory management, but could be useful to force immutability and provide * a convenient moment to verify that all registration succeeded. */ bool upb_byteshandler_setstartstr(upb_byteshandler *h, upb_startstr_handlerfunc *func, void *d); bool upb_byteshandler_setstring(upb_byteshandler *h, upb_string_handlerfunc *func, void *d); bool upb_byteshandler_setendstr(upb_byteshandler *h, upb_endfield_handlerfunc *func, void *d); /* "Static" methods */ bool upb_handlers_freeze(upb_handlers *const *handlers, int n, upb_status *s); upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f); bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type, upb_selector_t *s); UPB_INLINE upb_selector_t upb_handlers_getendselector(upb_selector_t start) { return start + 1; } /* Internal-only. */ uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f); uint32_t upb_handlers_selectorcount(const upb_fielddef *f); UPB_END_EXTERN_C /* ** Inline definitions for handlers.h, which are particularly long and a bit ** tricky. */ #ifndef UPB_HANDLERS_INL_H_ #define UPB_HANDLERS_INL_H_ #include
/* C inline methods. */ /* upb_bufhandle */ UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h) { h->obj_ = NULL; h->objtype_ = NULL; h->buf_ = NULL; h->objofs_ = 0; } UPB_INLINE void upb_bufhandle_uninit(upb_bufhandle *h) { UPB_UNUSED(h); } UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj, const void *type) { h->obj_ = obj; h->objtype_ = type; } UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf, size_t ofs) { h->buf_ = buf; h->objofs_ = ofs; } UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h) { return h->obj_; } UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h) { return h->objtype_; } UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h) { return h->buf_; } #ifdef __cplusplus /* Type detection and typedefs for integer types. * For platforms where there are multiple 32-bit or 64-bit types, we need to be * able to enumerate them so we can properly create overloads for all variants. * * If any platform existed where there were three integer types with the same * size, this would have to become more complicated. For example, short, int, * and long could all be 32-bits. Even more diabolically, short, int, long, * and long long could all be 64 bits and still be standard-compliant. * However, few platforms are this strange, and it's unlikely that upb will be * used on the strangest ones. */ /* Can't count on stdint.h limits like INT32_MAX, because in C++ these are * only defined when __STDC_LIMIT_MACROS are defined before the *first* include * of stdint.h. We can't guarantee that someone else didn't include these first * without defining __STDC_LIMIT_MACROS. */ #define UPB_INT32_MAX 0x7fffffffLL #define UPB_INT32_MIN (-UPB_INT32_MAX - 1) #define UPB_INT64_MAX 0x7fffffffffffffffLL #define UPB_INT64_MIN (-UPB_INT64_MAX - 1) #if INT_MAX == UPB_INT32_MAX && INT_MIN == UPB_INT32_MIN #define UPB_INT_IS_32BITS 1 #endif #if LONG_MAX == UPB_INT32_MAX && LONG_MIN == UPB_INT32_MIN #define UPB_LONG_IS_32BITS 1 #endif #if LONG_MAX == UPB_INT64_MAX && LONG_MIN == UPB_INT64_MIN #define UPB_LONG_IS_64BITS 1 #endif #if LLONG_MAX == UPB_INT64_MAX && LLONG_MIN == UPB_INT64_MIN #define UPB_LLONG_IS_64BITS 1 #endif /* We use macros instead of typedefs so we can undefine them later and avoid * leaking them outside this header file. */ #if UPB_INT_IS_32BITS #define UPB_INT32_T int #define UPB_UINT32_T unsigned int #if UPB_LONG_IS_32BITS #define UPB_TWO_32BIT_TYPES 1 #define UPB_INT32ALT_T long #define UPB_UINT32ALT_T unsigned long #endif /* UPB_LONG_IS_32BITS */ #elif UPB_LONG_IS_32BITS /* && !UPB_INT_IS_32BITS */ #define UPB_INT32_T long #define UPB_UINT32_T unsigned long #endif /* UPB_INT_IS_32BITS */ #if UPB_LONG_IS_64BITS #define UPB_INT64_T long #define UPB_UINT64_T unsigned long #if UPB_LLONG_IS_64BITS #define UPB_TWO_64BIT_TYPES 1 #define UPB_INT64ALT_T long long #define UPB_UINT64ALT_T unsigned long long #endif /* UPB_LLONG_IS_64BITS */ #elif UPB_LLONG_IS_64BITS /* && !UPB_LONG_IS_64BITS */ #define UPB_INT64_T long long #define UPB_UINT64_T unsigned long long #endif /* UPB_LONG_IS_64BITS */ #undef UPB_INT32_MAX #undef UPB_INT32_MIN #undef UPB_INT64_MAX #undef UPB_INT64_MIN #undef UPB_INT_IS_32BITS #undef UPB_LONG_IS_32BITS #undef UPB_LONG_IS_64BITS #undef UPB_LLONG_IS_64BITS namespace upb { typedef void CleanupFunc(void *ptr); /* Template to remove "const" from "const T*" and just return "T*". * * We define a nonsense default because otherwise it will fail to instantiate as * a function parameter type even in cases where we don't expect any caller to * actually match the overload. */ class CouldntRemoveConst {}; template
struct remove_constptr { typedef CouldntRemoveConst type; }; template
struct remove_constptr
{ typedef T *type; }; /* Template that we use below to remove a template specialization from * consideration if it matches a specific type. */ template
struct disable_if_same { typedef void Type; }; template
struct disable_if_same
{}; template
void DeletePointer(void *p) { delete static_cast
(p); } template
struct FirstUnlessVoidOrBool { typedef T1 value; }; template
struct FirstUnlessVoidOrBool
{ typedef T2 value; }; template
struct FirstUnlessVoidOrBool
{ typedef T2 value; }; template
struct is_same { static bool value; }; template
struct is_same
{ static bool value; }; template
bool is_same
::value = false; template
bool is_same
::value = true; /* FuncInfo *******************************************************************/ /* Info about the user's original, pre-wrapped function. */ template
struct FuncInfo { /* The type of the closure that the function takes (its first param). */ typedef C Closure; /* The return type. */ typedef R Return; }; /* Func ***********************************************************************/ /* Func1, Func2, Func3: Template classes representing a function and its * signature. * * Since the function is a template parameter, calling the function can be * inlined at compile-time and does not require a function pointer at runtime. * These functions are not bound to a handler data so have no data or cleanup * handler. */ struct UnboundFunc { CleanupFunc *GetCleanup() { return NULL; } void *GetData() { return NULL; } }; template
struct Func1 : public UnboundFunc { typedef R Return; typedef I FuncInfo; static R Call(P1 p1) { return F(p1); } }; template
struct Func2 : public UnboundFunc { typedef R Return; typedef I FuncInfo; static R Call(P1 p1, P2 p2) { return F(p1, p2); } }; template
struct Func3 : public UnboundFunc { typedef R Return; typedef I FuncInfo; static R Call(P1 p1, P2 p2, P3 p3) { return F(p1, p2, p3); } }; template
struct Func4 : public UnboundFunc { typedef R Return; typedef I FuncInfo; static R Call(P1 p1, P2 p2, P3 p3, P4 p4) { return F(p1, p2, p3, p4); } }; template
struct Func5 : public UnboundFunc { typedef R Return; typedef I FuncInfo; static R Call(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { return F(p1, p2, p3, p4, p5); } }; /* BoundFunc ******************************************************************/ /* BoundFunc2, BoundFunc3: Like Func2/Func3 except also contains a value that * shall be bound to the function's second parameter. * * Note that the second parameter is a const pointer, but our stored bound value * is non-const so we can free it when the handlers are destroyed. */ template
struct BoundFunc { typedef typename remove_constptr
::type MutableP2; explicit BoundFunc(MutableP2 data_) : data(data_) {} CleanupFunc *GetCleanup() { return &DeletePointer
; } MutableP2 GetData() { return data; } MutableP2 data; }; template
struct BoundFunc2 : public BoundFunc
{ typedef BoundFunc
Base; typedef I FuncInfo; explicit BoundFunc2(typename Base::MutableP2 arg) : Base(arg) {} }; template
struct BoundFunc3 : public BoundFunc
{ typedef BoundFunc
Base; typedef I FuncInfo; explicit BoundFunc3(typename Base::MutableP2 arg) : Base(arg) {} }; template
struct BoundFunc4 : public BoundFunc
{ typedef BoundFunc
Base; typedef I FuncInfo; explicit BoundFunc4(typename Base::MutableP2 arg) : Base(arg) {} }; template
struct BoundFunc5 : public BoundFunc
{ typedef BoundFunc
Base; typedef I FuncInfo; explicit BoundFunc5(typename Base::MutableP2 arg) : Base(arg) {} }; /* FuncSig ********************************************************************/ /* FuncSig1, FuncSig2, FuncSig3: template classes reflecting a function * *signature*, but without a specific function attached. * * These classes contain member functions that can be invoked with a * specific function to return a Func/BoundFunc class. */ template
struct FuncSig1 { template
Func1
> GetFunc() { return Func1
>(); } }; template
struct FuncSig2 { template
Func2
> GetFunc() { return Func2
>(); } template
BoundFunc2
> GetFunc( typename remove_constptr
::type param2) { return BoundFunc2
>(param2); } }; template
struct FuncSig3 { template
Func3
> GetFunc() { return Func3
>(); } template
BoundFunc3
> GetFunc( typename remove_constptr
::type param2) { return BoundFunc3
>(param2); } }; template
struct FuncSig4 { template
Func4
> GetFunc() { return Func4
>(); } template
BoundFunc4
> GetFunc( typename remove_constptr
::type param2) { return BoundFunc4
>(param2); } }; template
struct FuncSig5 { template
Func5
> GetFunc() { return Func5
>(); } template
BoundFunc5
> GetFunc( typename remove_constptr
::type param2) { return BoundFunc5
>(param2); } }; /* Overloaded template function that can construct the appropriate FuncSig* * class given a function pointer by deducing the template parameters. */ template
inline FuncSig1
MatchFunc(R (*f)(P1)) { UPB_UNUSED(f); /* Only used for template parameter deduction. */ return FuncSig1
(); } template
inline FuncSig2
MatchFunc(R (*f)(P1, P2)) { UPB_UNUSED(f); /* Only used for template parameter deduction. */ return FuncSig2
(); } template
inline FuncSig3
MatchFunc(R (*f)(P1, P2, P3)) { UPB_UNUSED(f); /* Only used for template parameter deduction. */ return FuncSig3
(); } template
inline FuncSig4
MatchFunc(R (*f)(P1, P2, P3, P4)) { UPB_UNUSED(f); /* Only used for template parameter deduction. */ return FuncSig4
(); } template
inline FuncSig5
MatchFunc(R (*f)(P1, P2, P3, P4, P5)) { UPB_UNUSED(f); /* Only used for template parameter deduction. */ return FuncSig5
(); } /* MethodSig ******************************************************************/ /* CallMethod*: a function template that calls a given method. */ template
R CallMethod0(C *obj) { return ((*obj).*F)(); } template
R CallMethod1(C *obj, P1 arg1) { return ((*obj).*F)(arg1); } template
R CallMethod2(C *obj, P1 arg1, P2 arg2) { return ((*obj).*F)(arg1, arg2); } template
R CallMethod3(C *obj, P1 arg1, P2 arg2, P3 arg3) { return ((*obj).*F)(arg1, arg2, arg3); } template
R CallMethod4(C *obj, P1 arg1, P2 arg2, P3 arg3, P4 arg4) { return ((*obj).*F)(arg1, arg2, arg3, arg4); } /* MethodSig: like FuncSig, but for member functions. * * GetFunc() returns a normal FuncN object, so after calling GetFunc() no * more logic is required to special-case methods. */ template
struct MethodSig0 { template
Func1
, FuncInfo
> GetFunc() { return Func1
, FuncInfo
>(); } }; template
struct MethodSig1 { template
Func2