1 // Amalgamated source file 2 /* 3 ** Defs are upb's internal representation of the constructs that can appear 4 ** in a .proto file: 5 ** 6 ** - upb::MessageDef (upb_msgdef): describes a "message" construct. 7 ** - upb::FieldDef (upb_fielddef): describes a message field. 8 ** - upb::FileDef (upb_filedef): describes a .proto file and its defs. 9 ** - upb::EnumDef (upb_enumdef): describes an enum. 10 ** - upb::OneofDef (upb_oneofdef): describes a oneof. 11 ** - upb::Def (upb_def): base class of all the others. 12 ** 13 ** TODO: definitions of services. 14 ** 15 ** Like upb_refcounted objects, defs are mutable only until frozen, and are 16 ** only thread-safe once frozen. 17 ** 18 ** This is a mixed C/C++ interface that offers a full API to both languages. 19 ** See the top-level README for more information. 20 */ 21 22 #ifndef UPB_DEF_H_ 23 #define UPB_DEF_H_ 24 25 /* 26 ** upb::RefCounted (upb_refcounted) 27 ** 28 ** A refcounting scheme that supports circular refs. It accomplishes this by 29 ** partitioning the set of objects into groups such that no cycle spans groups; 30 ** we can then reference-count the group as a whole and ignore refs within the 31 ** group. When objects are mutable, these groups are computed very 32 ** conservatively; we group any objects that have ever had a link between them. 33 ** When objects are frozen, we compute strongly-connected components which 34 ** allows us to be precise and only group objects that are actually cyclic. 35 ** 36 ** This is a mixed C/C++ interface that offers a full API to both languages. 37 ** See the top-level README for more information. 38 */ 39 40 #ifndef UPB_REFCOUNTED_H_ 41 #define UPB_REFCOUNTED_H_ 42 43 /* 44 ** upb_table 45 ** 46 ** This header is INTERNAL-ONLY! Its interfaces are not public or stable! 47 ** This file defines very fast int->upb_value (inttable) and string->upb_value 48 ** (strtable) hash tables. 49 ** 50 ** The table uses chained scatter with Brent's variation (inspired by the Lua 51 ** implementation of hash tables). The hash function for strings is Austin 52 ** Appleby's "MurmurHash." 53 ** 54 ** The inttable uses uintptr_t as its key, which guarantees it can be used to 55 ** store pointers or integers of at least 32 bits (upb isn't really useful on 56 ** systems where sizeof(void*) < 4). 57 ** 58 ** The table must be homogenous (all values of the same type). In debug 59 ** mode, we check this on insert and lookup. 60 */ 61 62 #ifndef UPB_TABLE_H_ 63 #define UPB_TABLE_H_ 64 65 #include <assert.h> 66 #include <stdint.h> 67 #include <string.h> 68 /* 69 ** This file contains shared definitions that are widely used across upb. 70 ** 71 ** This is a mixed C/C++ interface that offers a full API to both languages. 72 ** See the top-level README for more information. 73 */ 74 75 #ifndef UPB_H_ 76 #define UPB_H_ 77 78 #include <assert.h> 79 #include <stdarg.h> 80 #include <stdbool.h> 81 #include <stddef.h> 82 83 #ifdef __cplusplus 84 namespace upb { 85 class Allocator; 86 class Arena; 87 class Environment; 88 class ErrorSpace; 89 class Status; 90 template <int N> class InlinedArena; 91 template <int N> class InlinedEnvironment; 92 } 93 #endif 94 95 /* UPB_INLINE: inline if possible, emit standalone code if required. */ 96 #ifdef __cplusplus 97 #define UPB_INLINE inline 98 #elif defined (__GNUC__) 99 #define UPB_INLINE static __inline__ 100 #else 101 #define UPB_INLINE static 102 #endif 103 104 /* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler 105 * doesn't provide these preprocessor symbols. */ 106 #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) 107 #define UPB_BIG_ENDIAN 108 #endif 109 110 /* Macros for function attributes on compilers that support them. */ 111 #ifdef __GNUC__ 112 #define UPB_FORCEINLINE __inline__ __attribute__((always_inline)) 113 #define UPB_NOINLINE __attribute__((noinline)) 114 #define UPB_NORETURN __attribute__((__noreturn__)) 115 #else /* !defined(__GNUC__) */ 116 #define UPB_FORCEINLINE 117 #define UPB_NOINLINE 118 #define UPB_NORETURN 119 #endif 120 121 /* A few hacky workarounds for functions not in C89. 122 * For internal use only! 123 * TODO(haberman): fix these by including our own implementations, or finding 124 * another workaround. 125 */ 126 #ifdef __GNUC__ 127 #define _upb_snprintf __builtin_snprintf 128 #define _upb_vsnprintf __builtin_vsnprintf 129 #define _upb_va_copy(a, b) __va_copy(a, b) 130 #elif __STDC_VERSION__ >= 199901L 131 /* C99 versions. */ 132 #define _upb_snprintf snprintf 133 #define _upb_vsnprintf vsnprintf 134 #define _upb_va_copy(a, b) va_copy(a, b) 135 #else 136 #error Need implementations of [v]snprintf and va_copy 137 #endif 138 139 140 #if ((defined(__cplusplus) && __cplusplus >= 201103L) || \ 141 defined(__GXX_EXPERIMENTAL_CXX0X__)) && !defined(UPB_NO_CXX11) 142 #define UPB_CXX11 143 #endif 144 145 /* UPB_DISALLOW_COPY_AND_ASSIGN() 146 * UPB_DISALLOW_POD_OPS() 147 * 148 * Declare these in the "private" section of a C++ class to forbid copy/assign 149 * or all POD ops (construct, destruct, copy, assign) on that class. */ 150 #ifdef UPB_CXX11 151 #include <type_traits> 152 #define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \ 153 class_name(const class_name&) = delete; \ 154 void operator=(const class_name&) = delete; 155 #define UPB_DISALLOW_POD_OPS(class_name, full_class_name) \ 156 class_name() = delete; \ 157 ~class_name() = delete; \ 158 UPB_DISALLOW_COPY_AND_ASSIGN(class_name) 159 #define UPB_ASSERT_STDLAYOUT(type) \ 160 static_assert(std::is_standard_layout<type>::value, \ 161 #type " must be standard layout"); 162 #define UPB_FINAL final 163 #else /* !defined(UPB_CXX11) */ 164 #define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \ 165 class_name(const class_name&); \ 166 void operator=(const class_name&); 167 #define UPB_DISALLOW_POD_OPS(class_name, full_class_name) \ 168 class_name(); \ 169 ~class_name(); \ 170 UPB_DISALLOW_COPY_AND_ASSIGN(class_name) 171 #define UPB_ASSERT_STDLAYOUT(type) 172 #define UPB_FINAL 173 #endif 174 175 /* UPB_DECLARE_TYPE() 176 * UPB_DECLARE_DERIVED_TYPE() 177 * UPB_DECLARE_DERIVED_TYPE2() 178 * 179 * Macros for declaring C and C++ types both, including inheritance. 180 * The inheritance doesn't use real C++ inheritance, to stay compatible with C. 181 * 182 * These macros also provide upcasts: 183 * - in C: types-specific functions (ie. upb_foo_upcast(foo)) 184 * - in C++: upb::upcast(foo) along with implicit conversions 185 * 186 * Downcasts are not provided, but upb/def.h defines downcasts for upb::Def. */ 187 188 #define UPB_C_UPCASTS(ty, base) \ 189 UPB_INLINE base *ty ## _upcast_mutable(ty *p) { return (base*)p; } \ 190 UPB_INLINE const base *ty ## _upcast(const ty *p) { return (const base*)p; } 191 192 #define UPB_C_UPCASTS2(ty, base, base2) \ 193 UPB_C_UPCASTS(ty, base) \ 194 UPB_INLINE base2 *ty ## _upcast2_mutable(ty *p) { return (base2*)p; } \ 195 UPB_INLINE const base2 *ty ## _upcast2(const ty *p) { return (const base2*)p; } 196 197 #ifdef __cplusplus 198 199 #define UPB_BEGIN_EXTERN_C extern "C" { 200 #define UPB_END_EXTERN_C } 201 #define UPB_PRIVATE_FOR_CPP private: 202 #define UPB_DECLARE_TYPE(cppname, cname) typedef cppname cname; 203 204 #define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \ 205 UPB_DECLARE_TYPE(cppname, cname) \ 206 UPB_C_UPCASTS(cname, cbase) \ 207 namespace upb { \ 208 template <> \ 209 class Pointer<cppname> : public PointerBase<cppname, cppbase> { \ 210 public: \ 211 explicit Pointer(cppname* ptr) \ 212 : PointerBase<cppname, cppbase>(ptr) {} \ 213 }; \ 214 template <> \ 215 class Pointer<const cppname> \ 216 : public PointerBase<const cppname, const cppbase> { \ 217 public: \ 218 explicit Pointer(const cppname* ptr) \ 219 : PointerBase<const cppname, const cppbase>(ptr) {} \ 220 }; \ 221 } 222 223 #define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, cname, cbase, \ 224 cbase2) \ 225 UPB_DECLARE_TYPE(cppname, cname) \ 226 UPB_C_UPCASTS2(cname, cbase, cbase2) \ 227 namespace upb { \ 228 template <> \ 229 class Pointer<cppname> : public PointerBase2<cppname, cppbase, cppbase2> { \ 230 public: \ 231 explicit Pointer(cppname* ptr) \ 232 : PointerBase2<cppname, cppbase, cppbase2>(ptr) {} \ 233 }; \ 234 template <> \ 235 class Pointer<const cppname> \ 236 : public PointerBase2<const cppname, const cppbase, const cppbase2> { \ 237 public: \ 238 explicit Pointer(const cppname* ptr) \ 239 : PointerBase2<const cppname, const cppbase, const cppbase2>(ptr) {} \ 240 }; \ 241 } 242 243 #else /* !defined(__cplusplus) */ 244 245 #define UPB_BEGIN_EXTERN_C 246 #define UPB_END_EXTERN_C 247 #define UPB_PRIVATE_FOR_CPP 248 #define UPB_DECLARE_TYPE(cppname, cname) \ 249 struct cname; \ 250 typedef struct cname cname; 251 #define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \ 252 UPB_DECLARE_TYPE(cppname, cname) \ 253 UPB_C_UPCASTS(cname, cbase) 254 #define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, \ 255 cname, cbase, cbase2) \ 256 UPB_DECLARE_TYPE(cppname, cname) \ 257 UPB_C_UPCASTS2(cname, cbase, cbase2) 258 259 #endif /* defined(__cplusplus) */ 260 261 #define UPB_MAX(x, y) ((x) > (y) ? (x) : (y)) 262 #define UPB_MIN(x, y) ((x) < (y) ? (x) : (y)) 263 264 #define UPB_UNUSED(var) (void)var 265 266 /* For asserting something about a variable when the variable is not used for 267 * anything else. This prevents "unused variable" warnings when compiling in 268 * debug mode. */ 269 #define UPB_ASSERT_VAR(var, predicate) UPB_UNUSED(var); assert(predicate) 270 271 /* Generic function type. */ 272 typedef void upb_func(); 273 274 275 /* C++ Casts ******************************************************************/ 276 277 #ifdef __cplusplus 278 279 namespace upb { 280 281 template <class T> class Pointer; 282 283 /* Casts to a subclass. The caller must know that cast is correct; an 284 * incorrect cast will throw an assertion failure in debug mode. 285 * 286 * Example: 287 * upb::Def* def = GetDef(); 288 * // Assert-fails if this was not actually a MessageDef. 289 * upb::MessgeDef* md = upb::down_cast<upb::MessageDef>(def); 290 * 291 * Note that downcasts are only defined for some types (at the moment you can 292 * only downcast from a upb::Def to a specific Def type). */ 293 template<class To, class From> To down_cast(From* f); 294 295 /* Casts to a subclass. If the class does not actually match the given To type, 296 * returns NULL. 297 * 298 * Example: 299 * upb::Def* def = GetDef(); 300 * // md will be NULL if this was not actually a MessageDef. 301 * upb::MessgeDef* md = upb::down_cast<upb::MessageDef>(def); 302 * 303 * Note that dynamic casts are only defined for some types (at the moment you 304 * can only downcast from a upb::Def to a specific Def type).. */ 305 template<class To, class From> To dyn_cast(From* f); 306 307 /* Casts to any base class, or the type itself (ie. can be a no-op). 308 * 309 * Example: 310 * upb::MessageDef* md = GetDef(); 311 * // This will fail to compile if this wasn't actually a base class. 312 * upb::Def* def = upb::upcast(md); 313 */ 314 template <class T> inline Pointer<T> upcast(T *f) { return Pointer<T>(f); } 315 316 /* Attempt upcast to specific base class. 317 * 318 * Example: 319 * upb::MessageDef* md = GetDef(); 320 * upb::upcast_to<upb::Def>(md)->MethodOnDef(); 321 */ 322 template <class T, class F> inline T* upcast_to(F *f) { 323 return static_cast<T*>(upcast(f)); 324 } 325 326 /* PointerBase<T>: implementation detail of upb::upcast(). 327 * It is implicitly convertable to pointers to the Base class(es). 328 */ 329 template <class T, class Base> 330 class PointerBase { 331 public: 332 explicit PointerBase(T* ptr) : ptr_(ptr) {} 333 operator T*() { return ptr_; } 334 operator Base*() { return (Base*)ptr_; } 335 336 private: 337 T* ptr_; 338 }; 339 340 template <class T, class Base, class Base2> 341 class PointerBase2 : public PointerBase<T, Base> { 342 public: 343 explicit PointerBase2(T* ptr) : PointerBase<T, Base>(ptr) {} 344 operator Base2*() { return Pointer<Base>(*this); } 345 }; 346 347 } 348 349 #endif 350 351 352 /* upb::ErrorSpace ************************************************************/ 353 354 /* A upb::ErrorSpace represents some domain of possible error values. This lets 355 * upb::Status attach specific error codes to operations, like POSIX/C errno, 356 * Win32 error codes, etc. Clients who want to know the very specific error 357 * code can check the error space and then know the type of the integer code. 358 * 359 * NOTE: upb::ErrorSpace is currently not used and should be considered 360 * experimental. It is important primarily in cases where upb is performing 361 * I/O, but upb doesn't currently have any components that do this. */ 362 363 UPB_DECLARE_TYPE(upb::ErrorSpace, upb_errorspace) 364 365 #ifdef __cplusplus 366 class upb::ErrorSpace { 367 #else 368 struct upb_errorspace { 369 #endif 370 const char *name; 371 }; 372 373 374 /* upb::Status ****************************************************************/ 375 376 /* upb::Status represents a success or failure status and error message. 377 * It owns no resources and allocates no memory, so it should work 378 * even in OOM situations. */ 379 UPB_DECLARE_TYPE(upb::Status, upb_status) 380 381 /* The maximum length of an error message before it will get truncated. */ 382 #define UPB_STATUS_MAX_MESSAGE 128 383 384 UPB_BEGIN_EXTERN_C 385 386 const char *upb_status_errmsg(const upb_status *status); 387 bool upb_ok(const upb_status *status); 388 upb_errorspace *upb_status_errspace(const upb_status *status); 389 int upb_status_errcode(const upb_status *status); 390 391 /* Any of the functions that write to a status object allow status to be NULL, 392 * to support use cases where the function's caller does not care about the 393 * status message. */ 394 void upb_status_clear(upb_status *status); 395 void upb_status_seterrmsg(upb_status *status, const char *msg); 396 void upb_status_seterrf(upb_status *status, const char *fmt, ...); 397 void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args); 398 void upb_status_copy(upb_status *to, const upb_status *from); 399 400 UPB_END_EXTERN_C 401 402 #ifdef __cplusplus 403 404 class upb::Status { 405 public: 406 Status() { upb_status_clear(this); } 407 408 /* Returns true if there is no error. */ 409 bool ok() const { return upb_ok(this); } 410 411 /* Optional error space and code, useful if the caller wants to 412 * programmatically check the specific kind of error. */ 413 ErrorSpace* error_space() { return upb_status_errspace(this); } 414 int error_code() const { return upb_status_errcode(this); } 415 416 /* The returned string is invalidated by any other call into the status. */ 417 const char *error_message() const { return upb_status_errmsg(this); } 418 419 /* The error message will be truncated if it is longer than 420 * UPB_STATUS_MAX_MESSAGE-4. */ 421 void SetErrorMessage(const char* msg) { upb_status_seterrmsg(this, msg); } 422 void SetFormattedErrorMessage(const char* fmt, ...) { 423 va_list args; 424 va_start(args, fmt); 425 upb_status_vseterrf(this, fmt, args); 426 va_end(args); 427 } 428 429 /* Resets the status to a successful state with no message. */ 430 void Clear() { upb_status_clear(this); } 431 432 void CopyFrom(const Status& other) { upb_status_copy(this, &other); } 433 434 private: 435 UPB_DISALLOW_COPY_AND_ASSIGN(Status) 436 #else 437 struct upb_status { 438 #endif 439 bool ok_; 440 441 /* Specific status code defined by some error space (optional). */ 442 int code_; 443 upb_errorspace *error_space_; 444 445 /* TODO(haberman): add file/line of error? */ 446 447 /* Error message; NULL-terminated. */ 448 char msg[UPB_STATUS_MAX_MESSAGE]; 449 }; 450 451 #define UPB_STATUS_INIT {true, 0, NULL, {0}} 452 453 454 /** Built-in error spaces. ****************************************************/ 455 456 /* Errors raised by upb that we want to be able to detect programmatically. */ 457 typedef enum { 458 UPB_NOMEM /* Can't reuse ENOMEM because it is POSIX, not ISO C. */ 459 } upb_errcode_t; 460 461 extern upb_errorspace upb_upberr; 462 463 void upb_upberr_setoom(upb_status *s); 464 465 /* Since errno is defined by standard C, we define an error space for it in 466 * core upb. Other error spaces should be defined in other, platform-specific 467 * modules. */ 468 469 extern upb_errorspace upb_errnoerr; 470 471 472 /** upb::Allocator ************************************************************/ 473 474 /* A upb::Allocator is a possibly-stateful allocator object. 475 * 476 * It could either be an arena allocator (which doesn't require individual 477 * free() calls) or a regular malloc() (which does). The client must therefore 478 * free memory unless it knows that the allocator is an arena allocator. */ 479 UPB_DECLARE_TYPE(upb::Allocator, upb_alloc) 480 481 /* A malloc()/free() function. 482 * If "size" is 0 then the function acts like free(), otherwise it acts like 483 * realloc(). Only "oldsize" bytes from a previous allocation are preserved. */ 484 typedef void *upb_alloc_func(upb_alloc *alloc, void *ptr, size_t oldsize, 485 size_t size); 486 487 #ifdef __cplusplus 488 489 class upb::Allocator UPB_FINAL { 490 public: 491 Allocator() {} 492 493 private: 494 UPB_DISALLOW_COPY_AND_ASSIGN(Allocator) 495 496 public: 497 #else 498 struct upb_alloc { 499 #endif /* __cplusplus */ 500 upb_alloc_func *func; 501 }; 502 503 UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) { 504 assert(size > 0); 505 return alloc->func(alloc, NULL, 0, size); 506 } 507 508 UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize, 509 size_t size) { 510 assert(size > 0); 511 return alloc->func(alloc, ptr, oldsize, size); 512 } 513 514 UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) { 515 alloc->func(alloc, ptr, 0, 0); 516 } 517 518 /* The global allocator used by upb. Uses the standard malloc()/free(). */ 519 520 extern upb_alloc upb_alloc_global; 521 522 /* Functions that hard-code the global malloc. 523 * 524 * We still get benefit because we can put custom logic into our global 525 * allocator, like injecting out-of-memory faults in debug/testing builds. */ 526 527 UPB_INLINE void *upb_gmalloc(size_t size) { 528 return upb_malloc(&upb_alloc_global, size); 529 } 530 531 UPB_INLINE void *upb_grealloc(void *ptr, size_t oldsize, size_t size) { 532 return upb_realloc(&upb_alloc_global, ptr, oldsize, size); 533 } 534 535 UPB_INLINE void upb_gfree(void *ptr) { 536 upb_free(&upb_alloc_global, ptr); 537 } 538 539 /* upb::Arena *****************************************************************/ 540 541 /* upb::Arena is a specific allocator implementation that uses arena allocation. 542 * The user provides an allocator that will be used to allocate the underlying 543 * arena blocks. Arenas by nature do not require the individual allocations 544 * to be freed. However the Arena does allow users to register cleanup 545 * functions that will run when the arena is destroyed. 546 * 547 * A upb::Arena is *not* thread-safe. 548 * 549 * You could write a thread-safe arena allocator that satisfies the 550 * upb::Allocator interface, but it would not be as efficient for the 551 * single-threaded case. */ 552 UPB_DECLARE_TYPE(upb::Arena, upb_arena) 553 554 typedef void upb_cleanup_func(void *ud); 555 556 #define UPB_ARENA_BLOCK_OVERHEAD (sizeof(size_t)*4) 557 558 UPB_BEGIN_EXTERN_C 559 560 void upb_arena_init(upb_arena *a); 561 void upb_arena_init2(upb_arena *a, void *mem, size_t n, upb_alloc *alloc); 562 void upb_arena_uninit(upb_arena *a); 563 upb_alloc *upb_arena_alloc(upb_arena *a); 564 bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud); 565 size_t upb_arena_bytesallocated(const upb_arena *a); 566 void upb_arena_setnextblocksize(upb_arena *a, size_t size); 567 void upb_arena_setmaxblocksize(upb_arena *a, size_t size); 568 569 UPB_END_EXTERN_C 570 571 #ifdef __cplusplus 572 573 class upb::Arena { 574 public: 575 /* A simple arena with no initial memory block and the default allocator. */ 576 Arena() { upb_arena_init(this); } 577 578 /* Constructs an arena with the given initial block which allocates blocks 579 * with the given allocator. The given allocator must outlive the Arena. 580 * 581 * If you pass NULL for the allocator it will default to the global allocator 582 * upb_alloc_global, and NULL/0 for the initial block will cause there to be 583 * no initial block. */ 584 Arena(void *mem, size_t len, Allocator* a) { 585 upb_arena_init2(this, mem, len, a); 586 } 587 588 ~Arena() { upb_arena_uninit(this); } 589 590 /* Sets the size of the next block the Arena will request (unless the 591 * requested allocation is larger). Each block will double in size until the 592 * max limit is reached. */ 593 void SetNextBlockSize(size_t size) { upb_arena_setnextblocksize(this, size); } 594 595 /* Sets the maximum block size. No blocks larger than this will be requested 596 * from the underlying allocator unless individual arena allocations are 597 * larger. */ 598 void SetMaxBlockSize(size_t size) { upb_arena_setmaxblocksize(this, size); } 599 600 /* Allows this arena to be used as a generic allocator. 601 * 602 * The arena does not need free() calls so when using Arena as an allocator 603 * it is safe to skip them. However they are no-ops so there is no harm in 604 * calling free() either. */ 605 Allocator* allocator() { return upb_arena_alloc(this); } 606 607 /* Add a cleanup function to run when the arena is destroyed. 608 * Returns false on out-of-memory. */ 609 bool AddCleanup(upb_cleanup_func* func, void* ud) { 610 return upb_arena_addcleanup(this, func, ud); 611 } 612 613 /* Total number of bytes that have been allocated. It is undefined what 614 * Realloc() does to this counter. */ 615 size_t BytesAllocated() const { 616 return upb_arena_bytesallocated(this); 617 } 618 619 private: 620 UPB_DISALLOW_COPY_AND_ASSIGN(Arena) 621 622 #else 623 struct upb_arena { 624 #endif /* __cplusplus */ 625 /* We implement the allocator interface. 626 * This must be the first member of upb_arena! */ 627 upb_alloc alloc; 628 629 /* Allocator to allocate arena blocks. We are responsible for freeing these 630 * when we are destroyed. */ 631 upb_alloc *block_alloc; 632 633 size_t bytes_allocated; 634 size_t next_block_size; 635 size_t max_block_size; 636 637 /* Linked list of blocks. Points to an arena_block, defined in env.c */ 638 void *block_head; 639 640 /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */ 641 void *cleanup_head; 642 643 /* For future expansion, since the size of this struct is exposed to users. */ 644 void *future1; 645 void *future2; 646 }; 647 648 649 /* upb::Environment ***********************************************************/ 650 651 /* A upb::Environment provides a means for injecting malloc and an 652 * error-reporting callback into encoders/decoders. This allows them to be 653 * independent of nearly all assumptions about their actual environment. 654 * 655 * It is also a container for allocating the encoders/decoders themselves that 656 * insulates clients from knowing their actual size. This provides ABI 657 * compatibility even if the size of the objects change. And this allows the 658 * structure definitions to be in the .c files instead of the .h files, making 659 * the .h files smaller and more readable. 660 * 661 * We might want to consider renaming this to "Pipeline" if/when the concept of 662 * a pipeline element becomes more formalized. */ 663 UPB_DECLARE_TYPE(upb::Environment, upb_env) 664 665 /* A function that receives an error report from an encoder or decoder. The 666 * callback can return true to request that the error should be recovered, but 667 * if the error is not recoverable this has no effect. */ 668 typedef bool upb_error_func(void *ud, const upb_status *status); 669 670 UPB_BEGIN_EXTERN_C 671 672 void upb_env_init(upb_env *e); 673 void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc); 674 void upb_env_uninit(upb_env *e); 675 676 void upb_env_initonly(upb_env *e); 677 678 upb_arena *upb_env_arena(upb_env *e); 679 bool upb_env_ok(const upb_env *e); 680 void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud); 681 682 /* Convenience wrappers around the methods of the contained arena. */ 683 void upb_env_reporterrorsto(upb_env *e, upb_status *s); 684 bool upb_env_reporterror(upb_env *e, const upb_status *s); 685 void *upb_env_malloc(upb_env *e, size_t size); 686 void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size); 687 void upb_env_free(upb_env *e, void *ptr); 688 bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud); 689 size_t upb_env_bytesallocated(const upb_env *e); 690 691 UPB_END_EXTERN_C 692 693 #ifdef __cplusplus 694 695 class upb::Environment { 696 public: 697 /* The given Arena must outlive this environment. */ 698 Environment() { upb_env_initonly(this); } 699 700 Environment(void *mem, size_t len, Allocator *a) : arena_(mem, len, a) { 701 upb_env_initonly(this); 702 } 703 704 Arena* arena() { return upb_env_arena(this); } 705 706 /* Set a custom error reporting function. */ 707 void SetErrorFunction(upb_error_func* func, void* ud) { 708 upb_env_seterrorfunc(this, func, ud); 709 } 710 711 /* Set the error reporting function to simply copy the status to the given 712 * status and abort. */ 713 void ReportErrorsTo(Status* status) { upb_env_reporterrorsto(this, status); } 714 715 /* Returns true if all allocations and AddCleanup() calls have succeeded, 716 * and no errors were reported with ReportError() (except ones that recovered 717 * successfully). */ 718 bool ok() const { return upb_env_ok(this); } 719 720 /* Reports an error to this environment's callback, returning true if 721 * the caller should try to recover. */ 722 bool ReportError(const Status* status) { 723 return upb_env_reporterror(this, status); 724 } 725 726 private: 727 UPB_DISALLOW_COPY_AND_ASSIGN(Environment) 728 729 #else 730 struct upb_env { 731 #endif /* __cplusplus */ 732 upb_arena arena_; 733 upb_error_func *error_func_; 734 void *error_ud_; 735 bool ok_; 736 }; 737 738 739 /* upb::InlinedArena **********************************************************/ 740 /* upb::InlinedEnvironment ****************************************************/ 741 742 /* upb::InlinedArena and upb::InlinedEnvironment seed their arenas with a 743 * predefined amount of memory. No heap memory will be allocated until the 744 * initial block is exceeded. 745 * 746 * These types only exist in C++ */ 747 748 #ifdef __cplusplus 749 750 template <int N> class upb::InlinedArena : public upb::Arena { 751 public: 752 InlinedArena() : Arena(initial_block_, N, NULL) {} 753 explicit InlinedArena(Allocator* a) : Arena(initial_block_, N, a) {} 754 755 private: 756 UPB_DISALLOW_COPY_AND_ASSIGN(InlinedArena) 757 758 char initial_block_[N + UPB_ARENA_BLOCK_OVERHEAD]; 759 }; 760 761 template <int N> class upb::InlinedEnvironment : public upb::Environment { 762 public: 763 InlinedEnvironment() : Environment(initial_block_, N, NULL) {} 764 explicit InlinedEnvironment(Allocator *a) 765 : Environment(initial_block_, N, a) {} 766 767 private: 768 UPB_DISALLOW_COPY_AND_ASSIGN(InlinedEnvironment) 769 770 char initial_block_[N + UPB_ARENA_BLOCK_OVERHEAD]; 771 }; 772 773 #endif /* __cplusplus */ 774 775 776 777 #endif /* UPB_H_ */ 778 779 #ifdef __cplusplus 780 extern "C" { 781 #endif 782 783 784 /* upb_value ******************************************************************/ 785 786 /* A tagged union (stored untagged inside the table) so that we can check that 787 * clients calling table accessors are correctly typed without having to have 788 * an explosion of accessors. */ 789 typedef enum { 790 UPB_CTYPE_INT32 = 1, 791 UPB_CTYPE_INT64 = 2, 792 UPB_CTYPE_UINT32 = 3, 793 UPB_CTYPE_UINT64 = 4, 794 UPB_CTYPE_BOOL = 5, 795 UPB_CTYPE_CSTR = 6, 796 UPB_CTYPE_PTR = 7, 797 UPB_CTYPE_CONSTPTR = 8, 798 UPB_CTYPE_FPTR = 9 799 } upb_ctype_t; 800 801 typedef struct { 802 uint64_t val; 803 #ifndef NDEBUG 804 /* In debug mode we carry the value type around also so we can check accesses 805 * to be sure the right member is being read. */ 806 upb_ctype_t ctype; 807 #endif 808 } upb_value; 809 810 #ifdef NDEBUG 811 #define SET_TYPE(dest, val) UPB_UNUSED(val) 812 #else 813 #define SET_TYPE(dest, val) dest = val 814 #endif 815 816 /* Like strdup(), which isn't always available since it's not ANSI C. */ 817 char *upb_strdup(const char *s, upb_alloc *a); 818 /* Variant that works with a length-delimited rather than NULL-delimited string, 819 * as supported by strtable. */ 820 char *upb_strdup2(const char *s, size_t len, upb_alloc *a); 821 822 UPB_INLINE char *upb_gstrdup(const char *s) { 823 return upb_strdup(s, &upb_alloc_global); 824 } 825 826 UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val, 827 upb_ctype_t ctype) { 828 v->val = val; 829 SET_TYPE(v->ctype, ctype); 830 } 831 832 UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) { 833 upb_value ret; 834 _upb_value_setval(&ret, val, ctype); 835 return ret; 836 } 837 838 /* For each value ctype, define the following set of functions: 839 * 840 * // Get/set an int32 from a upb_value. 841 * int32_t upb_value_getint32(upb_value val); 842 * void upb_value_setint32(upb_value *val, int32_t cval); 843 * 844 * // Construct a new upb_value from an int32. 845 * upb_value upb_value_int32(int32_t val); */ 846 #define FUNCS(name, membername, type_t, converter, proto_type) \ 847 UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \ 848 val->val = (converter)cval; \ 849 SET_TYPE(val->ctype, proto_type); \ 850 } \ 851 UPB_INLINE upb_value upb_value_ ## name(type_t val) { \ 852 upb_value ret; \ 853 upb_value_set ## name(&ret, val); \ 854 return ret; \ 855 } \ 856 UPB_INLINE type_t upb_value_get ## name(upb_value val) { \ 857 assert(val.ctype == proto_type); \ 858 return (type_t)(converter)val.val; \ 859 } 860 861 FUNCS(int32, int32, int32_t, int32_t, UPB_CTYPE_INT32) 862 FUNCS(int64, int64, int64_t, int64_t, UPB_CTYPE_INT64) 863 FUNCS(uint32, uint32, uint32_t, uint32_t, UPB_CTYPE_UINT32) 864 FUNCS(uint64, uint64, uint64_t, uint64_t, UPB_CTYPE_UINT64) 865 FUNCS(bool, _bool, bool, bool, UPB_CTYPE_BOOL) 866 FUNCS(cstr, cstr, char*, uintptr_t, UPB_CTYPE_CSTR) 867 FUNCS(ptr, ptr, void*, uintptr_t, UPB_CTYPE_PTR) 868 FUNCS(constptr, constptr, const void*, uintptr_t, UPB_CTYPE_CONSTPTR) 869 FUNCS(fptr, fptr, upb_func*, uintptr_t, UPB_CTYPE_FPTR) 870 871 #undef FUNCS 872 #undef SET_TYPE 873 874 875 /* upb_tabkey *****************************************************************/ 876 877 /* Either: 878 * 1. an actual integer key, or 879 * 2. a pointer to a string prefixed by its uint32_t length, owned by us. 880 * 881 * ...depending on whether this is a string table or an int table. We would 882 * make this a union of those two types, but C89 doesn't support statically 883 * initializing a non-first union member. */ 884 typedef uintptr_t upb_tabkey; 885 886 #define UPB_TABKEY_NUM(n) n 887 #define UPB_TABKEY_NONE 0 888 /* The preprocessor isn't quite powerful enough to turn the compile-time string 889 * length into a byte-wise string representation, so code generation needs to 890 * help it along. 891 * 892 * "len1" is the low byte and len4 is the high byte. */ 893 #ifdef UPB_BIG_ENDIAN 894 #define UPB_TABKEY_STR(len1, len2, len3, len4, strval) \ 895 (uintptr_t)(len4 len3 len2 len1 strval) 896 #else 897 #define UPB_TABKEY_STR(len1, len2, len3, len4, strval) \ 898 (uintptr_t)(len1 len2 len3 len4 strval) 899 #endif 900 901 UPB_INLINE char *upb_tabstr(upb_tabkey key, uint32_t *len) { 902 char* mem = (char*)key; 903 if (len) memcpy(len, mem, sizeof(*len)); 904 return mem + sizeof(*len); 905 } 906 907 908 /* upb_tabval *****************************************************************/ 909 910 #ifdef __cplusplus 911 912 /* Status initialization not supported. 913 * 914 * This separate definition is necessary because in C++, UINTPTR_MAX isn't 915 * reliably available. */ 916 typedef struct { 917 uint64_t val; 918 } upb_tabval; 919 920 #else 921 922 /* C -- supports static initialization, but to support static initialization of 923 * both integers and points for both 32 and 64 bit targets, it takes a little 924 * bit of doing. */ 925 926 #if UINTPTR_MAX == 0xffffffffffffffffULL 927 #define UPB_PTR_IS_64BITS 928 #elif UINTPTR_MAX != 0xffffffff 929 #error Could not determine how many bits pointers are. 930 #endif 931 932 typedef union { 933 /* For static initialization. 934 * 935 * Unfortunately this ugliness is necessary -- it is the only way that we can, 936 * with -std=c89 -pedantic, statically initialize this to either a pointer or 937 * an integer on 32-bit platforms. */ 938 struct { 939 #ifdef UPB_PTR_IS_64BITS 940 uintptr_t val; 941 #else 942 uintptr_t val1; 943 uintptr_t val2; 944 #endif 945 } staticinit; 946 947 /* The normal accessor that we use for everything at runtime. */ 948 uint64_t val; 949 } upb_tabval; 950 951 #ifdef UPB_PTR_IS_64BITS 952 #define UPB_TABVALUE_INT_INIT(v) {{v}} 953 #define UPB_TABVALUE_EMPTY_INIT {{-1}} 954 #else 955 956 /* 32-bit pointers */ 957 958 #ifdef UPB_BIG_ENDIAN 959 #define UPB_TABVALUE_INT_INIT(v) {{0, v}} 960 #define UPB_TABVALUE_EMPTY_INIT {{-1, -1}} 961 #else 962 #define UPB_TABVALUE_INT_INIT(v) {{v, 0}} 963 #define UPB_TABVALUE_EMPTY_INIT {{-1, -1}} 964 #endif 965 966 #endif 967 968 #define UPB_TABVALUE_PTR_INIT(v) UPB_TABVALUE_INT_INIT((uintptr_t)v) 969 970 #undef UPB_PTR_IS_64BITS 971 972 #endif /* __cplusplus */ 973 974 975 /* upb_table ******************************************************************/ 976 977 typedef struct _upb_tabent { 978 upb_tabkey key; 979 upb_tabval val; 980 981 /* Internal chaining. This is const so we can create static initializers for 982 * tables. We cast away const sometimes, but *only* when the containing 983 * upb_table is known to be non-const. This requires a bit of care, but 984 * the subtlety is confined to table.c. */ 985 const struct _upb_tabent *next; 986 } upb_tabent; 987 988 typedef struct { 989 size_t count; /* Number of entries in the hash part. */ 990 size_t mask; /* Mask to turn hash value -> bucket. */ 991 upb_ctype_t ctype; /* Type of all values. */ 992 uint8_t size_lg2; /* Size of the hashtable part is 2^size_lg2 entries. */ 993 994 /* Hash table entries. 995 * Making this const isn't entirely accurate; what we really want is for it to 996 * have the same const-ness as the table it's inside. But there's no way to 997 * declare that in C. So we have to make it const so that we can statically 998 * initialize const hash tables. Then we cast away const when we have to. 999 */ 1000 const upb_tabent *entries; 1001 1002 #ifndef NDEBUG 1003 /* This table's allocator. We make the user pass it in to every relevant 1004 * function and only use this to check it in debug mode. We do this solely 1005 * to keep upb_table as small as possible. This might seem slightly paranoid 1006 * but the plan is to use upb_table for all map fields and extension sets in 1007 * a forthcoming message representation, so there could be a lot of these. 1008 * If this turns out to be too annoying later, we can change it (since this 1009 * is an internal-only header file). */ 1010 upb_alloc *alloc; 1011 #endif 1012 } upb_table; 1013 1014 #ifdef NDEBUG 1015 # define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \ 1016 {count, mask, ctype, size_lg2, entries} 1017 #else 1018 # ifdef UPB_DEBUG_REFS 1019 /* At the moment the only mutable tables we statically initialize are debug 1020 * ref tables. */ 1021 # define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \ 1022 {count, mask, ctype, size_lg2, entries, &upb_alloc_debugrefs} 1023 # else 1024 # define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \ 1025 {count, mask, ctype, size_lg2, entries, NULL} 1026 # endif 1027 #endif 1028 1029 typedef struct { 1030 upb_table t; 1031 } upb_strtable; 1032 1033 #define UPB_STRTABLE_INIT(count, mask, ctype, size_lg2, entries) \ 1034 {UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries)} 1035 1036 #define UPB_EMPTY_STRTABLE_INIT(ctype) \ 1037 UPB_STRTABLE_INIT(0, 0, ctype, 0, NULL) 1038 1039 typedef struct { 1040 upb_table t; /* For entries that don't fit in the array part. */ 1041 const upb_tabval *array; /* Array part of the table. See const note above. */ 1042 size_t array_size; /* Array part size. */ 1043 size_t array_count; /* Array part number of elements. */ 1044 } upb_inttable; 1045 1046 #define UPB_INTTABLE_INIT(count, mask, ctype, size_lg2, ent, a, asize, acount) \ 1047 {UPB_TABLE_INIT(count, mask, ctype, size_lg2, ent), a, asize, acount} 1048 1049 #define UPB_EMPTY_INTTABLE_INIT(ctype) \ 1050 UPB_INTTABLE_INIT(0, 0, ctype, 0, NULL, NULL, 0, 0) 1051 1052 #define UPB_ARRAY_EMPTYENT -1 1053 1054 UPB_INLINE size_t upb_table_size(const upb_table *t) { 1055 if (t->size_lg2 == 0) 1056 return 0; 1057 else 1058 return 1 << t->size_lg2; 1059 } 1060 1061 /* Internal-only functions, in .h file only out of necessity. */ 1062 UPB_INLINE bool upb_tabent_isempty(const upb_tabent *e) { 1063 return e->key == 0; 1064 } 1065 1066 /* Used by some of the unit tests for generic hashing functionality. */ 1067 uint32_t MurmurHash2(const void * key, size_t len, uint32_t seed); 1068 1069 UPB_INLINE uintptr_t upb_intkey(uintptr_t key) { 1070 return key; 1071 } 1072 1073 UPB_INLINE uint32_t upb_inthash(uintptr_t key) { 1074 return (uint32_t)key; 1075 } 1076 1077 static const upb_tabent *upb_getentry(const upb_table *t, uint32_t hash) { 1078 return t->entries + (hash & t->mask); 1079 } 1080 1081 UPB_INLINE bool upb_arrhas(upb_tabval key) { 1082 return key.val != (uint64_t)-1; 1083 } 1084 1085 /* Initialize and uninitialize a table, respectively. If memory allocation 1086 * failed, false is returned that the table is uninitialized. */ 1087 bool upb_inttable_init2(upb_inttable *table, upb_ctype_t ctype, upb_alloc *a); 1088 bool upb_strtable_init2(upb_strtable *table, upb_ctype_t ctype, upb_alloc *a); 1089 void upb_inttable_uninit2(upb_inttable *table, upb_alloc *a); 1090 void upb_strtable_uninit2(upb_strtable *table, upb_alloc *a); 1091 1092 UPB_INLINE bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype) { 1093 return upb_inttable_init2(table, ctype, &upb_alloc_global); 1094 } 1095 1096 UPB_INLINE bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype) { 1097 return upb_strtable_init2(table, ctype, &upb_alloc_global); 1098 } 1099 1100 UPB_INLINE void upb_inttable_uninit(upb_inttable *table) { 1101 upb_inttable_uninit2(table, &upb_alloc_global); 1102 } 1103 1104 UPB_INLINE void upb_strtable_uninit(upb_strtable *table) { 1105 upb_strtable_uninit2(table, &upb_alloc_global); 1106 } 1107 1108 /* Returns the number of values in the table. */ 1109 size_t upb_inttable_count(const upb_inttable *t); 1110 UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) { 1111 return t->t.count; 1112 } 1113 1114 /* Inserts the given key into the hashtable with the given value. The key must 1115 * not already exist in the hash table. For string tables, the key must be 1116 * NULL-terminated, and the table will make an internal copy of the key. 1117 * Inttables must not insert a value of UINTPTR_MAX. 1118 * 1119 * If a table resize was required but memory allocation failed, false is 1120 * returned and the table is unchanged. */ 1121 bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val, 1122 upb_alloc *a); 1123 bool upb_strtable_insert3(upb_strtable *t, const char *key, size_t len, 1124 upb_value val, upb_alloc *a); 1125 1126 UPB_INLINE bool upb_inttable_insert(upb_inttable *t, uintptr_t key, 1127 upb_value val) { 1128 return upb_inttable_insert2(t, key, val, &upb_alloc_global); 1129 } 1130 1131 UPB_INLINE bool upb_strtable_insert2(upb_strtable *t, const char *key, 1132 size_t len, upb_value val) { 1133 return upb_strtable_insert3(t, key, len, val, &upb_alloc_global); 1134 } 1135 1136 /* For NULL-terminated strings. */ 1137 UPB_INLINE bool upb_strtable_insert(upb_strtable *t, const char *key, 1138 upb_value val) { 1139 return upb_strtable_insert2(t, key, strlen(key), val); 1140 } 1141 1142 /* Looks up key in this table, returning "true" if the key was found. 1143 * If v is non-NULL, copies the value for this key into *v. */ 1144 bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v); 1145 bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len, 1146 upb_value *v); 1147 1148 /* For NULL-terminated strings. */ 1149 UPB_INLINE bool upb_strtable_lookup(const upb_strtable *t, const char *key, 1150 upb_value *v) { 1151 return upb_strtable_lookup2(t, key, strlen(key), v); 1152 } 1153 1154 /* Removes an item from the table. Returns true if the remove was successful, 1155 * and stores the removed item in *val if non-NULL. */ 1156 bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val); 1157 bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len, 1158 upb_value *val, upb_alloc *alloc); 1159 1160 UPB_INLINE bool upb_strtable_remove2(upb_strtable *t, const char *key, 1161 size_t len, upb_value *val) { 1162 return upb_strtable_remove3(t, key, len, val, &upb_alloc_global); 1163 } 1164 1165 /* For NULL-terminated strings. */ 1166 UPB_INLINE bool upb_strtable_remove(upb_strtable *t, const char *key, 1167 upb_value *v) { 1168 return upb_strtable_remove2(t, key, strlen(key), v); 1169 } 1170 1171 /* Updates an existing entry in an inttable. If the entry does not exist, 1172 * returns false and does nothing. Unlike insert/remove, this does not 1173 * invalidate iterators. */ 1174 bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val); 1175 1176 /* Handy routines for treating an inttable like a stack. May not be mixed with 1177 * other insert/remove calls. */ 1178 bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a); 1179 upb_value upb_inttable_pop(upb_inttable *t); 1180 1181 UPB_INLINE bool upb_inttable_push(upb_inttable *t, upb_value val) { 1182 return upb_inttable_push2(t, val, &upb_alloc_global); 1183 } 1184 1185 /* Convenience routines for inttables with pointer keys. */ 1186 bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val, 1187 upb_alloc *a); 1188 bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val); 1189 bool upb_inttable_lookupptr( 1190 const upb_inttable *t, const void *key, upb_value *val); 1191 1192 UPB_INLINE bool upb_inttable_insertptr(upb_inttable *t, const void *key, 1193 upb_value val) { 1194 return upb_inttable_insertptr2(t, key, val, &upb_alloc_global); 1195 } 1196 1197 /* Optimizes the table for the current set of entries, for both memory use and 1198 * lookup time. Client should call this after all entries have been inserted; 1199 * inserting more entries is legal, but will likely require a table resize. */ 1200 void upb_inttable_compact2(upb_inttable *t, upb_alloc *a); 1201 1202 UPB_INLINE void upb_inttable_compact(upb_inttable *t) { 1203 upb_inttable_compact2(t, &upb_alloc_global); 1204 } 1205 1206 /* A special-case inlinable version of the lookup routine for 32-bit 1207 * integers. */ 1208 UPB_INLINE bool upb_inttable_lookup32(const upb_inttable *t, uint32_t key, 1209 upb_value *v) { 1210 *v = upb_value_int32(0); /* Silence compiler warnings. */ 1211 if (key < t->array_size) { 1212 upb_tabval arrval = t->array[key]; 1213 if (upb_arrhas(arrval)) { 1214 _upb_value_setval(v, arrval.val, t->t.ctype); 1215 return true; 1216 } else { 1217 return false; 1218 } 1219 } else { 1220 const upb_tabent *e; 1221 if (t->t.entries == NULL) return false; 1222 for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) { 1223 if ((uint32_t)e->key == key) { 1224 _upb_value_setval(v, e->val.val, t->t.ctype); 1225 return true; 1226 } 1227 if (e->next == NULL) return false; 1228 } 1229 } 1230 } 1231 1232 /* Exposed for testing only. */ 1233 bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a); 1234 1235 /* Iterators ******************************************************************/ 1236 1237 /* Iterators for int and string tables. We are subject to some kind of unusual 1238 * design constraints: 1239 * 1240 * For high-level languages: 1241 * - we must be able to guarantee that we don't crash or corrupt memory even if 1242 * the program accesses an invalidated iterator. 1243 * 1244 * For C++11 range-based for: 1245 * - iterators must be copyable 1246 * - iterators must be comparable 1247 * - it must be possible to construct an "end" value. 1248 * 1249 * Iteration order is undefined. 1250 * 1251 * Modifying the table invalidates iterators. upb_{str,int}table_done() is 1252 * guaranteed to work even on an invalidated iterator, as long as the table it 1253 * is iterating over has not been freed. Calling next() or accessing data from 1254 * an invalidated iterator yields unspecified elements from the table, but it is 1255 * guaranteed not to crash and to return real table elements (except when done() 1256 * is true). */ 1257 1258 1259 /* upb_strtable_iter **********************************************************/ 1260 1261 /* upb_strtable_iter i; 1262 * upb_strtable_begin(&i, t); 1263 * for(; !upb_strtable_done(&i); upb_strtable_next(&i)) { 1264 * const char *key = upb_strtable_iter_key(&i); 1265 * const upb_value val = upb_strtable_iter_value(&i); 1266 * // ... 1267 * } 1268 */ 1269 1270 typedef struct { 1271 const upb_strtable *t; 1272 size_t index; 1273 } upb_strtable_iter; 1274 1275 void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t); 1276 void upb_strtable_next(upb_strtable_iter *i); 1277 bool upb_strtable_done(const upb_strtable_iter *i); 1278 const char *upb_strtable_iter_key(const upb_strtable_iter *i); 1279 size_t upb_strtable_iter_keylength(const upb_strtable_iter *i); 1280 upb_value upb_strtable_iter_value(const upb_strtable_iter *i); 1281 void upb_strtable_iter_setdone(upb_strtable_iter *i); 1282 bool upb_strtable_iter_isequal(const upb_strtable_iter *i1, 1283 const upb_strtable_iter *i2); 1284 1285 1286 /* upb_inttable_iter **********************************************************/ 1287 1288 /* upb_inttable_iter i; 1289 * upb_inttable_begin(&i, t); 1290 * for(; !upb_inttable_done(&i); upb_inttable_next(&i)) { 1291 * uintptr_t key = upb_inttable_iter_key(&i); 1292 * upb_value val = upb_inttable_iter_value(&i); 1293 * // ... 1294 * } 1295 */ 1296 1297 typedef struct { 1298 const upb_inttable *t; 1299 size_t index; 1300 bool array_part; 1301 } upb_inttable_iter; 1302 1303 void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t); 1304 void upb_inttable_next(upb_inttable_iter *i); 1305 bool upb_inttable_done(const upb_inttable_iter *i); 1306 uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i); 1307 upb_value upb_inttable_iter_value(const upb_inttable_iter *i); 1308 void upb_inttable_iter_setdone(upb_inttable_iter *i); 1309 bool upb_inttable_iter_isequal(const upb_inttable_iter *i1, 1310 const upb_inttable_iter *i2); 1311 1312 1313 #ifdef __cplusplus 1314 } /* extern "C" */ 1315 #endif 1316 1317 #endif /* UPB_TABLE_H_ */ 1318 1319 /* Reference tracking will check ref()/unref() operations to make sure the 1320 * ref ownership is correct. Where possible it will also make tools like 1321 * Valgrind attribute ref leaks to the code that took the leaked ref, not 1322 * the code that originally created the object. 1323 * 1324 * Enabling this requires the application to define upb_lock()/upb_unlock() 1325 * functions that acquire/release a global mutex (or #define UPB_THREAD_UNSAFE). 1326 * For this reason we don't enable it by default, even in debug builds. 1327 */ 1328 1329 /* #define UPB_DEBUG_REFS */ 1330 1331 #ifdef __cplusplus 1332 namespace upb { 1333 class RefCounted; 1334 template <class T> class reffed_ptr; 1335 } 1336 #endif 1337 1338 UPB_DECLARE_TYPE(upb::RefCounted, upb_refcounted) 1339 1340 struct upb_refcounted_vtbl; 1341 1342 #ifdef __cplusplus 1343 1344 class upb::RefCounted { 1345 public: 1346 /* Returns true if the given object is frozen. */ 1347 bool IsFrozen() const; 1348 1349 /* Increases the ref count, the new ref is owned by "owner" which must not 1350 * already own a ref (and should not itself be a refcounted object if the ref 1351 * could possibly be circular; see below). 1352 * Thread-safe iff "this" is frozen. */ 1353 void Ref(const void *owner) const; 1354 1355 /* Release a ref that was acquired from upb_refcounted_ref() and collects any 1356 * objects it can. */ 1357 void Unref(const void *owner) const; 1358 1359 /* Moves an existing ref from "from" to "to", without changing the overall 1360 * ref count. DonateRef(foo, NULL, owner) is the same as Ref(foo, owner), 1361 * but "to" may not be NULL. */ 1362 void DonateRef(const void *from, const void *to) const; 1363 1364 /* Verifies that a ref to the given object is currently held by the given 1365 * owner. Only effective in UPB_DEBUG_REFS builds. */ 1366 void CheckRef(const void *owner) const; 1367 1368 private: 1369 UPB_DISALLOW_POD_OPS(RefCounted, upb::RefCounted) 1370 #else 1371 struct upb_refcounted { 1372 #endif 1373 /* TODO(haberman): move the actual structure definition to structdefs.int.h. 1374 * The only reason they are here is because inline functions need to see the 1375 * definition of upb_handlers, which needs to see this definition. But we 1376 * can change the upb_handlers inline functions to deal in raw offsets 1377 * instead. 1378 */ 1379 1380 /* A single reference count shared by all objects in the group. */ 1381 uint32_t *group; 1382 1383 /* A singly-linked list of all objects in the group. */ 1384 upb_refcounted *next; 1385 1386 /* Table of function pointers for this type. */ 1387 const struct upb_refcounted_vtbl *vtbl; 1388 1389 /* Maintained only when mutable, this tracks the number of refs (but not 1390 * ref2's) to this object. *group should be the sum of all individual_count 1391 * in the group. */ 1392 uint32_t individual_count; 1393 1394 bool is_frozen; 1395 1396 #ifdef UPB_DEBUG_REFS 1397 upb_inttable *refs; /* Maps owner -> trackedref for incoming refs. */ 1398 upb_inttable *ref2s; /* Set of targets for outgoing ref2s. */ 1399 #endif 1400 }; 1401 1402 #ifdef UPB_DEBUG_REFS 1403 extern upb_alloc upb_alloc_debugrefs; 1404 #define UPB_REFCOUNT_INIT(vtbl, refs, ref2s) \ 1405 {&static_refcount, NULL, vtbl, 0, true, refs, ref2s} 1406 #else 1407 #define UPB_REFCOUNT_INIT(vtbl, refs, ref2s) \ 1408 {&static_refcount, NULL, vtbl, 0, true} 1409 #endif 1410 1411 UPB_BEGIN_EXTERN_C 1412 1413 /* It is better to use tracked refs when possible, for the extra debugging 1414 * capability. But if this is not possible (because you don't have easy access 1415 * to a stable pointer value that is associated with the ref), you can pass 1416 * UPB_UNTRACKED_REF instead. */ 1417 extern const void *UPB_UNTRACKED_REF; 1418 1419 /* Native C API. */ 1420 bool upb_refcounted_isfrozen(const upb_refcounted *r); 1421 void upb_refcounted_ref(const upb_refcounted *r, const void *owner); 1422 void upb_refcounted_unref(const upb_refcounted *r, const void *owner); 1423 void upb_refcounted_donateref( 1424 const upb_refcounted *r, const void *from, const void *to); 1425 void upb_refcounted_checkref(const upb_refcounted *r, const void *owner); 1426 1427 #define UPB_REFCOUNTED_CMETHODS(type, upcastfunc) \ 1428 UPB_INLINE bool type ## _isfrozen(const type *v) { \ 1429 return upb_refcounted_isfrozen(upcastfunc(v)); \ 1430 } \ 1431 UPB_INLINE void type ## _ref(const type *v, const void *owner) { \ 1432 upb_refcounted_ref(upcastfunc(v), owner); \ 1433 } \ 1434 UPB_INLINE void type ## _unref(const type *v, const void *owner) { \ 1435 upb_refcounted_unref(upcastfunc(v), owner); \ 1436 } \ 1437 UPB_INLINE void type ## _donateref(const type *v, const void *from, const void *to) { \ 1438 upb_refcounted_donateref(upcastfunc(v), from, to); \ 1439 } \ 1440 UPB_INLINE void type ## _checkref(const type *v, const void *owner) { \ 1441 upb_refcounted_checkref(upcastfunc(v), owner); \ 1442 } 1443 1444 #define UPB_REFCOUNTED_CPPMETHODS \ 1445 bool IsFrozen() const { \ 1446 return upb::upcast_to<const upb::RefCounted>(this)->IsFrozen(); \ 1447 } \ 1448 void Ref(const void *owner) const { \ 1449 return upb::upcast_to<const upb::RefCounted>(this)->Ref(owner); \ 1450 } \ 1451 void Unref(const void *owner) const { \ 1452 return upb::upcast_to<const upb::RefCounted>(this)->Unref(owner); \ 1453 } \ 1454 void DonateRef(const void *from, const void *to) const { \ 1455 return upb::upcast_to<const upb::RefCounted>(this)->DonateRef(from, to); \ 1456 } \ 1457 void CheckRef(const void *owner) const { \ 1458 return upb::upcast_to<const upb::RefCounted>(this)->CheckRef(owner); \ 1459 } 1460 1461 /* Internal-to-upb Interface **************************************************/ 1462 1463 typedef void upb_refcounted_visit(const upb_refcounted *r, 1464 const upb_refcounted *subobj, 1465 void *closure); 1466 1467 struct upb_refcounted_vtbl { 1468 /* Must visit all subobjects that are currently ref'd via upb_refcounted_ref2. 1469 * Must be longjmp()-safe. */ 1470 void (*visit)(const upb_refcounted *r, upb_refcounted_visit *visit, void *c); 1471 1472 /* Must free the object and release all references to other objects. */ 1473 void (*free)(upb_refcounted *r); 1474 }; 1475 1476 /* Initializes the refcounted with a single ref for the given owner. Returns 1477 * false if memory could not be allocated. */ 1478 bool upb_refcounted_init(upb_refcounted *r, 1479 const struct upb_refcounted_vtbl *vtbl, 1480 const void *owner); 1481 1482 /* Adds a ref from one refcounted object to another ("from" must not already 1483 * own a ref). These refs may be circular; cycles will be collected correctly 1484 * (if conservatively). These refs do not need to be freed in from's free() 1485 * function. */ 1486 void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from); 1487 1488 /* Removes a ref that was acquired from upb_refcounted_ref2(), and collects any 1489 * object it can. This is only necessary when "from" no longer points to "r", 1490 * and not from from's "free" function. */ 1491 void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from); 1492 1493 #define upb_ref2(r, from) \ 1494 upb_refcounted_ref2((const upb_refcounted*)r, (upb_refcounted*)from) 1495 #define upb_unref2(r, from) \ 1496 upb_refcounted_unref2((const upb_refcounted*)r, (upb_refcounted*)from) 1497 1498 /* Freezes all mutable object reachable by ref2() refs from the given roots. 1499 * This will split refcounting groups into precise SCC groups, so that 1500 * refcounting of frozen objects can be more aggressive. If memory allocation 1501 * fails, or if more than 2**31 mutable objects are reachable from "roots", or 1502 * if the maximum depth of the graph exceeds "maxdepth", false is returned and 1503 * the objects are unchanged. 1504 * 1505 * After this operation succeeds, the objects are frozen/const, and may not be 1506 * used through non-const pointers. In particular, they may not be passed as 1507 * the second parameter of upb_refcounted_{ref,unref}2(). On the upside, all 1508 * operations on frozen refcounteds are threadsafe, and objects will be freed 1509 * at the precise moment that they become unreachable. 1510 * 1511 * Caller must own refs on each object in the "roots" list. */ 1512 bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s, 1513 int maxdepth); 1514 1515 /* Shared by all compiled-in refcounted objects. */ 1516 extern uint32_t static_refcount; 1517 1518 UPB_END_EXTERN_C 1519 1520 #ifdef __cplusplus 1521 /* C++ Wrappers. */ 1522 namespace upb { 1523 inline bool RefCounted::IsFrozen() const { 1524 return upb_refcounted_isfrozen(this); 1525 } 1526 inline void RefCounted::Ref(const void *owner) const { 1527 upb_refcounted_ref(this, owner); 1528 } 1529 inline void RefCounted::Unref(const void *owner) const { 1530 upb_refcounted_unref(this, owner); 1531 } 1532 inline void RefCounted::DonateRef(const void *from, const void *to) const { 1533 upb_refcounted_donateref(this, from, to); 1534 } 1535 inline void RefCounted::CheckRef(const void *owner) const { 1536 upb_refcounted_checkref(this, owner); 1537 } 1538 } /* namespace upb */ 1539 #endif 1540 1541 1542 /* upb::reffed_ptr ************************************************************/ 1543 1544 #ifdef __cplusplus 1545 1546 #include <algorithm> /* For std::swap(). */ 1547 1548 /* Provides RAII semantics for upb refcounted objects. Each reffed_ptr owns a 1549 * ref on whatever object it points to (if any). */ 1550 template <class T> class upb::reffed_ptr { 1551 public: 1552 reffed_ptr() : ptr_(NULL) {} 1553 1554 /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */ 1555 template <class U> 1556 reffed_ptr(U* val, const void* ref_donor = NULL) 1557 : ptr_(upb::upcast(val)) { 1558 if (ref_donor) { 1559 assert(ptr_); 1560 ptr_->DonateRef(ref_donor, this); 1561 } else if (ptr_) { 1562 ptr_->Ref(this); 1563 } 1564 } 1565 1566 template <class U> 1567 reffed_ptr(const reffed_ptr<U>& other) 1568 : ptr_(upb::upcast(other.get())) { 1569 if (ptr_) ptr_->Ref(this); 1570 } 1571 1572 reffed_ptr(const reffed_ptr& other) 1573 : ptr_(upb::upcast(other.get())) { 1574 if (ptr_) ptr_->Ref(this); 1575 } 1576 1577 ~reffed_ptr() { if (ptr_) ptr_->Unref(this); } 1578 1579 template <class U> 1580 reffed_ptr& operator=(const reffed_ptr<U>& other) { 1581 reset(other.get()); 1582 return *this; 1583 } 1584 1585 reffed_ptr& operator=(const reffed_ptr& other) { 1586 reset(other.get()); 1587 return *this; 1588 } 1589 1590 /* TODO(haberman): add C++11 move construction/assignment for greater 1591 * efficiency. */ 1592 1593 void swap(reffed_ptr& other) { 1594 if (ptr_ == other.ptr_) { 1595 return; 1596 } 1597 1598 if (ptr_) ptr_->DonateRef(this, &other); 1599 if (other.ptr_) other.ptr_->DonateRef(&other, this); 1600 std::swap(ptr_, other.ptr_); 1601 } 1602 1603 T& operator*() const { 1604 assert(ptr_); 1605 return *ptr_; 1606 } 1607 1608 T* operator->() const { 1609 assert(ptr_); 1610 return ptr_; 1611 } 1612 1613 T* get() const { return ptr_; } 1614 1615 /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */ 1616 template <class U> 1617 void reset(U* ptr = NULL, const void* ref_donor = NULL) { 1618 reffed_ptr(ptr, ref_donor).swap(*this); 1619 } 1620 1621 template <class U> 1622 reffed_ptr<U> down_cast() { 1623 return reffed_ptr<U>(upb::down_cast<U*>(get())); 1624 } 1625 1626 template <class U> 1627 reffed_ptr<U> dyn_cast() { 1628 return reffed_ptr<U>(upb::dyn_cast<U*>(get())); 1629 } 1630 1631 /* Plain release() is unsafe; if we were the only owner, it would leak the 1632 * object. Instead we provide this: */ 1633 T* ReleaseTo(const void* new_owner) { 1634 T* ret = NULL; 1635 ptr_->DonateRef(this, new_owner); 1636 std::swap(ret, ptr_); 1637 return ret; 1638 } 1639 1640 private: 1641 T* ptr_; 1642 }; 1643 1644 #endif /* __cplusplus */ 1645 1646 #endif /* UPB_REFCOUNT_H_ */ 1647 1648 #ifdef __cplusplus 1649 #include <cstring> 1650 #include <string> 1651 #include <vector> 1652 1653 namespace upb { 1654 class Def; 1655 class EnumDef; 1656 class FieldDef; 1657 class FileDef; 1658 class MessageDef; 1659 class OneofDef; 1660 } 1661 #endif 1662 1663 UPB_DECLARE_DERIVED_TYPE(upb::Def, upb::RefCounted, upb_def, upb_refcounted) 1664 UPB_DECLARE_DERIVED_TYPE(upb::OneofDef, upb::RefCounted, upb_oneofdef, 1665 upb_refcounted) 1666 UPB_DECLARE_DERIVED_TYPE(upb::FileDef, upb::RefCounted, upb_filedef, 1667 upb_refcounted) 1668 1669 /* The maximum message depth that the type graph can have. This is a resource 1670 * limit for the C stack since we sometimes need to recursively traverse the 1671 * graph. Cycles are ok; the traversal will stop when it detects a cycle, but 1672 * we must hit the cycle before the maximum depth is reached. 1673 * 1674 * If having a single static limit is too inflexible, we can add another variant 1675 * of Def::Freeze that allows specifying this as a parameter. */ 1676 #define UPB_MAX_MESSAGE_DEPTH 64 1677 1678 1679 /* upb::Def: base class for top-level defs ***********************************/ 1680 1681 /* All the different kind of defs that can be defined at the top-level and put 1682 * in a SymbolTable or appear in a FileDef::defs() list. This excludes some 1683 * defs (like oneofs and files). It only includes fields because they can be 1684 * defined as extensions. */ 1685 typedef enum { 1686 UPB_DEF_MSG, 1687 UPB_DEF_FIELD, 1688 UPB_DEF_ENUM, 1689 UPB_DEF_SERVICE, /* Not yet implemented. */ 1690 UPB_DEF_ANY = -1 /* Wildcard for upb_symtab_get*() */ 1691 } upb_deftype_t; 1692 1693 #ifdef __cplusplus 1694 1695 /* The base class of all defs. Its base is upb::RefCounted (use upb::upcast() 1696 * to convert). */ 1697 class upb::Def { 1698 public: 1699 typedef upb_deftype_t Type; 1700 1701 Def* Dup(const void *owner) const; 1702 1703 /* upb::RefCounted methods like Ref()/Unref(). */ 1704 UPB_REFCOUNTED_CPPMETHODS 1705 1706 Type def_type() const; 1707 1708 /* "fullname" is the def's fully-qualified name (eg. foo.bar.Message). */ 1709 const char *full_name() const; 1710 1711 /* The final part of a def's name (eg. Message). */ 1712 const char *name() const; 1713 1714 /* The def must be mutable. Caller retains ownership of fullname. Defs are 1715 * not required to have a name; if a def has no name when it is frozen, it 1716 * will remain an anonymous def. On failure, returns false and details in "s" 1717 * if non-NULL. */ 1718 bool set_full_name(const char* fullname, upb::Status* s); 1719 bool set_full_name(const std::string &fullname, upb::Status* s); 1720 1721 /* The file in which this def appears. It is not necessary to add a def to a 1722 * file (and consequently the accessor may return NULL). Set this by calling 1723 * file->Add(def). */ 1724 FileDef* file() const; 1725 1726 /* Freezes the given defs; this validates all constraints and marks the defs 1727 * as frozen (read-only). "defs" may not contain any fielddefs, but fields 1728 * of any msgdefs will be frozen. 1729 * 1730 * Symbolic references to sub-types and enum defaults must have already been 1731 * resolved. Any mutable defs reachable from any of "defs" must also be in 1732 * the list; more formally, "defs" must be a transitive closure of mutable 1733 * defs. 1734 * 1735 * After this operation succeeds, the finalized defs must only be accessed 1736 * through a const pointer! */ 1737 static bool Freeze(Def* const* defs, size_t n, Status* status); 1738 static bool Freeze(const std::vector<Def*>& defs, Status* status); 1739 1740 private: 1741 UPB_DISALLOW_POD_OPS(Def, upb::Def) 1742 }; 1743 1744 #endif /* __cplusplus */ 1745 1746 UPB_BEGIN_EXTERN_C 1747 1748 /* Native C API. */ 1749 upb_def *upb_def_dup(const upb_def *def, const void *owner); 1750 1751 /* Include upb_refcounted methods like upb_def_ref()/upb_def_unref(). */ 1752 UPB_REFCOUNTED_CMETHODS(upb_def, upb_def_upcast) 1753 1754 upb_deftype_t upb_def_type(const upb_def *d); 1755 const char *upb_def_fullname(const upb_def *d); 1756 const char *upb_def_name(const upb_def *d); 1757 const upb_filedef *upb_def_file(const upb_def *d); 1758 bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s); 1759 bool upb_def_freeze(upb_def *const *defs, size_t n, upb_status *s); 1760 1761 /* Temporary API: for internal use only. */ 1762 bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s); 1763 1764 UPB_END_EXTERN_C 1765 1766 1767 /* upb::Def casts *************************************************************/ 1768 1769 #ifdef __cplusplus 1770 #define UPB_CPP_CASTS(cname, cpptype) \ 1771 namespace upb { \ 1772 template <> \ 1773 inline cpptype *down_cast<cpptype *, Def>(Def * def) { \ 1774 return upb_downcast_##cname##_mutable(def); \ 1775 } \ 1776 template <> \ 1777 inline cpptype *dyn_cast<cpptype *, Def>(Def * def) { \ 1778 return upb_dyncast_##cname##_mutable(def); \ 1779 } \ 1780 template <> \ 1781 inline const cpptype *down_cast<const cpptype *, const Def>( \ 1782 const Def *def) { \ 1783 return upb_downcast_##cname(def); \ 1784 } \ 1785 template <> \ 1786 inline const cpptype *dyn_cast<const cpptype *, const Def>(const Def *def) { \ 1787 return upb_dyncast_##cname(def); \ 1788 } \ 1789 template <> \ 1790 inline const cpptype *down_cast<const cpptype *, Def>(Def * def) { \ 1791 return upb_downcast_##cname(def); \ 1792 } \ 1793 template <> \ 1794 inline const cpptype *dyn_cast<const cpptype *, Def>(Def * def) { \ 1795 return upb_dyncast_##cname(def); \ 1796 } \ 1797 } /* namespace upb */ 1798 #else 1799 #define UPB_CPP_CASTS(cname, cpptype) 1800 #endif /* __cplusplus */ 1801 1802 /* Dynamic casts, for determining if a def is of a particular type at runtime. 1803 * Downcasts, for when some wants to assert that a def is of a particular type. 1804 * These are only checked if we are building debug. */ 1805 #define UPB_DEF_CASTS(lower, upper, cpptype) \ 1806 UPB_INLINE const upb_##lower *upb_dyncast_##lower(const upb_def *def) { \ 1807 if (upb_def_type(def) != UPB_DEF_##upper) return NULL; \ 1808 return (upb_##lower *)def; \ 1809 } \ 1810 UPB_INLINE const upb_##lower *upb_downcast_##lower(const upb_def *def) { \ 1811 assert(upb_def_type(def) == UPB_DEF_##upper); \ 1812 return (const upb_##lower *)def; \ 1813 } \ 1814 UPB_INLINE upb_##lower *upb_dyncast_##lower##_mutable(upb_def *def) { \ 1815 return (upb_##lower *)upb_dyncast_##lower(def); \ 1816 } \ 1817 UPB_INLINE upb_##lower *upb_downcast_##lower##_mutable(upb_def *def) { \ 1818 return (upb_##lower *)upb_downcast_##lower(def); \ 1819 } \ 1820 UPB_CPP_CASTS(lower, cpptype) 1821 1822 #define UPB_DEFINE_DEF(cppname, lower, upper, cppmethods, members) \ 1823 UPB_DEFINE_CLASS2(cppname, upb::Def, upb::RefCounted, cppmethods, \ 1824 members) \ 1825 UPB_DEF_CASTS(lower, upper, cppname) 1826 1827 #define UPB_DECLARE_DEF_TYPE(cppname, lower, upper) \ 1828 UPB_DECLARE_DERIVED_TYPE2(cppname, upb::Def, upb::RefCounted, \ 1829 upb_ ## lower, upb_def, upb_refcounted) \ 1830 UPB_DEF_CASTS(lower, upper, cppname) 1831 1832 UPB_DECLARE_DEF_TYPE(upb::FieldDef, fielddef, FIELD) 1833 UPB_DECLARE_DEF_TYPE(upb::MessageDef, msgdef, MSG) 1834 UPB_DECLARE_DEF_TYPE(upb::EnumDef, enumdef, ENUM) 1835 1836 #undef UPB_DECLARE_DEF_TYPE 1837 #undef UPB_DEF_CASTS 1838 #undef UPB_CPP_CASTS 1839 1840 1841 /* upb::FieldDef **************************************************************/ 1842 1843 /* The types a field can have. Note that this list is not identical to the 1844 * types defined in descriptor.proto, which gives INT32 and SINT32 separate 1845 * types (we distinguish the two with the "integer encoding" enum below). */ 1846 typedef enum { 1847 UPB_TYPE_FLOAT = 1, 1848 UPB_TYPE_DOUBLE = 2, 1849 UPB_TYPE_BOOL = 3, 1850 UPB_TYPE_STRING = 4, 1851 UPB_TYPE_BYTES = 5, 1852 UPB_TYPE_MESSAGE = 6, 1853 UPB_TYPE_ENUM = 7, /* Enum values are int32. */ 1854 UPB_TYPE_INT32 = 8, 1855 UPB_TYPE_UINT32 = 9, 1856 UPB_TYPE_INT64 = 10, 1857 UPB_TYPE_UINT64 = 11 1858 } upb_fieldtype_t; 1859 1860 /* The repeated-ness of each field; this matches descriptor.proto. */ 1861 typedef enum { 1862 UPB_LABEL_OPTIONAL = 1, 1863 UPB_LABEL_REQUIRED = 2, 1864 UPB_LABEL_REPEATED = 3 1865 } upb_label_t; 1866 1867 /* How integers should be encoded in serializations that offer multiple 1868 * integer encoding methods. */ 1869 typedef enum { 1870 UPB_INTFMT_VARIABLE = 1, 1871 UPB_INTFMT_FIXED = 2, 1872 UPB_INTFMT_ZIGZAG = 3 /* Only for signed types (INT32/INT64). */ 1873 } upb_intfmt_t; 1874 1875 /* Descriptor types, as defined in descriptor.proto. */ 1876 typedef enum { 1877 UPB_DESCRIPTOR_TYPE_DOUBLE = 1, 1878 UPB_DESCRIPTOR_TYPE_FLOAT = 2, 1879 UPB_DESCRIPTOR_TYPE_INT64 = 3, 1880 UPB_DESCRIPTOR_TYPE_UINT64 = 4, 1881 UPB_DESCRIPTOR_TYPE_INT32 = 5, 1882 UPB_DESCRIPTOR_TYPE_FIXED64 = 6, 1883 UPB_DESCRIPTOR_TYPE_FIXED32 = 7, 1884 UPB_DESCRIPTOR_TYPE_BOOL = 8, 1885 UPB_DESCRIPTOR_TYPE_STRING = 9, 1886 UPB_DESCRIPTOR_TYPE_GROUP = 10, 1887 UPB_DESCRIPTOR_TYPE_MESSAGE = 11, 1888 UPB_DESCRIPTOR_TYPE_BYTES = 12, 1889 UPB_DESCRIPTOR_TYPE_UINT32 = 13, 1890 UPB_DESCRIPTOR_TYPE_ENUM = 14, 1891 UPB_DESCRIPTOR_TYPE_SFIXED32 = 15, 1892 UPB_DESCRIPTOR_TYPE_SFIXED64 = 16, 1893 UPB_DESCRIPTOR_TYPE_SINT32 = 17, 1894 UPB_DESCRIPTOR_TYPE_SINT64 = 18 1895 } upb_descriptortype_t; 1896 1897 typedef enum { 1898 UPB_SYNTAX_PROTO2 = 2, 1899 UPB_SYNTAX_PROTO3 = 3 1900 } upb_syntax_t; 1901 1902 /* Maximum field number allowed for FieldDefs. This is an inherent limit of the 1903 * protobuf wire format. */ 1904 #define UPB_MAX_FIELDNUMBER ((1 << 29) - 1) 1905 1906 #ifdef __cplusplus 1907 1908 /* A upb_fielddef describes a single field in a message. It is most often 1909 * found as a part of a upb_msgdef, but can also stand alone to represent 1910 * an extension. 1911 * 1912 * Its base class is upb::Def (use upb::upcast() to convert). */ 1913 class upb::FieldDef { 1914 public: 1915 typedef upb_fieldtype_t Type; 1916 typedef upb_label_t Label; 1917 typedef upb_intfmt_t IntegerFormat; 1918 typedef upb_descriptortype_t DescriptorType; 1919 1920 /* These return true if the given value is a valid member of the enumeration. */ 1921 static bool CheckType(int32_t val); 1922 static bool CheckLabel(int32_t val); 1923 static bool CheckDescriptorType(int32_t val); 1924 static bool CheckIntegerFormat(int32_t val); 1925 1926 /* These convert to the given enumeration; they require that the value is 1927 * valid. */ 1928 static Type ConvertType(int32_t val); 1929 static Label ConvertLabel(int32_t val); 1930 static DescriptorType ConvertDescriptorType(int32_t val); 1931 static IntegerFormat ConvertIntegerFormat(int32_t val); 1932 1933 /* Returns NULL if memory allocation failed. */ 1934 static reffed_ptr<FieldDef> New(); 1935 1936 /* Duplicates the given field, returning NULL if memory allocation failed. 1937 * When a fielddef is duplicated, the subdef (if any) is made symbolic if it 1938 * wasn't already. If the subdef is set but has no name (which is possible 1939 * since msgdefs are not required to have a name) the new fielddef's subdef 1940 * will be unset. */ 1941 FieldDef* Dup(const void* owner) const; 1942 1943 /* upb::RefCounted methods like Ref()/Unref(). */ 1944 UPB_REFCOUNTED_CPPMETHODS 1945 1946 /* Functionality from upb::Def. */ 1947 const char* full_name() const; 1948 1949 bool type_is_set() const; /* set_[descriptor_]type() has been called? */ 1950 Type type() const; /* Requires that type_is_set() == true. */ 1951 Label label() const; /* Defaults to UPB_LABEL_OPTIONAL. */ 1952 const char* name() const; /* NULL if uninitialized. */ 1953 uint32_t number() const; /* Returns 0 if uninitialized. */ 1954 bool is_extension() const; 1955 1956 /* Copies the JSON name for this field into the given buffer. Returns the 1957 * actual size of the JSON name, including the NULL terminator. If the 1958 * return value is 0, the JSON name is unset. If the return value is 1959 * greater than len, the JSON name was truncated. The buffer is always 1960 * NULL-terminated if len > 0. 1961 * 1962 * The JSON name always defaults to a camelCased version of the regular 1963 * name. However if the regular name is unset, the JSON name will be unset 1964 * also. 1965 */ 1966 size_t GetJsonName(char* buf, size_t len) const; 1967 1968 /* Convenience version of the above function which copies the JSON name 1969 * into the given string, returning false if the name is not set. */ 1970 template <class T> 1971 bool GetJsonName(T* str) { 1972 str->resize(GetJsonName(NULL, 0)); 1973 GetJsonName(&(*str)[0], str->size()); 1974 return str->size() > 0; 1975 } 1976 1977 /* For UPB_TYPE_MESSAGE fields only where is_tag_delimited() == false, 1978 * indicates whether this field should have lazy parsing handlers that yield 1979 * the unparsed string for the submessage. 1980 * 1981 * TODO(haberman): I think we want to move this into a FieldOptions container 1982 * when we add support for custom options (the FieldOptions struct will 1983 * contain both regular FieldOptions like "lazy" *and* custom options). */ 1984 bool lazy() const; 1985 1986 /* For non-string, non-submessage fields, this indicates whether binary 1987 * protobufs are encoded in packed or non-packed format. 1988 * 1989 * TODO(haberman): see note above about putting options like this into a 1990 * FieldOptions container. */ 1991 bool packed() const; 1992 1993 /* An integer that can be used as an index into an array of fields for 1994 * whatever message this field belongs to. Guaranteed to be less than 1995 * f->containing_type()->field_count(). May only be accessed once the def has 1996 * been finalized. */ 1997 uint32_t index() const; 1998 1999 /* The MessageDef to which this field belongs. 2000 * 2001 * If this field has been added to a MessageDef, that message can be retrieved 2002 * directly (this is always the case for frozen FieldDefs). 2003 * 2004 * If the field has not yet been added to a MessageDef, you can set the name 2005 * of the containing type symbolically instead. This is mostly useful for 2006 * extensions, where the extension is declared separately from the message. */ 2007 const MessageDef* containing_type() const; 2008 const char* containing_type_name(); 2009 2010 /* The OneofDef to which this field belongs, or NULL if this field is not part 2011 * of a oneof. */ 2012 const OneofDef* containing_oneof() const; 2013 2014 /* The field's type according to the enum in descriptor.proto. This is not 2015 * the same as UPB_TYPE_*, because it distinguishes between (for example) 2016 * INT32 and SINT32, whereas our "type" enum does not. This return of 2017 * descriptor_type() is a function of type(), integer_format(), and 2018 * is_tag_delimited(). Likewise set_descriptor_type() sets all three 2019 * appropriately. */ 2020 DescriptorType descriptor_type() const; 2021 2022 /* Convenient field type tests. */ 2023 bool IsSubMessage() const; 2024 bool IsString() const; 2025 bool IsSequence() const; 2026 bool IsPrimitive() const; 2027 bool IsMap() const; 2028 2029 /* Whether this field must be able to explicitly represent presence: 2030 * 2031 * * This is always false for repeated fields (an empty repeated field is 2032 * equivalent to a repeated field with zero entries). 2033 * 2034 * * This is always true for submessages. 2035 * 2036 * * For other fields, it depends on the message (see 2037 * MessageDef::SetPrimitivesHavePresence()) 2038 */ 2039 bool HasPresence() const; 2040 2041 /* How integers are encoded. Only meaningful for integer types. 2042 * Defaults to UPB_INTFMT_VARIABLE, and is reset when "type" changes. */ 2043 IntegerFormat integer_format() const; 2044 2045 /* Whether a submessage field is tag-delimited or not (if false, then 2046 * length-delimited). May only be set when type() == UPB_TYPE_MESSAGE. */ 2047 bool is_tag_delimited() const; 2048 2049 /* Returns the non-string default value for this fielddef, which may either 2050 * be something the client set explicitly or the "default default" (0 for 2051 * numbers, empty for strings). The field's type indicates the type of the 2052 * returned value, except for enum fields that are still mutable. 2053 * 2054 * Requires that the given function matches the field's current type. */ 2055 int64_t default_int64() const; 2056 int32_t default_int32() const; 2057 uint64_t default_uint64() const; 2058 uint32_t default_uint32() const; 2059 bool default_bool() const; 2060 float default_float() const; 2061 double default_double() const; 2062 2063 /* The resulting string is always NULL-terminated. If non-NULL, the length 2064 * will be stored in *len. */ 2065 const char *default_string(size_t* len) const; 2066 2067 /* For frozen UPB_TYPE_ENUM fields, enum defaults can always be read as either 2068 * string or int32, and both of these methods will always return true. 2069 * 2070 * For mutable UPB_TYPE_ENUM fields, the story is a bit more complicated. 2071 * Enum defaults are unusual. They can be specified either as string or int32, 2072 * but to be valid the enum must have that value as a member. And if no 2073 * default is specified, the "default default" comes from the EnumDef. 2074 * 2075 * We allow reading the default as either an int32 or a string, but only if 2076 * we have a meaningful value to report. We have a meaningful value if it was 2077 * set explicitly, or if we could get the "default default" from the EnumDef. 2078 * Also if you explicitly set the name and we find the number in the EnumDef */ 2079 bool EnumHasStringDefault() const; 2080 bool EnumHasInt32Default() const; 2081 2082 /* Submessage and enum fields must reference a "subdef", which is the 2083 * upb::MessageDef or upb::EnumDef that defines their type. Note that when 2084 * the FieldDef is mutable it may not have a subdef *yet*, but this function 2085 * still returns true to indicate that the field's type requires a subdef. */ 2086 bool HasSubDef() const; 2087 2088 /* Returns the enum or submessage def for this field, if any. The field's 2089 * type must match (ie. you may only call enum_subdef() for fields where 2090 * type() == UPB_TYPE_ENUM). Returns NULL if the subdef has not been set or 2091 * is currently set symbolically. */ 2092 const EnumDef* enum_subdef() const; 2093 const MessageDef* message_subdef() const; 2094 2095 /* Returns the generic subdef for this field. Requires that HasSubDef() (ie. 2096 * only works for UPB_TYPE_ENUM and UPB_TYPE_MESSAGE fields). */ 2097 const Def* subdef() const; 2098 2099 /* Returns the symbolic name of the subdef. If the subdef is currently set 2100 * unresolved (ie. set symbolically) returns the symbolic name. If it has 2101 * been resolved to a specific subdef, returns the name from that subdef. */ 2102 const char* subdef_name() const; 2103 2104 /* Setters (non-const methods), only valid for mutable FieldDefs! ***********/ 2105 2106 bool set_full_name(const char* fullname, upb::Status* s); 2107 bool set_full_name(const std::string& fullname, upb::Status* s); 2108 2109 /* This may only be called if containing_type() == NULL (ie. the field has not 2110 * been added to a message yet). */ 2111 bool set_containing_type_name(const char *name, Status* status); 2112 bool set_containing_type_name(const std::string& name, Status* status); 2113 2114 /* Defaults to false. When we freeze, we ensure that this can only be true 2115 * for length-delimited message fields. Prior to freezing this can be true or 2116 * false with no restrictions. */ 2117 void set_lazy(bool lazy); 2118 2119 /* Defaults to true. Sets whether this field is encoded in packed format. */ 2120 void set_packed(bool packed); 2121 2122 /* "type" or "descriptor_type" MUST be set explicitly before the fielddef is 2123 * finalized. These setters require that the enum value is valid; if the 2124 * value did not come directly from an enum constant, the caller should 2125 * validate it first with the functions above (CheckFieldType(), etc). */ 2126 void set_type(Type type); 2127 void set_label(Label label); 2128 void set_descriptor_type(DescriptorType type); 2129 void set_is_extension(bool is_extension); 2130 2131 /* "number" and "name" must be set before the FieldDef is added to a 2132 * MessageDef, and may not be set after that. 2133 * 2134 * "name" is the same as full_name()/set_full_name(), but since fielddefs 2135 * most often use simple, non-qualified names, we provide this accessor 2136 * also. Generally only extensions will want to think of this name as 2137 * fully-qualified. */ 2138 bool set_number(uint32_t number, upb::Status* s); 2139 bool set_name(const char* name, upb::Status* s); 2140 bool set_name(const std::string& name, upb::Status* s); 2141 2142 /* Sets the JSON name to the given string. */ 2143 /* TODO(haberman): implement. Right now only default json_name (camelCase) 2144 * is supported. */ 2145 bool set_json_name(const char* json_name, upb::Status* s); 2146 bool set_json_name(const std::string& name, upb::Status* s); 2147 2148 /* Clears the JSON name. This will make it revert to its default, which is 2149 * a camelCased version of the regular field name. */ 2150 void clear_json_name(); 2151 2152 void set_integer_format(IntegerFormat format); 2153 bool set_tag_delimited(bool tag_delimited, upb::Status* s); 2154 2155 /* Sets default value for the field. The call must exactly match the type 2156 * of the field. Enum fields may use either setint32 or setstring to set 2157 * the default numerically or symbolically, respectively, but symbolic 2158 * defaults must be resolved before finalizing (see ResolveEnumDefault()). 2159 * 2160 * Changing the type of a field will reset its default. */ 2161 void set_default_int64(int64_t val); 2162 void set_default_int32(int32_t val); 2163 void set_default_uint64(uint64_t val); 2164 void set_default_uint32(uint32_t val); 2165 void set_default_bool(bool val); 2166 void set_default_float(float val); 2167 void set_default_double(double val); 2168 bool set_default_string(const void *str, size_t len, Status *s); 2169 bool set_default_string(const std::string &str, Status *s); 2170 void set_default_cstr(const char *str, Status *s); 2171 2172 /* Before a fielddef is frozen, its subdef may be set either directly (with a 2173 * upb::Def*) or symbolically. Symbolic refs must be resolved before the 2174 * containing msgdef can be frozen (see upb_resolve() above). upb always 2175 * guarantees that any def reachable from a live def will also be kept alive. 2176 * 2177 * Both methods require that upb_hassubdef(f) (so the type must be set prior 2178 * to calling these methods). Returns false if this is not the case, or if 2179 * the given subdef is not of the correct type. The subdef is reset if the 2180 * field's type is changed. The subdef can be set to NULL to clear it. */ 2181 bool set_subdef(const Def* subdef, Status* s); 2182 bool set_enum_subdef(const EnumDef* subdef, Status* s); 2183 bool set_message_subdef(const MessageDef* subdef, Status* s); 2184 bool set_subdef_name(const char* name, Status* s); 2185 bool set_subdef_name(const std::string &name, Status* s); 2186 2187 private: 2188 UPB_DISALLOW_POD_OPS(FieldDef, upb::FieldDef) 2189 }; 2190 2191 # endif /* defined(__cplusplus) */ 2192 2193 UPB_BEGIN_EXTERN_C 2194 2195 /* Native C API. */ 2196 upb_fielddef *upb_fielddef_new(const void *owner); 2197 upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner); 2198 2199 /* Include upb_refcounted methods like upb_fielddef_ref(). */ 2200 UPB_REFCOUNTED_CMETHODS(upb_fielddef, upb_fielddef_upcast2) 2201 2202 /* Methods from upb_def. */ 2203 const char *upb_fielddef_fullname(const upb_fielddef *f); 2204 bool upb_fielddef_setfullname(upb_fielddef *f, const char *fullname, 2205 upb_status *s); 2206 2207 bool upb_fielddef_typeisset(const upb_fielddef *f); 2208 upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f); 2209 upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f); 2210 upb_label_t upb_fielddef_label(const upb_fielddef *f); 2211 uint32_t upb_fielddef_number(const upb_fielddef *f); 2212 const char *upb_fielddef_name(const upb_fielddef *f); 2213 bool upb_fielddef_isextension(const upb_fielddef *f); 2214 bool upb_fielddef_lazy(const upb_fielddef *f); 2215 bool upb_fielddef_packed(const upb_fielddef *f); 2216 size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len); 2217 const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f); 2218 const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f); 2219 upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f); 2220 const char *upb_fielddef_containingtypename(upb_fielddef *f); 2221 upb_intfmt_t upb_fielddef_intfmt(const upb_fielddef *f); 2222 uint32_t upb_fielddef_index(const upb_fielddef *f); 2223 bool upb_fielddef_istagdelim(const upb_fielddef *f); 2224 bool upb_fielddef_issubmsg(const upb_fielddef *f); 2225 bool upb_fielddef_isstring(const upb_fielddef *f); 2226 bool upb_fielddef_isseq(const upb_fielddef *f); 2227 bool upb_fielddef_isprimitive(const upb_fielddef *f); 2228 bool upb_fielddef_ismap(const upb_fielddef *f); 2229 bool upb_fielddef_haspresence(const upb_fielddef *f); 2230 int64_t upb_fielddef_defaultint64(const upb_fielddef *f); 2231 int32_t upb_fielddef_defaultint32(const upb_fielddef *f); 2232 uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f); 2233 uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f); 2234 bool upb_fielddef_defaultbool(const upb_fielddef *f); 2235 float upb_fielddef_defaultfloat(const upb_fielddef *f); 2236 double upb_fielddef_defaultdouble(const upb_fielddef *f); 2237 const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len); 2238 bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f); 2239 bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f); 2240 bool upb_fielddef_hassubdef(const upb_fielddef *f); 2241 const upb_def *upb_fielddef_subdef(const upb_fielddef *f); 2242 const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f); 2243 const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f); 2244 const char *upb_fielddef_subdefname(const upb_fielddef *f); 2245 2246 void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type); 2247 void upb_fielddef_setdescriptortype(upb_fielddef *f, int type); 2248 void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label); 2249 bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s); 2250 bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s); 2251 bool upb_fielddef_setjsonname(upb_fielddef *f, const char *name, upb_status *s); 2252 bool upb_fielddef_clearjsonname(upb_fielddef *f); 2253 bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name, 2254 upb_status *s); 2255 void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension); 2256 void upb_fielddef_setlazy(upb_fielddef *f, bool lazy); 2257 void upb_fielddef_setpacked(upb_fielddef *f, bool packed); 2258 void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt); 2259 void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim); 2260 void upb_fielddef_setdefaultint64(upb_fielddef *f, int64_t val); 2261 void upb_fielddef_setdefaultint32(upb_fielddef *f, int32_t val); 2262 void upb_fielddef_setdefaultuint64(upb_fielddef *f, uint64_t val); 2263 void upb_fielddef_setdefaultuint32(upb_fielddef *f, uint32_t val); 2264 void upb_fielddef_setdefaultbool(upb_fielddef *f, bool val); 2265 void upb_fielddef_setdefaultfloat(upb_fielddef *f, float val); 2266 void upb_fielddef_setdefaultdouble(upb_fielddef *f, double val); 2267 bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len, 2268 upb_status *s); 2269 void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str, 2270 upb_status *s); 2271 bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef, 2272 upb_status *s); 2273 bool upb_fielddef_setmsgsubdef(upb_fielddef *f, const upb_msgdef *subdef, 2274 upb_status *s); 2275 bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef, 2276 upb_status *s); 2277 bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name, 2278 upb_status *s); 2279 2280 bool upb_fielddef_checklabel(int32_t label); 2281 bool upb_fielddef_checktype(int32_t type); 2282 bool upb_fielddef_checkdescriptortype(int32_t type); 2283 bool upb_fielddef_checkintfmt(int32_t fmt); 2284 2285 UPB_END_EXTERN_C 2286 2287 2288 /* upb::MessageDef ************************************************************/ 2289 2290 typedef upb_inttable_iter upb_msg_field_iter; 2291 typedef upb_strtable_iter upb_msg_oneof_iter; 2292 2293 /* Well-known field tag numbers for map-entry messages. */ 2294 #define UPB_MAPENTRY_KEY 1 2295 #define UPB_MAPENTRY_VALUE 2 2296 2297 #ifdef __cplusplus 2298 2299 /* Structure that describes a single .proto message type. 2300 * 2301 * Its base class is upb::Def (use upb::upcast() to convert). */ 2302 class upb::MessageDef { 2303 public: 2304 /* Returns NULL if memory allocation failed. */ 2305 static reffed_ptr<MessageDef> New(); 2306 2307 /* upb::RefCounted methods like Ref()/Unref(). */ 2308 UPB_REFCOUNTED_CPPMETHODS 2309 2310 /* Functionality from upb::Def. */ 2311 const char* full_name() const; 2312 const char* name() const; 2313 bool set_full_name(const char* fullname, Status* s); 2314 bool set_full_name(const std::string& fullname, Status* s); 2315 2316 /* Call to freeze this MessageDef. 2317 * WARNING: this will fail if this message has any unfrozen submessages! 2318 * Messages with cycles must be frozen as a batch using upb::Def::Freeze(). */ 2319 bool Freeze(Status* s); 2320 2321 /* The number of fields that belong to the MessageDef. */ 2322 int field_count() const; 2323 2324 /* The number of oneofs that belong to the MessageDef. */ 2325 int oneof_count() const; 2326 2327 /* Adds a field (upb_fielddef object) to a msgdef. Requires that the msgdef 2328 * and the fielddefs are mutable. The fielddef's name and number must be 2329 * set, and the message may not already contain any field with this name or 2330 * number, and this fielddef may not be part of another message. In error 2331 * cases false is returned and the msgdef is unchanged. 2332 * 2333 * If the given field is part of a oneof, this call succeeds if and only if 2334 * that oneof is already part of this msgdef. (Note that adding a oneof to a 2335 * msgdef automatically adds all of its fields to the msgdef at the time that 2336 * the oneof is added, so it is usually more idiomatic to add the oneof's 2337 * fields first then add the oneof to the msgdef. This case is supported for 2338 * convenience.) 2339 * 2340 * If |f| is already part of this MessageDef, this method performs no action 2341 * and returns true (success). Thus, this method is idempotent. */ 2342 bool AddField(FieldDef* f, Status* s); 2343 bool AddField(const reffed_ptr<FieldDef>& f, Status* s); 2344 2345 /* Adds a oneof (upb_oneofdef object) to a msgdef. Requires that the msgdef, 2346 * oneof, and any fielddefs are mutable, that the fielddefs contained in the 2347 * oneof do not have any name or number conflicts with existing fields in the 2348 * msgdef, and that the oneof's name is unique among all oneofs in the msgdef. 2349 * If the oneof is added successfully, all of its fields will be added 2350 * directly to the msgdef as well. In error cases, false is returned and the 2351 * msgdef is unchanged. */ 2352 bool AddOneof(OneofDef* o, Status* s); 2353 bool AddOneof(const reffed_ptr<OneofDef>& o, Status* s); 2354 2355 upb_syntax_t syntax() const; 2356 2357 /* Returns false if we don't support this syntax value. */ 2358 bool set_syntax(upb_syntax_t syntax); 2359 2360 /* Set this to false to indicate that primitive fields should not have 2361 * explicit presence information associated with them. This will affect all 2362 * fields added to this message. Defaults to true. */ 2363 void SetPrimitivesHavePresence(bool have_presence); 2364 2365 /* These return NULL if the field is not found. */ 2366 FieldDef* FindFieldByNumber(uint32_t number); 2367 FieldDef* FindFieldByName(const char *name, size_t len); 2368 const FieldDef* FindFieldByNumber(uint32_t number) const; 2369 const FieldDef* FindFieldByName(const char* name, size_t len) const; 2370 2371 2372 FieldDef* FindFieldByName(const char *name) { 2373 return FindFieldByName(name, strlen(name)); 2374 } 2375 const FieldDef* FindFieldByName(const char *name) const { 2376 return FindFieldByName(name, strlen(name)); 2377 } 2378 2379 template <class T> 2380 FieldDef* FindFieldByName(const T& str) { 2381 return FindFieldByName(str.c_str(), str.size()); 2382 } 2383 template <class T> 2384 const FieldDef* FindFieldByName(const T& str) const { 2385 return FindFieldByName(str.c_str(), str.size()); 2386 } 2387 2388 OneofDef* FindOneofByName(const char* name, size_t len); 2389 const OneofDef* FindOneofByName(const char* name, size_t len) const; 2390 2391 OneofDef* FindOneofByName(const char* name) { 2392 return FindOneofByName(name, strlen(name)); 2393 } 2394 const OneofDef* FindOneofByName(const char* name) const { 2395 return FindOneofByName(name, strlen(name)); 2396 } 2397 2398 template<class T> 2399 OneofDef* FindOneofByName(const T& str) { 2400 return FindOneofByName(str.c_str(), str.size()); 2401 } 2402 template<class T> 2403 const OneofDef* FindOneofByName(const T& str) const { 2404 return FindOneofByName(str.c_str(), str.size()); 2405 } 2406 2407 /* Returns a new msgdef that is a copy of the given msgdef (and a copy of all 2408 * the fields) but with any references to submessages broken and replaced 2409 * with just the name of the submessage. Returns NULL if memory allocation 2410 * failed. 2411 * 2412 * TODO(haberman): which is more useful, keeping fields resolved or 2413 * unresolving them? If there's no obvious answer, Should this functionality 2414 * just be moved into symtab.c? */ 2415 MessageDef* Dup(const void* owner) const; 2416 2417 /* Is this message a map entry? */ 2418 void setmapentry(bool map_entry); 2419 bool mapentry() const; 2420 2421 /* Iteration over fields. The order is undefined. */ 2422 class field_iterator 2423 : public std::iterator<std::forward_iterator_tag, FieldDef*> { 2424 public: 2425 explicit field_iterator(MessageDef* md); 2426 static field_iterator end(MessageDef* md); 2427 2428 void operator++(); 2429 FieldDef* operator*() const; 2430 bool operator!=(const field_iterator& other) const; 2431 bool operator==(const field_iterator& other) const; 2432 2433 private: 2434 upb_msg_field_iter iter_; 2435 }; 2436 2437 class const_field_iterator 2438 : public std::iterator<std::forward_iterator_tag, const FieldDef*> { 2439 public: 2440 explicit const_field_iterator(const MessageDef* md); 2441 static const_field_iterator end(const MessageDef* md); 2442 2443 void operator++(); 2444 const FieldDef* operator*() const; 2445 bool operator!=(const const_field_iterator& other) const; 2446 bool operator==(const const_field_iterator& other) const; 2447 2448 private: 2449 upb_msg_field_iter iter_; 2450 }; 2451 2452 /* Iteration over oneofs. The order is undefined. */ 2453 class oneof_iterator 2454 : public std::iterator<std::forward_iterator_tag, FieldDef*> { 2455 public: 2456 explicit oneof_iterator(MessageDef* md); 2457 static oneof_iterator end(MessageDef* md); 2458 2459 void operator++(); 2460 OneofDef* operator*() const; 2461 bool operator!=(const oneof_iterator& other) const; 2462 bool operator==(const oneof_iterator& other) const; 2463 2464 private: 2465 upb_msg_oneof_iter iter_; 2466 }; 2467 2468 class const_oneof_iterator 2469 : public std::iterator<std::forward_iterator_tag, const FieldDef*> { 2470 public: 2471 explicit const_oneof_iterator(const MessageDef* md); 2472 static const_oneof_iterator end(const MessageDef* md); 2473 2474 void operator++(); 2475 const OneofDef* operator*() const; 2476 bool operator!=(const const_oneof_iterator& other) const; 2477 bool operator==(const const_oneof_iterator& other) const; 2478 2479 private: 2480 upb_msg_oneof_iter iter_; 2481 }; 2482 2483 class FieldAccessor { 2484 public: 2485 explicit FieldAccessor(MessageDef* msg) : msg_(msg) {} 2486 field_iterator begin() { return msg_->field_begin(); } 2487 field_iterator end() { return msg_->field_end(); } 2488 private: 2489 MessageDef* msg_; 2490 }; 2491 2492 class ConstFieldAccessor { 2493 public: 2494 explicit ConstFieldAccessor(const MessageDef* msg) : msg_(msg) {} 2495 const_field_iterator begin() { return msg_->field_begin(); } 2496 const_field_iterator end() { return msg_->field_end(); } 2497 private: 2498 const MessageDef* msg_; 2499 }; 2500 2501 class OneofAccessor { 2502 public: 2503 explicit OneofAccessor(MessageDef* msg) : msg_(msg) {} 2504 oneof_iterator begin() { return msg_->oneof_begin(); } 2505 oneof_iterator end() { return msg_->oneof_end(); } 2506 private: 2507 MessageDef* msg_; 2508 }; 2509 2510 class ConstOneofAccessor { 2511 public: 2512 explicit ConstOneofAccessor(const MessageDef* msg) : msg_(msg) {} 2513 const_oneof_iterator begin() { return msg_->oneof_begin(); } 2514 const_oneof_iterator end() { return msg_->oneof_end(); } 2515 private: 2516 const MessageDef* msg_; 2517 }; 2518 2519 field_iterator field_begin(); 2520 field_iterator field_end(); 2521 const_field_iterator field_begin() const; 2522 const_field_iterator field_end() const; 2523 2524 oneof_iterator oneof_begin(); 2525 oneof_iterator oneof_end(); 2526 const_oneof_iterator oneof_begin() const; 2527 const_oneof_iterator oneof_end() const; 2528 2529 FieldAccessor fields() { return FieldAccessor(this); } 2530 ConstFieldAccessor fields() const { return ConstFieldAccessor(this); } 2531 OneofAccessor oneofs() { return OneofAccessor(this); } 2532 ConstOneofAccessor oneofs() const { return ConstOneofAccessor(this); } 2533 2534 private: 2535 UPB_DISALLOW_POD_OPS(MessageDef, upb::MessageDef) 2536 }; 2537 2538 #endif /* __cplusplus */ 2539 2540 UPB_BEGIN_EXTERN_C 2541 2542 /* Returns NULL if memory allocation failed. */ 2543 upb_msgdef *upb_msgdef_new(const void *owner); 2544 2545 /* Include upb_refcounted methods like upb_msgdef_ref(). */ 2546 UPB_REFCOUNTED_CMETHODS(upb_msgdef, upb_msgdef_upcast2) 2547 2548 bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status); 2549 2550 upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner); 2551 const char *upb_msgdef_fullname(const upb_msgdef *m); 2552 const char *upb_msgdef_name(const upb_msgdef *m); 2553 int upb_msgdef_numoneofs(const upb_msgdef *m); 2554 upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m); 2555 2556 bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor, 2557 upb_status *s); 2558 bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor, 2559 upb_status *s); 2560 bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname, upb_status *s); 2561 void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry); 2562 bool upb_msgdef_mapentry(const upb_msgdef *m); 2563 bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax); 2564 2565 /* Field lookup in a couple of different variations: 2566 * - itof = int to field 2567 * - ntof = name to field 2568 * - ntofz = name to field, null-terminated string. */ 2569 const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i); 2570 const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name, 2571 size_t len); 2572 int upb_msgdef_numfields(const upb_msgdef *m); 2573 2574 UPB_INLINE const upb_fielddef *upb_msgdef_ntofz(const upb_msgdef *m, 2575 const char *name) { 2576 return upb_msgdef_ntof(m, name, strlen(name)); 2577 } 2578 2579 UPB_INLINE upb_fielddef *upb_msgdef_itof_mutable(upb_msgdef *m, uint32_t i) { 2580 return (upb_fielddef*)upb_msgdef_itof(m, i); 2581 } 2582 2583 UPB_INLINE upb_fielddef *upb_msgdef_ntof_mutable(upb_msgdef *m, 2584 const char *name, size_t len) { 2585 return (upb_fielddef *)upb_msgdef_ntof(m, name, len); 2586 } 2587 2588 /* Oneof lookup: 2589 * - ntoo = name to oneof 2590 * - ntooz = name to oneof, null-terminated string. */ 2591 const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name, 2592 size_t len); 2593 int upb_msgdef_numoneofs(const upb_msgdef *m); 2594 2595 UPB_INLINE const upb_oneofdef *upb_msgdef_ntooz(const upb_msgdef *m, 2596 const char *name) { 2597 return upb_msgdef_ntoo(m, name, strlen(name)); 2598 } 2599 2600 UPB_INLINE upb_oneofdef *upb_msgdef_ntoo_mutable(upb_msgdef *m, 2601 const char *name, size_t len) { 2602 return (upb_oneofdef *)upb_msgdef_ntoo(m, name, len); 2603 } 2604 2605 /* Lookup of either field or oneof by name. Returns whether either was found. 2606 * If the return is true, then the found def will be set, and the non-found 2607 * one set to NULL. */ 2608 bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len, 2609 const upb_fielddef **f, const upb_oneofdef **o); 2610 2611 UPB_INLINE bool upb_msgdef_lookupnamez(const upb_msgdef *m, const char *name, 2612 const upb_fielddef **f, 2613 const upb_oneofdef **o) { 2614 return upb_msgdef_lookupname(m, name, strlen(name), f, o); 2615 } 2616 2617 /* Iteration over fields and oneofs. For example: 2618 * 2619 * upb_msg_field_iter i; 2620 * for(upb_msg_field_begin(&i, m); 2621 * !upb_msg_field_done(&i); 2622 * upb_msg_field_next(&i)) { 2623 * upb_fielddef *f = upb_msg_iter_field(&i); 2624 * // ... 2625 * } 2626 * 2627 * For C we don't have separate iterators for const and non-const. 2628 * It is the caller's responsibility to cast the upb_fielddef* to 2629 * const if the upb_msgdef* is const. */ 2630 void upb_msg_field_begin(upb_msg_field_iter *iter, const upb_msgdef *m); 2631 void upb_msg_field_next(upb_msg_field_iter *iter); 2632 bool upb_msg_field_done(const upb_msg_field_iter *iter); 2633 upb_fielddef *upb_msg_iter_field(const upb_msg_field_iter *iter); 2634 void upb_msg_field_iter_setdone(upb_msg_field_iter *iter); 2635 2636 /* Similar to above, we also support iterating through the oneofs in a 2637 * msgdef. */ 2638 void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m); 2639 void upb_msg_oneof_next(upb_msg_oneof_iter *iter); 2640 bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter); 2641 upb_oneofdef *upb_msg_iter_oneof(const upb_msg_oneof_iter *iter); 2642 void upb_msg_oneof_iter_setdone(upb_msg_oneof_iter *iter); 2643 2644 UPB_END_EXTERN_C 2645 2646 2647 /* upb::EnumDef ***************************************************************/ 2648 2649 typedef upb_strtable_iter upb_enum_iter; 2650 2651 #ifdef __cplusplus 2652 2653 /* Class that represents an enum. Its base class is upb::Def (convert with 2654 * upb::upcast()). */ 2655 class upb::EnumDef { 2656 public: 2657 /* Returns NULL if memory allocation failed. */ 2658 static reffed_ptr<EnumDef> New(); 2659 2660 /* upb::RefCounted methods like Ref()/Unref(). */ 2661 UPB_REFCOUNTED_CPPMETHODS 2662 2663 /* Functionality from upb::Def. */ 2664 const char* full_name() const; 2665 const char* name() const; 2666 bool set_full_name(const char* fullname, Status* s); 2667 bool set_full_name(const std::string& fullname, Status* s); 2668 2669 /* Call to freeze this EnumDef. */ 2670 bool Freeze(Status* s); 2671 2672 /* The value that is used as the default when no field default is specified. 2673 * If not set explicitly, the first value that was added will be used. 2674 * The default value must be a member of the enum. 2675 * Requires that value_count() > 0. */ 2676 int32_t default_value() const; 2677 2678 /* Sets the default value. If this value is not valid, returns false and an 2679 * error message in status. */ 2680 bool set_default_value(int32_t val, Status* status); 2681 2682 /* Returns the number of values currently defined in the enum. Note that 2683 * multiple names can refer to the same number, so this may be greater than 2684 * the total number of unique numbers. */ 2685 int value_count() const; 2686 2687 /* Adds a single name/number pair to the enum. Fails if this name has 2688 * already been used by another value. */ 2689 bool AddValue(const char* name, int32_t num, Status* status); 2690 bool AddValue(const std::string& name, int32_t num, Status* status); 2691 2692 /* Lookups from name to integer, returning true if found. */ 2693 bool FindValueByName(const char* name, int32_t* num) const; 2694 2695 /* Finds the name corresponding to the given number, or NULL if none was 2696 * found. If more than one name corresponds to this number, returns the 2697 * first one that was added. */ 2698 const char* FindValueByNumber(int32_t num) const; 2699 2700 /* Returns a new EnumDef with all the same values. The new EnumDef will be 2701 * owned by the given owner. */ 2702 EnumDef* Dup(const void* owner) const; 2703 2704 /* Iteration over name/value pairs. The order is undefined. 2705 * Adding an enum val invalidates any iterators. 2706 * 2707 * TODO: make compatible with range-for, with elements as pairs? */ 2708 class Iterator { 2709 public: 2710 explicit Iterator(const EnumDef*); 2711 2712 int32_t number(); 2713 const char *name(); 2714 bool Done(); 2715 void Next(); 2716 2717 private: 2718 upb_enum_iter iter_; 2719 }; 2720 2721 private: 2722 UPB_DISALLOW_POD_OPS(EnumDef, upb::EnumDef) 2723 }; 2724 2725 #endif /* __cplusplus */ 2726 2727 UPB_BEGIN_EXTERN_C 2728 2729 /* Native C API. */ 2730 upb_enumdef *upb_enumdef_new(const void *owner); 2731 upb_enumdef *upb_enumdef_dup(const upb_enumdef *e, const void *owner); 2732 2733 /* Include upb_refcounted methods like upb_enumdef_ref(). */ 2734 UPB_REFCOUNTED_CMETHODS(upb_enumdef, upb_enumdef_upcast2) 2735 2736 bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status); 2737 2738 /* From upb_def. */ 2739 const char *upb_enumdef_fullname(const upb_enumdef *e); 2740 const char *upb_enumdef_name(const upb_enumdef *e); 2741 bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname, 2742 upb_status *s); 2743 2744 int32_t upb_enumdef_default(const upb_enumdef *e); 2745 bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s); 2746 int upb_enumdef_numvals(const upb_enumdef *e); 2747 bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num, 2748 upb_status *status); 2749 2750 /* Enum lookups: 2751 * - ntoi: look up a name with specified length. 2752 * - ntoiz: look up a name provided as a null-terminated string. 2753 * - iton: look up an integer, returning the name as a null-terminated 2754 * string. */ 2755 bool upb_enumdef_ntoi(const upb_enumdef *e, const char *name, size_t len, 2756 int32_t *num); 2757 UPB_INLINE bool upb_enumdef_ntoiz(const upb_enumdef *e, 2758 const char *name, int32_t *num) { 2759 return upb_enumdef_ntoi(e, name, strlen(name), num); 2760 } 2761 const char *upb_enumdef_iton(const upb_enumdef *e, int32_t num); 2762 2763 /* upb_enum_iter i; 2764 * for(upb_enum_begin(&i, e); !upb_enum_done(&i); upb_enum_next(&i)) { 2765 * // ... 2766 * } 2767 */ 2768 void upb_enum_begin(upb_enum_iter *iter, const upb_enumdef *e); 2769 void upb_enum_next(upb_enum_iter *iter); 2770 bool upb_enum_done(upb_enum_iter *iter); 2771 const char *upb_enum_iter_name(upb_enum_iter *iter); 2772 int32_t upb_enum_iter_number(upb_enum_iter *iter); 2773 2774 UPB_END_EXTERN_C 2775 2776 /* upb::OneofDef **************************************************************/ 2777 2778 typedef upb_inttable_iter upb_oneof_iter; 2779 2780 #ifdef __cplusplus 2781 2782 /* Class that represents a oneof. */ 2783 class upb::OneofDef { 2784 public: 2785 /* Returns NULL if memory allocation failed. */ 2786 static reffed_ptr<OneofDef> New(); 2787 2788 /* upb::RefCounted methods like Ref()/Unref(). */ 2789 UPB_REFCOUNTED_CPPMETHODS 2790 2791 /* Returns the MessageDef that owns this OneofDef. */ 2792 const MessageDef* containing_type() const; 2793 2794 /* Returns the name of this oneof. This is the name used to look up the oneof 2795 * by name once added to a message def. */ 2796 const char* name() const; 2797 bool set_name(const char* name, Status* s); 2798 bool set_name(const std::string& name, Status* s); 2799 2800 /* Returns the number of fields currently defined in the oneof. */ 2801 int field_count() const; 2802 2803 /* Adds a field to the oneof. The field must not have been added to any other 2804 * oneof or msgdef. If the oneof is not yet part of a msgdef, then when the 2805 * oneof is eventually added to a msgdef, all fields added to the oneof will 2806 * also be added to the msgdef at that time. If the oneof is already part of a 2807 * msgdef, the field must either be a part of that msgdef already, or must not 2808 * be a part of any msgdef; in the latter case, the field is added to the 2809 * msgdef as a part of this operation. 2810 * 2811 * The field may only have an OPTIONAL label, never REQUIRED or REPEATED. 2812 * 2813 * If |f| is already part of this MessageDef, this method performs no action 2814 * and returns true (success). Thus, this method is idempotent. */ 2815 bool AddField(FieldDef* field, Status* s); 2816 bool AddField(const reffed_ptr<FieldDef>& field, Status* s); 2817 2818 /* Looks up by name. */ 2819 const FieldDef* FindFieldByName(const char* name, size_t len) const; 2820 FieldDef* FindFieldByName(const char* name, size_t len); 2821 const FieldDef* FindFieldByName(const char* name) const { 2822 return FindFieldByName(name, strlen(name)); 2823 } 2824 FieldDef* FindFieldByName(const char* name) { 2825 return FindFieldByName(name, strlen(name)); 2826 } 2827 2828 template <class T> 2829 FieldDef* FindFieldByName(const T& str) { 2830 return FindFieldByName(str.c_str(), str.size()); 2831 } 2832 template <class T> 2833 const FieldDef* FindFieldByName(const T& str) const { 2834 return FindFieldByName(str.c_str(), str.size()); 2835 } 2836 2837 /* Looks up by tag number. */ 2838 const FieldDef* FindFieldByNumber(uint32_t num) const; 2839 2840 /* Returns a new OneofDef with all the same fields. The OneofDef will be owned 2841 * by the given owner. */ 2842 OneofDef* Dup(const void* owner) const; 2843 2844 /* Iteration over fields. The order is undefined. */ 2845 class iterator : public std::iterator<std::forward_iterator_tag, FieldDef*> { 2846 public: 2847 explicit iterator(OneofDef* md); 2848 static iterator end(OneofDef* md); 2849 2850 void operator++(); 2851 FieldDef* operator*() const; 2852 bool operator!=(const iterator& other) const; 2853 bool operator==(const iterator& other) const; 2854 2855 private: 2856 upb_oneof_iter iter_; 2857 }; 2858 2859 class const_iterator 2860 : public std::iterator<std::forward_iterator_tag, const FieldDef*> { 2861 public: 2862 explicit const_iterator(const OneofDef* md); 2863 static const_iterator end(const OneofDef* md); 2864 2865 void operator++(); 2866 const FieldDef* operator*() const; 2867 bool operator!=(const const_iterator& other) const; 2868 bool operator==(const const_iterator& other) const; 2869 2870 private: 2871 upb_oneof_iter iter_; 2872 }; 2873 2874 iterator begin(); 2875 iterator end(); 2876 const_iterator begin() const; 2877 const_iterator end() const; 2878 2879 private: 2880 UPB_DISALLOW_POD_OPS(OneofDef, upb::OneofDef) 2881 }; 2882 2883 #endif /* __cplusplus */ 2884 2885 UPB_BEGIN_EXTERN_C 2886 2887 /* Native C API. */ 2888 upb_oneofdef *upb_oneofdef_new(const void *owner); 2889 upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner); 2890 2891 /* Include upb_refcounted methods like upb_oneofdef_ref(). */ 2892 UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast) 2893 2894 const char *upb_oneofdef_name(const upb_oneofdef *o); 2895 bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s); 2896 2897 const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o); 2898 int upb_oneofdef_numfields(const upb_oneofdef *o); 2899 bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f, 2900 const void *ref_donor, 2901 upb_status *s); 2902 2903 /* Oneof lookups: 2904 * - ntof: look up a field by name. 2905 * - ntofz: look up a field by name (as a null-terminated string). 2906 * - itof: look up a field by number. */ 2907 const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o, 2908 const char *name, size_t length); 2909 UPB_INLINE const upb_fielddef *upb_oneofdef_ntofz(const upb_oneofdef *o, 2910 const char *name) { 2911 return upb_oneofdef_ntof(o, name, strlen(name)); 2912 } 2913 const upb_fielddef *upb_oneofdef_itof(const upb_oneofdef *o, uint32_t num); 2914 2915 /* upb_oneof_iter i; 2916 * for(upb_oneof_begin(&i, e); !upb_oneof_done(&i); upb_oneof_next(&i)) { 2917 * // ... 2918 * } 2919 */ 2920 void upb_oneof_begin(upb_oneof_iter *iter, const upb_oneofdef *o); 2921 void upb_oneof_next(upb_oneof_iter *iter); 2922 bool upb_oneof_done(upb_oneof_iter *iter); 2923 upb_fielddef *upb_oneof_iter_field(const upb_oneof_iter *iter); 2924 void upb_oneof_iter_setdone(upb_oneof_iter *iter); 2925 2926 UPB_END_EXTERN_C 2927 2928 2929 /* upb::FileDef ***************************************************************/ 2930 2931 #ifdef __cplusplus 2932 2933 /* Class that represents a .proto file with some things defined in it. 2934 * 2935 * Many users won't care about FileDefs, but they are necessary if you want to 2936 * read the values of file-level options. */ 2937 class upb::FileDef { 2938 public: 2939 /* Returns NULL if memory allocation failed. */ 2940 static reffed_ptr<FileDef> New(); 2941 2942 /* upb::RefCounted methods like Ref()/Unref(). */ 2943 UPB_REFCOUNTED_CPPMETHODS 2944 2945 /* Get/set name of the file (eg. "foo/bar.proto"). */ 2946 const char* name() const; 2947 bool set_name(const char* name, Status* s); 2948 bool set_name(const std::string& name, Status* s); 2949 2950 /* Package name for definitions inside the file (eg. "foo.bar"). */ 2951 const char* package() const; 2952 bool set_package(const char* package, Status* s); 2953 2954 /* Syntax for the file. Defaults to proto2. */ 2955 upb_syntax_t syntax() const; 2956 void set_syntax(upb_syntax_t syntax); 2957 2958 /* Get the list of defs from the file. These are returned in the order that 2959 * they were added to the FileDef. */ 2960 int def_count() const; 2961 const Def* def(int index) const; 2962 Def* def(int index); 2963 2964 /* Get the list of dependencies from the file. These are returned in the 2965 * order that they were added to the FileDef. */ 2966 int dependency_count() const; 2967 const FileDef* dependency(int index) const; 2968 2969 /* Adds defs to this file. The def must not already belong to another 2970 * file. 2971 * 2972 * Note: this does *not* ensure that this def's name is unique in this file! 2973 * Use a SymbolTable if you want to check this property. Especially since 2974 * properly checking uniqueness would require a check across *all* files 2975 * (including dependencies). */ 2976 bool AddDef(Def* def, Status* s); 2977 bool AddMessage(MessageDef* m, Status* s); 2978 bool AddEnum(EnumDef* e, Status* s); 2979 bool AddExtension(FieldDef* f, Status* s); 2980 2981 /* Adds a dependency of this file. */ 2982 bool AddDependency(const FileDef* file); 2983 2984 /* Freezes this FileDef and all messages/enums under it. All subdefs must be 2985 * resolved and all messages/enums must validate. Returns true if this 2986 * succeeded. 2987 * 2988 * TODO(haberman): should we care whether the file's dependencies are frozen 2989 * already? */ 2990 bool Freeze(Status* s); 2991 2992 private: 2993 UPB_DISALLOW_POD_OPS(FileDef, upb::FileDef) 2994 }; 2995 2996 #endif 2997 2998 UPB_BEGIN_EXTERN_C 2999 3000 upb_filedef *upb_filedef_new(const void *owner); 3001 3002 /* Include upb_refcounted methods like upb_msgdef_ref(). */ 3003 UPB_REFCOUNTED_CMETHODS(upb_filedef, upb_filedef_upcast) 3004 3005 const char *upb_filedef_name(const upb_filedef *f); 3006 const char *upb_filedef_package(const upb_filedef *f); 3007 upb_syntax_t upb_filedef_syntax(const upb_filedef *f); 3008 size_t upb_filedef_defcount(const upb_filedef *f); 3009 size_t upb_filedef_depcount(const upb_filedef *f); 3010 const upb_def *upb_filedef_def(const upb_filedef *f, size_t i); 3011 const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i); 3012 3013 bool upb_filedef_freeze(upb_filedef *f, upb_status *s); 3014 bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s); 3015 bool upb_filedef_setpackage(upb_filedef *f, const char *package, upb_status *s); 3016 bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax, upb_status *s); 3017 3018 bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor, 3019 upb_status *s); 3020 bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep); 3021 3022 UPB_INLINE bool upb_filedef_addmsg(upb_filedef *f, upb_msgdef *m, 3023 const void *ref_donor, upb_status *s) { 3024 return upb_filedef_adddef(f, upb_msgdef_upcast_mutable(m), ref_donor, s); 3025 } 3026 3027 UPB_INLINE bool upb_filedef_addenum(upb_filedef *f, upb_enumdef *e, 3028 const void *ref_donor, upb_status *s) { 3029 return upb_filedef_adddef(f, upb_enumdef_upcast_mutable(e), ref_donor, s); 3030 } 3031 3032 UPB_INLINE bool upb_filedef_addext(upb_filedef *file, upb_fielddef *f, 3033 const void *ref_donor, upb_status *s) { 3034 return upb_filedef_adddef(file, upb_fielddef_upcast_mutable(f), ref_donor, s); 3035 } 3036 UPB_INLINE upb_def *upb_filedef_mutabledef(upb_filedef *f, int i) { 3037 return (upb_def*)upb_filedef_def(f, i); 3038 } 3039 3040 UPB_END_EXTERN_C 3041 3042 #ifdef __cplusplus 3043 3044 UPB_INLINE const char* upb_safecstr(const std::string& str) { 3045 assert(str.size() == std::strlen(str.c_str())); 3046 return str.c_str(); 3047 } 3048 3049 /* Inline C++ wrappers. */ 3050 namespace upb { 3051 3052 inline Def* Def::Dup(const void* owner) const { 3053 return upb_def_dup(this, owner); 3054 } 3055 inline Def::Type Def::def_type() const { return upb_def_type(this); } 3056 inline const char* Def::full_name() const { return upb_def_fullname(this); } 3057 inline const char* Def::name() const { return upb_def_name(this); } 3058 inline bool Def::set_full_name(const char* fullname, Status* s) { 3059 return upb_def_setfullname(this, fullname, s); 3060 } 3061 inline bool Def::set_full_name(const std::string& fullname, Status* s) { 3062 return upb_def_setfullname(this, upb_safecstr(fullname), s); 3063 } 3064 inline bool Def::Freeze(Def* const* defs, size_t n, Status* status) { 3065 return upb_def_freeze(defs, n, status); 3066 } 3067 inline bool Def::Freeze(const std::vector<Def*>& defs, Status* status) { 3068 return upb_def_freeze((Def* const*)&defs[0], defs.size(), status); 3069 } 3070 3071 inline bool FieldDef::CheckType(int32_t val) { 3072 return upb_fielddef_checktype(val); 3073 } 3074 inline bool FieldDef::CheckLabel(int32_t val) { 3075 return upb_fielddef_checklabel(val); 3076 } 3077 inline bool FieldDef::CheckDescriptorType(int32_t val) { 3078 return upb_fielddef_checkdescriptortype(val); 3079 } 3080 inline bool FieldDef::CheckIntegerFormat(int32_t val) { 3081 return upb_fielddef_checkintfmt(val); 3082 } 3083 inline FieldDef::Type FieldDef::ConvertType(int32_t val) { 3084 assert(CheckType(val)); 3085 return static_cast<FieldDef::Type>(val); 3086 } 3087 inline FieldDef::Label FieldDef::ConvertLabel(int32_t val) { 3088 assert(CheckLabel(val)); 3089 return static_cast<FieldDef::Label>(val); 3090 } 3091 inline FieldDef::DescriptorType FieldDef::ConvertDescriptorType(int32_t val) { 3092 assert(CheckDescriptorType(val)); 3093 return static_cast<FieldDef::DescriptorType>(val); 3094 } 3095 inline FieldDef::IntegerFormat FieldDef::ConvertIntegerFormat(int32_t val) { 3096 assert(CheckIntegerFormat(val)); 3097 return static_cast<FieldDef::IntegerFormat>(val); 3098 } 3099 3100 inline reffed_ptr<FieldDef> FieldDef::New() { 3101 upb_fielddef *f = upb_fielddef_new(&f); 3102 return reffed_ptr<FieldDef>(f, &f); 3103 } 3104 inline FieldDef* FieldDef::Dup(const void* owner) const { 3105 return upb_fielddef_dup(this, owner); 3106 } 3107 inline const char* FieldDef::full_name() const { 3108 return upb_fielddef_fullname(this); 3109 } 3110 inline bool FieldDef::set_full_name(const char* fullname, Status* s) { 3111 return upb_fielddef_setfullname(this, fullname, s); 3112 } 3113 inline bool FieldDef::set_full_name(const std::string& fullname, Status* s) { 3114 return upb_fielddef_setfullname(this, upb_safecstr(fullname), s); 3115 } 3116 inline bool FieldDef::type_is_set() const { 3117 return upb_fielddef_typeisset(this); 3118 } 3119 inline FieldDef::Type FieldDef::type() const { return upb_fielddef_type(this); } 3120 inline FieldDef::DescriptorType FieldDef::descriptor_type() const { 3121 return upb_fielddef_descriptortype(this); 3122 } 3123 inline FieldDef::Label FieldDef::label() const { 3124 return upb_fielddef_label(this); 3125 } 3126 inline uint32_t FieldDef::number() const { return upb_fielddef_number(this); } 3127 inline const char* FieldDef::name() const { return upb_fielddef_name(this); } 3128 inline bool FieldDef::is_extension() const { 3129 return upb_fielddef_isextension(this); 3130 } 3131 inline size_t FieldDef::GetJsonName(char* buf, size_t len) const { 3132 return upb_fielddef_getjsonname(this, buf, len); 3133 } 3134 inline bool FieldDef::lazy() const { 3135 return upb_fielddef_lazy(this); 3136 } 3137 inline void FieldDef::set_lazy(bool lazy) { 3138 upb_fielddef_setlazy(this, lazy); 3139 } 3140 inline bool FieldDef::packed() const { 3141 return upb_fielddef_packed(this); 3142 } 3143 inline uint32_t FieldDef::index() const { 3144 return upb_fielddef_index(this); 3145 } 3146 inline void FieldDef::set_packed(bool packed) { 3147 upb_fielddef_setpacked(this, packed); 3148 } 3149 inline const MessageDef* FieldDef::containing_type() const { 3150 return upb_fielddef_containingtype(this); 3151 } 3152 inline const OneofDef* FieldDef::containing_oneof() const { 3153 return upb_fielddef_containingoneof(this); 3154 } 3155 inline const char* FieldDef::containing_type_name() { 3156 return upb_fielddef_containingtypename(this); 3157 } 3158 inline bool FieldDef::set_number(uint32_t number, Status* s) { 3159 return upb_fielddef_setnumber(this, number, s); 3160 } 3161 inline bool FieldDef::set_name(const char *name, Status* s) { 3162 return upb_fielddef_setname(this, name, s); 3163 } 3164 inline bool FieldDef::set_name(const std::string& name, Status* s) { 3165 return upb_fielddef_setname(this, upb_safecstr(name), s); 3166 } 3167 inline bool FieldDef::set_json_name(const char *name, Status* s) { 3168 return upb_fielddef_setjsonname(this, name, s); 3169 } 3170 inline bool FieldDef::set_json_name(const std::string& name, Status* s) { 3171 return upb_fielddef_setjsonname(this, upb_safecstr(name), s); 3172 } 3173 inline void FieldDef::clear_json_name() { 3174 upb_fielddef_clearjsonname(this); 3175 } 3176 inline bool FieldDef::set_containing_type_name(const char *name, Status* s) { 3177 return upb_fielddef_setcontainingtypename(this, name, s); 3178 } 3179 inline bool FieldDef::set_containing_type_name(const std::string &name, 3180 Status *s) { 3181 return upb_fielddef_setcontainingtypename(this, upb_safecstr(name), s); 3182 } 3183 inline void FieldDef::set_type(upb_fieldtype_t type) { 3184 upb_fielddef_settype(this, type); 3185 } 3186 inline void FieldDef::set_is_extension(bool is_extension) { 3187 upb_fielddef_setisextension(this, is_extension); 3188 } 3189 inline void FieldDef::set_descriptor_type(FieldDef::DescriptorType type) { 3190 upb_fielddef_setdescriptortype(this, type); 3191 } 3192 inline void FieldDef::set_label(upb_label_t label) { 3193 upb_fielddef_setlabel(this, label); 3194 } 3195 inline bool FieldDef::IsSubMessage() const { 3196 return upb_fielddef_issubmsg(this); 3197 } 3198 inline bool FieldDef::IsString() const { return upb_fielddef_isstring(this); } 3199 inline bool FieldDef::IsSequence() const { return upb_fielddef_isseq(this); } 3200 inline bool FieldDef::IsMap() const { return upb_fielddef_ismap(this); } 3201 inline int64_t FieldDef::default_int64() const { 3202 return upb_fielddef_defaultint64(this); 3203 } 3204 inline int32_t FieldDef::default_int32() const { 3205 return upb_fielddef_defaultint32(this); 3206 } 3207 inline uint64_t FieldDef::default_uint64() const { 3208 return upb_fielddef_defaultuint64(this); 3209 } 3210 inline uint32_t FieldDef::default_uint32() const { 3211 return upb_fielddef_defaultuint32(this); 3212 } 3213 inline bool FieldDef::default_bool() const { 3214 return upb_fielddef_defaultbool(this); 3215 } 3216 inline float FieldDef::default_float() const { 3217 return upb_fielddef_defaultfloat(this); 3218 } 3219 inline double FieldDef::default_double() const { 3220 return upb_fielddef_defaultdouble(this); 3221 } 3222 inline const char* FieldDef::default_string(size_t* len) const { 3223 return upb_fielddef_defaultstr(this, len); 3224 } 3225 inline void FieldDef::set_default_int64(int64_t value) { 3226 upb_fielddef_setdefaultint64(this, value); 3227 } 3228 inline void FieldDef::set_default_int32(int32_t value) { 3229 upb_fielddef_setdefaultint32(this, value); 3230 } 3231 inline void FieldDef::set_default_uint64(uint64_t value) { 3232 upb_fielddef_setdefaultuint64(this, value); 3233 } 3234 inline void FieldDef::set_default_uint32(uint32_t value) { 3235 upb_fielddef_setdefaultuint32(this, value); 3236 } 3237 inline void FieldDef::set_default_bool(bool value) { 3238 upb_fielddef_setdefaultbool(this, value); 3239 } 3240 inline void FieldDef::set_default_float(float value) { 3241 upb_fielddef_setdefaultfloat(this, value); 3242 } 3243 inline void FieldDef::set_default_double(double value) { 3244 upb_fielddef_setdefaultdouble(this, value); 3245 } 3246 inline bool FieldDef::set_default_string(const void *str, size_t len, 3247 Status *s) { 3248 return upb_fielddef_setdefaultstr(this, str, len, s); 3249 } 3250 inline bool FieldDef::set_default_string(const std::string& str, Status* s) { 3251 return upb_fielddef_setdefaultstr(this, str.c_str(), str.size(), s); 3252 } 3253 inline void FieldDef::set_default_cstr(const char* str, Status* s) { 3254 return upb_fielddef_setdefaultcstr(this, str, s); 3255 } 3256 inline bool FieldDef::HasSubDef() const { return upb_fielddef_hassubdef(this); } 3257 inline const Def* FieldDef::subdef() const { return upb_fielddef_subdef(this); } 3258 inline const MessageDef *FieldDef::message_subdef() const { 3259 return upb_fielddef_msgsubdef(this); 3260 } 3261 inline const EnumDef *FieldDef::enum_subdef() const { 3262 return upb_fielddef_enumsubdef(this); 3263 } 3264 inline const char* FieldDef::subdef_name() const { 3265 return upb_fielddef_subdefname(this); 3266 } 3267 inline bool FieldDef::set_subdef(const Def* subdef, Status* s) { 3268 return upb_fielddef_setsubdef(this, subdef, s); 3269 } 3270 inline bool FieldDef::set_enum_subdef(const EnumDef* subdef, Status* s) { 3271 return upb_fielddef_setenumsubdef(this, subdef, s); 3272 } 3273 inline bool FieldDef::set_message_subdef(const MessageDef* subdef, Status* s) { 3274 return upb_fielddef_setmsgsubdef(this, subdef, s); 3275 } 3276 inline bool FieldDef::set_subdef_name(const char* name, Status* s) { 3277 return upb_fielddef_setsubdefname(this, name, s); 3278 } 3279 inline bool FieldDef::set_subdef_name(const std::string& name, Status* s) { 3280 return upb_fielddef_setsubdefname(this, upb_safecstr(name), s); 3281 } 3282 3283 inline reffed_ptr<MessageDef> MessageDef::New() { 3284 upb_msgdef *m = upb_msgdef_new(&m); 3285 return reffed_ptr<MessageDef>(m, &m); 3286 } 3287 inline const char *MessageDef::full_name() const { 3288 return upb_msgdef_fullname(this); 3289 } 3290 inline const char *MessageDef::name() const { 3291 return upb_msgdef_name(this); 3292 } 3293 inline upb_syntax_t MessageDef::syntax() const { 3294 return upb_msgdef_syntax(this); 3295 } 3296 inline bool MessageDef::set_full_name(const char* fullname, Status* s) { 3297 return upb_msgdef_setfullname(this, fullname, s); 3298 } 3299 inline bool MessageDef::set_full_name(const std::string& fullname, Status* s) { 3300 return upb_msgdef_setfullname(this, upb_safecstr(fullname), s); 3301 } 3302 inline bool MessageDef::set_syntax(upb_syntax_t syntax) { 3303 return upb_msgdef_setsyntax(this, syntax); 3304 } 3305 inline bool MessageDef::Freeze(Status* status) { 3306 return upb_msgdef_freeze(this, status); 3307 } 3308 inline int MessageDef::field_count() const { 3309 return upb_msgdef_numfields(this); 3310 } 3311 inline int MessageDef::oneof_count() const { 3312 return upb_msgdef_numoneofs(this); 3313 } 3314 inline bool MessageDef::AddField(upb_fielddef* f, Status* s) { 3315 return upb_msgdef_addfield(this, f, NULL, s); 3316 } 3317 inline bool MessageDef::AddField(const reffed_ptr<FieldDef>& f, Status* s) { 3318 return upb_msgdef_addfield(this, f.get(), NULL, s); 3319 } 3320 inline bool MessageDef::AddOneof(upb_oneofdef* o, Status* s) { 3321 return upb_msgdef_addoneof(this, o, NULL, s); 3322 } 3323 inline bool MessageDef::AddOneof(const reffed_ptr<OneofDef>& o, Status* s) { 3324 return upb_msgdef_addoneof(this, o.get(), NULL, s); 3325 } 3326 inline FieldDef* MessageDef::FindFieldByNumber(uint32_t number) { 3327 return upb_msgdef_itof_mutable(this, number); 3328 } 3329 inline FieldDef* MessageDef::FindFieldByName(const char* name, size_t len) { 3330 return upb_msgdef_ntof_mutable(this, name, len); 3331 } 3332 inline const FieldDef* MessageDef::FindFieldByNumber(uint32_t number) const { 3333 return upb_msgdef_itof(this, number); 3334 } 3335 inline const FieldDef *MessageDef::FindFieldByName(const char *name, 3336 size_t len) const { 3337 return upb_msgdef_ntof(this, name, len); 3338 } 3339 inline OneofDef* MessageDef::FindOneofByName(const char* name, size_t len) { 3340 return upb_msgdef_ntoo_mutable(this, name, len); 3341 } 3342 inline const OneofDef* MessageDef::FindOneofByName(const char* name, 3343 size_t len) const { 3344 return upb_msgdef_ntoo(this, name, len); 3345 } 3346 inline MessageDef* MessageDef::Dup(const void *owner) const { 3347 return upb_msgdef_dup(this, owner); 3348 } 3349 inline void MessageDef::setmapentry(bool map_entry) { 3350 upb_msgdef_setmapentry(this, map_entry); 3351 } 3352 inline bool MessageDef::mapentry() const { 3353 return upb_msgdef_mapentry(this); 3354 } 3355 inline MessageDef::field_iterator MessageDef::field_begin() { 3356 return field_iterator(this); 3357 } 3358 inline MessageDef::field_iterator MessageDef::field_end() { 3359 return field_iterator::end(this); 3360 } 3361 inline MessageDef::const_field_iterator MessageDef::field_begin() const { 3362 return const_field_iterator(this); 3363 } 3364 inline MessageDef::const_field_iterator MessageDef::field_end() const { 3365 return const_field_iterator::end(this); 3366 } 3367 3368 inline MessageDef::oneof_iterator MessageDef::oneof_begin() { 3369 return oneof_iterator(this); 3370 } 3371 inline MessageDef::oneof_iterator MessageDef::oneof_end() { 3372 return oneof_iterator::end(this); 3373 } 3374 inline MessageDef::const_oneof_iterator MessageDef::oneof_begin() const { 3375 return const_oneof_iterator(this); 3376 } 3377 inline MessageDef::const_oneof_iterator MessageDef::oneof_end() const { 3378 return const_oneof_iterator::end(this); 3379 } 3380 3381 inline MessageDef::field_iterator::field_iterator(MessageDef* md) { 3382 upb_msg_field_begin(&iter_, md); 3383 } 3384 inline MessageDef::field_iterator MessageDef::field_iterator::end( 3385 MessageDef* md) { 3386 MessageDef::field_iterator iter(md); 3387 upb_msg_field_iter_setdone(&iter.iter_); 3388 return iter; 3389 } 3390 inline FieldDef* MessageDef::field_iterator::operator*() const { 3391 return upb_msg_iter_field(&iter_); 3392 } 3393 inline void MessageDef::field_iterator::operator++() { 3394 return upb_msg_field_next(&iter_); 3395 } 3396 inline bool MessageDef::field_iterator::operator==( 3397 const field_iterator &other) const { 3398 return upb_inttable_iter_isequal(&iter_, &other.iter_); 3399 } 3400 inline bool MessageDef::field_iterator::operator!=( 3401 const field_iterator &other) const { 3402 return !(*this == other); 3403 } 3404 3405 inline MessageDef::const_field_iterator::const_field_iterator( 3406 const MessageDef* md) { 3407 upb_msg_field_begin(&iter_, md); 3408 } 3409 inline MessageDef::const_field_iterator MessageDef::const_field_iterator::end( 3410 const MessageDef *md) { 3411 MessageDef::const_field_iterator iter(md); 3412 upb_msg_field_iter_setdone(&iter.iter_); 3413 return iter; 3414 } 3415 inline const FieldDef* MessageDef::const_field_iterator::operator*() const { 3416 return upb_msg_iter_field(&iter_); 3417 } 3418 inline void MessageDef::const_field_iterator::operator++() { 3419 return upb_msg_field_next(&iter_); 3420 } 3421 inline bool MessageDef::const_field_iterator::operator==( 3422 const const_field_iterator &other) const { 3423 return upb_inttable_iter_isequal(&iter_, &other.iter_); 3424 } 3425 inline bool MessageDef::const_field_iterator::operator!=( 3426 const const_field_iterator &other) const { 3427 return !(*this == other); 3428 } 3429 3430 inline MessageDef::oneof_iterator::oneof_iterator(MessageDef* md) { 3431 upb_msg_oneof_begin(&iter_, md); 3432 } 3433 inline MessageDef::oneof_iterator MessageDef::oneof_iterator::end( 3434 MessageDef* md) { 3435 MessageDef::oneof_iterator iter(md); 3436 upb_msg_oneof_iter_setdone(&iter.iter_); 3437 return iter; 3438 } 3439 inline OneofDef* MessageDef::oneof_iterator::operator*() const { 3440 return upb_msg_iter_oneof(&iter_); 3441 } 3442 inline void MessageDef::oneof_iterator::operator++() { 3443 return upb_msg_oneof_next(&iter_); 3444 } 3445 inline bool MessageDef::oneof_iterator::operator==( 3446 const oneof_iterator &other) const { 3447 return upb_strtable_iter_isequal(&iter_, &other.iter_); 3448 } 3449 inline bool MessageDef::oneof_iterator::operator!=( 3450 const oneof_iterator &other) const { 3451 return !(*this == other); 3452 } 3453 3454 inline MessageDef::const_oneof_iterator::const_oneof_iterator( 3455 const MessageDef* md) { 3456 upb_msg_oneof_begin(&iter_, md); 3457 } 3458 inline MessageDef::const_oneof_iterator MessageDef::const_oneof_iterator::end( 3459 const MessageDef *md) { 3460 MessageDef::const_oneof_iterator iter(md); 3461 upb_msg_oneof_iter_setdone(&iter.iter_); 3462 return iter; 3463 } 3464 inline const OneofDef* MessageDef::const_oneof_iterator::operator*() const { 3465 return upb_msg_iter_oneof(&iter_); 3466 } 3467 inline void MessageDef::const_oneof_iterator::operator++() { 3468 return upb_msg_oneof_next(&iter_); 3469 } 3470 inline bool MessageDef::const_oneof_iterator::operator==( 3471 const const_oneof_iterator &other) const { 3472 return upb_strtable_iter_isequal(&iter_, &other.iter_); 3473 } 3474 inline bool MessageDef::const_oneof_iterator::operator!=( 3475 const const_oneof_iterator &other) const { 3476 return !(*this == other); 3477 } 3478 3479 inline reffed_ptr<EnumDef> EnumDef::New() { 3480 upb_enumdef *e = upb_enumdef_new(&e); 3481 return reffed_ptr<EnumDef>(e, &e); 3482 } 3483 inline const char* EnumDef::full_name() const { 3484 return upb_enumdef_fullname(this); 3485 } 3486 inline const char* EnumDef::name() const { 3487 return upb_enumdef_name(this); 3488 } 3489 inline bool EnumDef::set_full_name(const char* fullname, Status* s) { 3490 return upb_enumdef_setfullname(this, fullname, s); 3491 } 3492 inline bool EnumDef::set_full_name(const std::string& fullname, Status* s) { 3493 return upb_enumdef_setfullname(this, upb_safecstr(fullname), s); 3494 } 3495 inline bool EnumDef::Freeze(Status* status) { 3496 return upb_enumdef_freeze(this, status); 3497 } 3498 inline int32_t EnumDef::default_value() const { 3499 return upb_enumdef_default(this); 3500 } 3501 inline bool EnumDef::set_default_value(int32_t val, Status* status) { 3502 return upb_enumdef_setdefault(this, val, status); 3503 } 3504 inline int EnumDef::value_count() const { return upb_enumdef_numvals(this); } 3505 inline bool EnumDef::AddValue(const char* name, int32_t num, Status* status) { 3506 return upb_enumdef_addval(this, name, num, status); 3507 } 3508 inline bool EnumDef::AddValue(const std::string& name, int32_t num, 3509 Status* status) { 3510 return upb_enumdef_addval(this, upb_safecstr(name), num, status); 3511 } 3512 inline bool EnumDef::FindValueByName(const char* name, int32_t *num) const { 3513 return upb_enumdef_ntoiz(this, name, num); 3514 } 3515 inline const char* EnumDef::FindValueByNumber(int32_t num) const { 3516 return upb_enumdef_iton(this, num); 3517 } 3518 inline EnumDef* EnumDef::Dup(const void* owner) const { 3519 return upb_enumdef_dup(this, owner); 3520 } 3521 3522 inline EnumDef::Iterator::Iterator(const EnumDef* e) { 3523 upb_enum_begin(&iter_, e); 3524 } 3525 inline int32_t EnumDef::Iterator::number() { 3526 return upb_enum_iter_number(&iter_); 3527 } 3528 inline const char* EnumDef::Iterator::name() { 3529 return upb_enum_iter_name(&iter_); 3530 } 3531 inline bool EnumDef::Iterator::Done() { return upb_enum_done(&iter_); } 3532 inline void EnumDef::Iterator::Next() { return upb_enum_next(&iter_); } 3533 3534 inline reffed_ptr<OneofDef> OneofDef::New() { 3535 upb_oneofdef *o = upb_oneofdef_new(&o); 3536 return reffed_ptr<OneofDef>(o, &o); 3537 } 3538 3539 inline const MessageDef* OneofDef::containing_type() const { 3540 return upb_oneofdef_containingtype(this); 3541 } 3542 inline const char* OneofDef::name() const { 3543 return upb_oneofdef_name(this); 3544 } 3545 inline bool OneofDef::set_name(const char* name, Status* s) { 3546 return upb_oneofdef_setname(this, name, s); 3547 } 3548 inline bool OneofDef::set_name(const std::string& name, Status* s) { 3549 return upb_oneofdef_setname(this, upb_safecstr(name), s); 3550 } 3551 inline int OneofDef::field_count() const { 3552 return upb_oneofdef_numfields(this); 3553 } 3554 inline bool OneofDef::AddField(FieldDef* field, Status* s) { 3555 return upb_oneofdef_addfield(this, field, NULL, s); 3556 } 3557 inline bool OneofDef::AddField(const reffed_ptr<FieldDef>& field, Status* s) { 3558 return upb_oneofdef_addfield(this, field.get(), NULL, s); 3559 } 3560 inline const FieldDef* OneofDef::FindFieldByName(const char* name, 3561 size_t len) const { 3562 return upb_oneofdef_ntof(this, name, len); 3563 } 3564 inline const FieldDef* OneofDef::FindFieldByNumber(uint32_t num) const { 3565 return upb_oneofdef_itof(this, num); 3566 } 3567 inline OneofDef::iterator OneofDef::begin() { return iterator(this); } 3568 inline OneofDef::iterator OneofDef::end() { return iterator::end(this); } 3569 inline OneofDef::const_iterator OneofDef::begin() const { 3570 return const_iterator(this); 3571 } 3572 inline OneofDef::const_iterator OneofDef::end() const { 3573 return const_iterator::end(this); 3574 } 3575 3576 inline OneofDef::iterator::iterator(OneofDef* o) { 3577 upb_oneof_begin(&iter_, o); 3578 } 3579 inline OneofDef::iterator OneofDef::iterator::end(OneofDef* o) { 3580 OneofDef::iterator iter(o); 3581 upb_oneof_iter_setdone(&iter.iter_); 3582 return iter; 3583 } 3584 inline FieldDef* OneofDef::iterator::operator*() const { 3585 return upb_oneof_iter_field(&iter_); 3586 } 3587 inline void OneofDef::iterator::operator++() { return upb_oneof_next(&iter_); } 3588 inline bool OneofDef::iterator::operator==(const iterator &other) const { 3589 return upb_inttable_iter_isequal(&iter_, &other.iter_); 3590 } 3591 inline bool OneofDef::iterator::operator!=(const iterator &other) const { 3592 return !(*this == other); 3593 } 3594 3595 inline OneofDef::const_iterator::const_iterator(const OneofDef* md) { 3596 upb_oneof_begin(&iter_, md); 3597 } 3598 inline OneofDef::const_iterator OneofDef::const_iterator::end( 3599 const OneofDef *md) { 3600 OneofDef::const_iterator iter(md); 3601 upb_oneof_iter_setdone(&iter.iter_); 3602 return iter; 3603 } 3604 inline const FieldDef* OneofDef::const_iterator::operator*() const { 3605 return upb_msg_iter_field(&iter_); 3606 } 3607 inline void OneofDef::const_iterator::operator++() { 3608 return upb_oneof_next(&iter_); 3609 } 3610 inline bool OneofDef::const_iterator::operator==( 3611 const const_iterator &other) const { 3612 return upb_inttable_iter_isequal(&iter_, &other.iter_); 3613 } 3614 inline bool OneofDef::const_iterator::operator!=( 3615 const const_iterator &other) const { 3616 return !(*this == other); 3617 } 3618 3619 inline reffed_ptr<FileDef> FileDef::New() { 3620 upb_filedef *f = upb_filedef_new(&f); 3621 return reffed_ptr<FileDef>(f, &f); 3622 } 3623 3624 inline const char* FileDef::name() const { 3625 return upb_filedef_name(this); 3626 } 3627 inline bool FileDef::set_name(const char* name, Status* s) { 3628 return upb_filedef_setname(this, name, s); 3629 } 3630 inline bool FileDef::set_name(const std::string& name, Status* s) { 3631 return upb_filedef_setname(this, upb_safecstr(name), s); 3632 } 3633 inline const char* FileDef::package() const { 3634 return upb_filedef_package(this); 3635 } 3636 inline bool FileDef::set_package(const char* package, Status* s) { 3637 return upb_filedef_setpackage(this, package, s); 3638 } 3639 inline int FileDef::def_count() const { 3640 return upb_filedef_defcount(this); 3641 } 3642 inline const Def* FileDef::def(int index) const { 3643 return upb_filedef_def(this, index); 3644 } 3645 inline Def* FileDef::def(int index) { 3646 return const_cast<Def*>(upb_filedef_def(this, index)); 3647 } 3648 inline int FileDef::dependency_count() const { 3649 return upb_filedef_depcount(this); 3650 } 3651 inline const FileDef* FileDef::dependency(int index) const { 3652 return upb_filedef_dep(this, index); 3653 } 3654 inline bool FileDef::AddDef(Def* def, Status* s) { 3655 return upb_filedef_adddef(this, def, NULL, s); 3656 } 3657 inline bool FileDef::AddMessage(MessageDef* m, Status* s) { 3658 return upb_filedef_addmsg(this, m, NULL, s); 3659 } 3660 inline bool FileDef::AddEnum(EnumDef* e, Status* s) { 3661 return upb_filedef_addenum(this, e, NULL, s); 3662 } 3663 inline bool FileDef::AddExtension(FieldDef* f, Status* s) { 3664 return upb_filedef_addext(this, f, NULL, s); 3665 } 3666 inline bool FileDef::AddDependency(const FileDef* file) { 3667 return upb_filedef_adddep(this, file); 3668 } 3669 3670 } /* namespace upb */ 3671 #endif 3672 3673 #endif /* UPB_DEF_H_ */ 3674 /* 3675 ** This file contains definitions of structs that should be considered private 3676 ** and NOT stable across versions of upb. 3677 ** 3678 ** The only reason they are declared here and not in .c files is to allow upb 3679 ** and the application (if desired) to embed statically-initialized instances 3680 ** of structures like defs. 3681 ** 3682 ** If you include this file, all guarantees of ABI compatibility go out the 3683 ** window! Any code that includes this file needs to recompile against the 3684 ** exact same version of upb that they are linking against. 3685 ** 3686 ** You also need to recompile if you change the value of the UPB_DEBUG_REFS 3687 ** flag. 3688 */ 3689 3690 3691 #ifndef UPB_STATICINIT_H_ 3692 #define UPB_STATICINIT_H_ 3693 3694 #ifdef __cplusplus 3695 /* Because of how we do our typedefs, this header can't be included from C++. */ 3696 #error This file cannot be included from C++ 3697 #endif 3698 3699 /* upb_refcounted *************************************************************/ 3700 3701 3702 /* upb_def ********************************************************************/ 3703 3704 struct upb_def { 3705 upb_refcounted base; 3706 3707 const char *fullname; 3708 const upb_filedef* file; 3709 char type; /* A upb_deftype_t (char to save space) */ 3710 3711 /* Used as a flag during the def's mutable stage. Must be false unless 3712 * it is currently being used by a function on the stack. This allows 3713 * us to easily determine which defs were passed into the function's 3714 * current invocation. */ 3715 bool came_from_user; 3716 }; 3717 3718 #define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \ 3719 { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false } 3720 3721 3722 /* upb_fielddef ***************************************************************/ 3723 3724 struct upb_fielddef { 3725 upb_def base; 3726 3727 union { 3728 int64_t sint; 3729 uint64_t uint; 3730 double dbl; 3731 float flt; 3732 void *bytes; 3733 } defaultval; 3734 union { 3735 const upb_msgdef *def; /* If !msg_is_symbolic. */ 3736 char *name; /* If msg_is_symbolic. */ 3737 } msg; 3738 union { 3739 const upb_def *def; /* If !subdef_is_symbolic. */ 3740 char *name; /* If subdef_is_symbolic. */ 3741 } sub; /* The msgdef or enumdef for this field, if upb_hassubdef(f). */ 3742 bool subdef_is_symbolic; 3743 bool msg_is_symbolic; 3744 const upb_oneofdef *oneof; 3745 bool default_is_string; 3746 bool type_is_set_; /* False until type is explicitly set. */ 3747 bool is_extension_; 3748 bool lazy_; 3749 bool packed_; 3750 upb_intfmt_t intfmt; 3751 bool tagdelim; 3752 upb_fieldtype_t type_; 3753 upb_label_t label_; 3754 uint32_t number_; 3755 uint32_t selector_base; /* Used to index into a upb::Handlers table. */ 3756 uint32_t index_; 3757 }; 3758 3759 extern const struct upb_refcounted_vtbl upb_fielddef_vtbl; 3760 3761 #define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \ 3762 packed, name, num, msgdef, subdef, selector_base, \ 3763 index, defaultval, refs, ref2s) \ 3764 { \ 3765 UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \ 3766 defaultval, {msgdef}, {subdef}, NULL, false, false, \ 3767 type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \ 3768 lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \ 3769 } 3770 3771 3772 /* upb_msgdef *****************************************************************/ 3773 3774 struct upb_msgdef { 3775 upb_def base; 3776 3777 size_t selector_count; 3778 uint32_t submsg_field_count; 3779 3780 /* Tables for looking up fields by number and name. */ 3781 upb_inttable itof; /* int to field */ 3782 upb_strtable ntof; /* name to field/oneof */ 3783 3784 /* Is this a map-entry message? */ 3785 bool map_entry; 3786 3787 /* Whether this message has proto2 or proto3 semantics. */ 3788 upb_syntax_t syntax; 3789 3790 /* TODO(haberman): proper extension ranges (there can be multiple). */ 3791 }; 3792 3793 extern const struct upb_refcounted_vtbl upb_msgdef_vtbl; 3794 3795 /* TODO: also support static initialization of the oneofs table. This will be 3796 * needed if we compile in descriptors that contain oneofs. */ 3797 #define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \ 3798 map_entry, syntax, refs, ref2s) \ 3799 { \ 3800 UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \ 3801 selector_count, submsg_field_count, itof, ntof, map_entry, syntax \ 3802 } 3803 3804 3805 /* upb_enumdef ****************************************************************/ 3806 3807 struct upb_enumdef { 3808 upb_def base; 3809 3810 upb_strtable ntoi; 3811 upb_inttable iton; 3812 int32_t defaultval; 3813 }; 3814 3815 extern const struct upb_refcounted_vtbl upb_enumdef_vtbl; 3816 3817 #define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \ 3818 { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \ 3819 iton, defaultval } 3820 3821 3822 /* upb_oneofdef ***************************************************************/ 3823 3824 struct upb_oneofdef { 3825 upb_refcounted base; 3826 3827 const char *name; 3828 upb_strtable ntof; 3829 upb_inttable itof; 3830 const upb_msgdef *parent; 3831 }; 3832 3833 extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl; 3834 3835 #define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \ 3836 { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), name, ntof, itof } 3837 3838 3839 /* upb_symtab *****************************************************************/ 3840 3841 struct upb_symtab { 3842 upb_refcounted base; 3843 3844 upb_strtable symtab; 3845 }; 3846 3847 struct upb_filedef { 3848 upb_refcounted base; 3849 3850 const char *name; 3851 const char *package; 3852 upb_syntax_t syntax; 3853 3854 upb_inttable defs; 3855 upb_inttable deps; 3856 }; 3857 3858 extern const struct upb_refcounted_vtbl upb_filedef_vtbl; 3859 3860 #endif /* UPB_STATICINIT_H_ */ 3861 /* 3862 ** upb::Handlers (upb_handlers) 3863 ** 3864 ** A upb_handlers is like a virtual table for a upb_msgdef. Each field of the 3865 ** message can have associated functions that will be called when we are 3866 ** parsing or visiting a stream of data. This is similar to how handlers work 3867 ** in SAX (the Simple API for XML). 3868 ** 3869 ** The handlers have no idea where the data is coming from, so a single set of 3870 ** handlers could be used with two completely different data sources (for 3871 ** example, a parser and a visitor over in-memory objects). This decoupling is 3872 ** the most important feature of upb, because it allows parsers and serializers 3873 ** to be highly reusable. 3874 ** 3875 ** This is a mixed C/C++ interface that offers a full API to both languages. 3876 ** See the top-level README for more information. 3877 */ 3878 3879 #ifndef UPB_HANDLERS_H 3880 #define UPB_HANDLERS_H 3881 3882 3883 #ifdef __cplusplus 3884 namespace upb { 3885 class BufferHandle; 3886 class BytesHandler; 3887 class HandlerAttributes; 3888 class Handlers; 3889 template <class T> class Handler; 3890 template <class T> struct CanonicalType; 3891 } /* namespace upb */ 3892 #endif 3893 3894 UPB_DECLARE_TYPE(upb::BufferHandle, upb_bufhandle) 3895 UPB_DECLARE_TYPE(upb::BytesHandler, upb_byteshandler) 3896 UPB_DECLARE_TYPE(upb::HandlerAttributes, upb_handlerattr) 3897 UPB_DECLARE_DERIVED_TYPE(upb::Handlers, upb::RefCounted, 3898 upb_handlers, upb_refcounted) 3899 3900 /* The maximum depth that the handler graph can have. This is a resource limit 3901 * for the C stack since we sometimes need to recursively traverse the graph. 3902 * Cycles are ok; the traversal will stop when it detects a cycle, but we must 3903 * hit the cycle before the maximum depth is reached. 3904 * 3905 * If having a single static limit is too inflexible, we can add another variant 3906 * of Handlers::Freeze that allows specifying this as a parameter. */ 3907 #define UPB_MAX_HANDLER_DEPTH 64 3908 3909 /* All the different types of handlers that can be registered. 3910 * Only needed for the advanced functions in upb::Handlers. */ 3911 typedef enum { 3912 UPB_HANDLER_INT32, 3913 UPB_HANDLER_INT64, 3914 UPB_HANDLER_UINT32, 3915 UPB_HANDLER_UINT64, 3916 UPB_HANDLER_FLOAT, 3917 UPB_HANDLER_DOUBLE, 3918 UPB_HANDLER_BOOL, 3919 UPB_HANDLER_STARTSTR, 3920 UPB_HANDLER_STRING, 3921 UPB_HANDLER_ENDSTR, 3922 UPB_HANDLER_STARTSUBMSG, 3923 UPB_HANDLER_ENDSUBMSG, 3924 UPB_HANDLER_STARTSEQ, 3925 UPB_HANDLER_ENDSEQ 3926 } upb_handlertype_t; 3927 3928 #define UPB_HANDLER_MAX (UPB_HANDLER_ENDSEQ+1) 3929 3930 #define UPB_BREAK NULL 3931 3932 /* A convenient definition for when no closure is needed. */ 3933 extern char _upb_noclosure; 3934 #define UPB_NO_CLOSURE &_upb_noclosure 3935 3936 /* A selector refers to a specific field handler in the Handlers object 3937 * (for example: the STARTSUBMSG handler for field "field15"). */ 3938 typedef int32_t upb_selector_t; 3939 3940 UPB_BEGIN_EXTERN_C 3941 3942 /* Forward-declares for C inline accessors. We need to declare these here 3943 * so we can "friend" them in the class declarations in C++. */ 3944 UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h, 3945 upb_selector_t s); 3946 UPB_INLINE const void *upb_handlerattr_handlerdata(const upb_handlerattr *attr); 3947 UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h, 3948 upb_selector_t s); 3949 3950 UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h); 3951 UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj, 3952 const void *type); 3953 UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf, 3954 size_t ofs); 3955 UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h); 3956 UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h); 3957 UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h); 3958 3959 UPB_END_EXTERN_C 3960 3961 3962 /* Static selectors for upb::Handlers. */ 3963 #define UPB_STARTMSG_SELECTOR 0 3964 #define UPB_ENDMSG_SELECTOR 1 3965 #define UPB_STATIC_SELECTOR_COUNT 2 3966 3967 /* Static selectors for upb::BytesHandler. */ 3968 #define UPB_STARTSTR_SELECTOR 0 3969 #define UPB_STRING_SELECTOR 1 3970 #define UPB_ENDSTR_SELECTOR 2 3971 3972 typedef void upb_handlerfree(void *d); 3973 3974 #ifdef __cplusplus 3975 3976 /* A set of attributes that accompanies a handler's function pointer. */ 3977 class upb::HandlerAttributes { 3978 public: 3979 HandlerAttributes(); 3980 ~HandlerAttributes(); 3981 3982 /* Sets the handler data that will be passed as the second parameter of the 3983 * handler. To free this pointer when the handlers are freed, call 3984 * Handlers::AddCleanup(). */ 3985 bool SetHandlerData(const void *handler_data); 3986 const void* handler_data() const; 3987 3988 /* Use this to specify the type of the closure. This will be checked against 3989 * all other closure types for handler that use the same closure. 3990 * Registration will fail if this does not match all other non-NULL closure 3991 * types. */ 3992 bool SetClosureType(const void *closure_type); 3993 const void* closure_type() const; 3994 3995 /* Use this to specify the type of the returned closure. Only used for 3996 * Start*{String,SubMessage,Sequence} handlers. This must match the closure 3997 * type of any handlers that use it (for example, the StringBuf handler must 3998 * match the closure returned from StartString). */ 3999 bool SetReturnClosureType(const void *return_closure_type); 4000 const void* return_closure_type() const; 4001 4002 /* Set to indicate that the handler always returns "ok" (either "true" or a 4003 * non-NULL closure). This is a hint that can allow code generators to 4004 * generate more efficient code. */ 4005 bool SetAlwaysOk(bool always_ok); 4006 bool always_ok() const; 4007 4008 private: 4009 friend UPB_INLINE const void * ::upb_handlerattr_handlerdata( 4010 const upb_handlerattr *attr); 4011 #else 4012 struct upb_handlerattr { 4013 #endif 4014 const void *handler_data_; 4015 const void *closure_type_; 4016 const void *return_closure_type_; 4017 bool alwaysok_; 4018 }; 4019 4020 #define UPB_HANDLERATTR_INITIALIZER {NULL, NULL, NULL, false} 4021 4022 typedef struct { 4023 upb_func *func; 4024 4025 /* It is wasteful to include the entire attributes here: 4026 * 4027 * * Some of the information is redundant (like storing the closure type 4028 * separately for each handler that must match). 4029 * * Some of the info is only needed prior to freeze() (like closure types). 4030 * * alignment padding wastes a lot of space for alwaysok_. 4031 * 4032 * If/when the size and locality of handlers is an issue, we can optimize this 4033 * not to store the entire attr like this. We do not expose the table's 4034 * layout to allow this optimization in the future. */ 4035 upb_handlerattr attr; 4036 } upb_handlers_tabent; 4037 4038 #ifdef __cplusplus 4039 4040 /* Extra information about a buffer that is passed to a StringBuf handler. 4041 * TODO(haberman): allow the handle to be pinned so that it will outlive 4042 * the handler invocation. */ 4043 class upb::BufferHandle { 4044 public: 4045 BufferHandle(); 4046 ~BufferHandle(); 4047 4048 /* The beginning of the buffer. This may be different than the pointer 4049 * passed to a StringBuf handler because the handler may receive data 4050 * that is from the middle or end of a larger buffer. */ 4051 const char* buffer() const; 4052 4053 /* The offset within the attached object where this buffer begins. Only 4054 * meaningful if there is an attached object. */ 4055 size_t object_offset() const; 4056 4057 /* Note that object_offset is the offset of "buf" within the attached 4058 * object. */ 4059 void SetBuffer(const char* buf, size_t object_offset); 4060 4061 /* The BufferHandle can have an "attached object", which can be used to 4062 * tunnel through a pointer to the buffer's underlying representation. */ 4063 template <class T> 4064 void SetAttachedObject(const T* obj); 4065 4066 /* Returns NULL if the attached object is not of this type. */ 4067 template <class T> 4068 const T* GetAttachedObject() const; 4069 4070 private: 4071 friend UPB_INLINE void ::upb_bufhandle_init(upb_bufhandle *h); 4072 friend UPB_INLINE void ::upb_bufhandle_setobj(upb_bufhandle *h, 4073 const void *obj, 4074 const void *type); 4075 friend UPB_INLINE void ::upb_bufhandle_setbuf(upb_bufhandle *h, 4076 const char *buf, size_t ofs); 4077 friend UPB_INLINE const void* ::upb_bufhandle_obj(const upb_bufhandle *h); 4078 friend UPB_INLINE const void* ::upb_bufhandle_objtype( 4079 const upb_bufhandle *h); 4080 friend UPB_INLINE const char* ::upb_bufhandle_buf(const upb_bufhandle *h); 4081 #else 4082 struct upb_bufhandle { 4083 #endif 4084 const char *buf_; 4085 const void *obj_; 4086 const void *objtype_; 4087 size_t objofs_; 4088 }; 4089 4090 #ifdef __cplusplus 4091 4092 /* A upb::Handlers object represents the set of handlers associated with a 4093 * message in the graph of messages. You can think of it as a big virtual 4094 * table with functions corresponding to all the events that can fire while 4095 * parsing or visiting a message of a specific type. 4096 * 4097 * Any handlers that are not set behave as if they had successfully consumed 4098 * the value. Any unset Start* handlers will propagate their closure to the 4099 * inner frame. 4100 * 4101 * The easiest way to create the *Handler objects needed by the Set* methods is 4102 * with the UpbBind() and UpbMakeHandler() macros; see below. */ 4103 class upb::Handlers { 4104 public: 4105 typedef upb_selector_t Selector; 4106 typedef upb_handlertype_t Type; 4107 4108 typedef Handler<void *(*)(void *, const void *)> StartFieldHandler; 4109 typedef Handler<bool (*)(void *, const void *)> EndFieldHandler; 4110 typedef Handler<bool (*)(void *, const void *)> StartMessageHandler; 4111 typedef Handler<bool (*)(void *, const void *, Status*)> EndMessageHandler; 4112 typedef Handler<void *(*)(void *, const void *, size_t)> StartStringHandler; 4113 typedef Handler<size_t (*)(void *, const void *, const char *, size_t, 4114 const BufferHandle *)> StringHandler; 4115 4116 template <class T> struct ValueHandler { 4117 typedef Handler<bool(*)(void *, const void *, T)> H; 4118 }; 4119 4120 typedef ValueHandler<int32_t>::H Int32Handler; 4121 typedef ValueHandler<int64_t>::H Int64Handler; 4122 typedef ValueHandler<uint32_t>::H UInt32Handler; 4123 typedef ValueHandler<uint64_t>::H UInt64Handler; 4124 typedef ValueHandler<float>::H FloatHandler; 4125 typedef ValueHandler<double>::H DoubleHandler; 4126 typedef ValueHandler<bool>::H BoolHandler; 4127 4128 /* Any function pointer can be converted to this and converted back to its 4129 * correct type. */ 4130 typedef void GenericFunction(); 4131 4132 typedef void HandlersCallback(const void *closure, upb_handlers *h); 4133 4134 /* Returns a new handlers object for the given frozen msgdef. 4135 * Returns NULL if memory allocation failed. */ 4136 static reffed_ptr<Handlers> New(const MessageDef *m); 4137 4138 /* Convenience function for registering a graph of handlers that mirrors the 4139 * graph of msgdefs for some message. For "m" and all its children a new set 4140 * of handlers will be created and the given callback will be invoked, 4141 * allowing the client to register handlers for this message. Note that any 4142 * subhandlers set by the callback will be overwritten. */ 4143 static reffed_ptr<const Handlers> NewFrozen(const MessageDef *m, 4144 HandlersCallback *callback, 4145 const void *closure); 4146 4147 /* Functionality from upb::RefCounted. */ 4148 UPB_REFCOUNTED_CPPMETHODS 4149 4150 /* All handler registration functions return bool to indicate success or 4151 * failure; details about failures are stored in this status object. If a 4152 * failure does occur, it must be cleared before the Handlers are frozen, 4153 * otherwise the freeze() operation will fail. The functions may *only* be 4154 * used while the Handlers are mutable. */ 4155 const Status* status(); 4156 void ClearError(); 4157 4158 /* Call to freeze these Handlers. Requires that any SubHandlers are already 4159 * frozen. For cycles, you must use the static version below and freeze the 4160 * whole graph at once. */ 4161 bool Freeze(Status* s); 4162 4163 /* Freezes the given set of handlers. You may not freeze a handler without 4164 * also freezing any handlers they point to. */ 4165 static bool Freeze(Handlers*const* handlers, int n, Status* s); 4166 static bool Freeze(const std::vector<Handlers*>& handlers, Status* s); 4167 4168 /* Returns the msgdef associated with this handlers object. */ 4169 const MessageDef* message_def() const; 4170 4171 /* Adds the given pointer and function to the list of cleanup functions that 4172 * will be run when these handlers are freed. If this pointer has previously 4173 * been registered, the function returns false and does nothing. */ 4174 bool AddCleanup(void *ptr, upb_handlerfree *cleanup); 4175 4176 /* Sets the startmsg handler for the message, which is defined as follows: 4177 * 4178 * bool startmsg(MyType* closure) { 4179 * // Called when the message begins. Returns true if processing should 4180 * // continue. 4181 * return true; 4182 * } 4183 */ 4184 bool SetStartMessageHandler(const StartMessageHandler& handler); 4185 4186 /* Sets the endmsg handler for the message, which is defined as follows: 4187 * 4188 * bool endmsg(MyType* closure, upb_status *status) { 4189 * // Called when processing of this message ends, whether in success or 4190 * // failure. "status" indicates the final status of processing, and 4191 * // can also be modified in-place to update the final status. 4192 * } 4193 */ 4194 bool SetEndMessageHandler(const EndMessageHandler& handler); 4195 4196 /* Sets the value handler for the given field, which is defined as follows 4197 * (this is for an int32 field; other field types will pass their native 4198 * C/C++ type for "val"): 4199 * 4200 * bool OnValue(MyClosure* c, const MyHandlerData* d, int32_t val) { 4201 * // Called when the field's value is encountered. "d" contains 4202 * // whatever data was bound to this field when it was registered. 4203 * // Returns true if processing should continue. 4204 * return true; 4205 * } 4206 * 4207 * handers->SetInt32Handler(f, UpbBind(OnValue, new MyHandlerData(...))); 4208 * 4209 * The value type must exactly match f->type(). 4210 * For example, a handler that takes an int32_t parameter may only be used for 4211 * fields of type UPB_TYPE_INT32 and UPB_TYPE_ENUM. 4212 * 4213 * Returns false if the handler failed to register; in this case the cleanup 4214 * handler (if any) will be called immediately. 4215 */ 4216 bool SetInt32Handler (const FieldDef* f, const Int32Handler& h); 4217 bool SetInt64Handler (const FieldDef* f, const Int64Handler& h); 4218 bool SetUInt32Handler(const FieldDef* f, const UInt32Handler& h); 4219 bool SetUInt64Handler(const FieldDef* f, const UInt64Handler& h); 4220 bool SetFloatHandler (const FieldDef* f, const FloatHandler& h); 4221 bool SetDoubleHandler(const FieldDef* f, const DoubleHandler& h); 4222 bool SetBoolHandler (const FieldDef* f, const BoolHandler& h); 4223 4224 /* Like the previous, but templated on the type on the value (ie. int32). 4225 * This is mostly useful to call from other templates. To call this you must 4226 * specify the template parameter explicitly, ie: 4227 * h->SetValueHandler<T>(f, UpbBind(MyHandler<T>, MyData)); */ 4228 template <class T> 4229 bool SetValueHandler( 4230 const FieldDef *f, 4231 const typename ValueHandler<typename CanonicalType<T>::Type>::H& handler); 4232 4233 /* Sets handlers for a string field, which are defined as follows: 4234 * 4235 * MySubClosure* startstr(MyClosure* c, const MyHandlerData* d, 4236 * size_t size_hint) { 4237 * // Called when a string value begins. The return value indicates the 4238 * // closure for the string. "size_hint" indicates the size of the 4239 * // string if it is known, however if the string is length-delimited 4240 * // and the end-of-string is not available size_hint will be zero. 4241 * // This case is indistinguishable from the case where the size is 4242 * // known to be zero. 4243 * // 4244 * // TODO(haberman): is it important to distinguish these cases? 4245 * // If we had ssize_t as a type we could make -1 "unknown", but 4246 * // ssize_t is POSIX (not ANSI) and therefore less portable. 4247 * // In practice I suspect it won't be important to distinguish. 4248 * return closure; 4249 * } 4250 * 4251 * size_t str(MyClosure* closure, const MyHandlerData* d, 4252 * const char *str, size_t len) { 4253 * // Called for each buffer of string data; the multiple physical buffers 4254 * // are all part of the same logical string. The return value indicates 4255 * // how many bytes were consumed. If this number is less than "len", 4256 * // this will also indicate that processing should be halted for now, 4257 * // like returning false or UPB_BREAK from any other callback. If 4258 * // number is greater than "len", the excess bytes will be skipped over 4259 * // and not passed to the callback. 4260 * return len; 4261 * } 4262 * 4263 * bool endstr(MyClosure* c, const MyHandlerData* d) { 4264 * // Called when a string value ends. Return value indicates whether 4265 * // processing should continue. 4266 * return true; 4267 * } 4268 */ 4269 bool SetStartStringHandler(const FieldDef* f, const StartStringHandler& h); 4270 bool SetStringHandler(const FieldDef* f, const StringHandler& h); 4271 bool SetEndStringHandler(const FieldDef* f, const EndFieldHandler& h); 4272 4273 /* Sets the startseq handler, which is defined as follows: 4274 * 4275 * MySubClosure *startseq(MyClosure* c, const MyHandlerData* d) { 4276 * // Called when a sequence (repeated field) begins. The returned 4277 * // pointer indicates the closure for the sequence (or UPB_BREAK 4278 * // to interrupt processing). 4279 * return closure; 4280 * } 4281 * 4282 * h->SetStartSequenceHandler(f, UpbBind(startseq, new MyHandlerData(...))); 4283 * 4284 * Returns "false" if "f" does not belong to this message or is not a 4285 * repeated field. 4286 */ 4287 bool SetStartSequenceHandler(const FieldDef* f, const StartFieldHandler& h); 4288 4289 /* Sets the startsubmsg handler for the given field, which is defined as 4290 * follows: 4291 * 4292 * MySubClosure* startsubmsg(MyClosure* c, const MyHandlerData* d) { 4293 * // Called when a submessage begins. The returned pointer indicates the 4294 * // closure for the sequence (or UPB_BREAK to interrupt processing). 4295 * return closure; 4296 * } 4297 * 4298 * h->SetStartSubMessageHandler(f, UpbBind(startsubmsg, 4299 * new MyHandlerData(...))); 4300 * 4301 * Returns "false" if "f" does not belong to this message or is not a 4302 * submessage/group field. 4303 */ 4304 bool SetStartSubMessageHandler(const FieldDef* f, const StartFieldHandler& h); 4305 4306 /* Sets the endsubmsg handler for the given field, which is defined as 4307 * follows: 4308 * 4309 * bool endsubmsg(MyClosure* c, const MyHandlerData* d) { 4310 * // Called when a submessage ends. Returns true to continue processing. 4311 * return true; 4312 * } 4313 * 4314 * Returns "false" if "f" does not belong to this message or is not a 4315 * submessage/group field. 4316 */ 4317 bool SetEndSubMessageHandler(const FieldDef *f, const EndFieldHandler &h); 4318 4319 /* Starts the endsubseq handler for the given field, which is defined as 4320 * follows: 4321 * 4322 * bool endseq(MyClosure* c, const MyHandlerData* d) { 4323 * // Called when a sequence ends. Returns true continue processing. 4324 * return true; 4325 * } 4326 * 4327 * Returns "false" if "f" does not belong to this message or is not a 4328 * repeated field. 4329 */ 4330 bool SetEndSequenceHandler(const FieldDef* f, const EndFieldHandler& h); 4331 4332 /* Sets or gets the object that specifies handlers for the given field, which 4333 * must be a submessage or group. Returns NULL if no handlers are set. */ 4334 bool SetSubHandlers(const FieldDef* f, const Handlers* sub); 4335 const Handlers* GetSubHandlers(const FieldDef* f) const; 4336 4337 /* Equivalent to GetSubHandlers, but takes the STARTSUBMSG selector for the 4338 * field. */ 4339 const Handlers* GetSubHandlers(Selector startsubmsg) const; 4340 4341 /* A selector refers to a specific field handler in the Handlers object 4342 * (for example: the STARTSUBMSG handler for field "field15"). 4343 * On success, returns true and stores the selector in "s". 4344 * If the FieldDef or Type are invalid, returns false. 4345 * The returned selector is ONLY valid for Handlers whose MessageDef 4346 * contains this FieldDef. */ 4347 static bool GetSelector(const FieldDef* f, Type type, Selector* s); 4348 4349 /* Given a START selector of any kind, returns the corresponding END selector. */ 4350 static Selector GetEndSelector(Selector start_selector); 4351 4352 /* Returns the function pointer for this handler. It is the client's 4353 * responsibility to cast to the correct function type before calling it. */ 4354 GenericFunction* GetHandler(Selector selector); 4355 4356 /* Sets the given attributes to the attributes for this selector. */ 4357 bool GetAttributes(Selector selector, HandlerAttributes* attr); 4358 4359 /* Returns the handler data that was registered with this handler. */ 4360 const void* GetHandlerData(Selector selector); 4361 4362 /* Could add any of the following functions as-needed, with some minor 4363 * implementation changes: 4364 * 4365 * const FieldDef* GetFieldDef(Selector selector); 4366 * static bool IsSequence(Selector selector); */ 4367 4368 private: 4369 UPB_DISALLOW_POD_OPS(Handlers, upb::Handlers) 4370 4371 friend UPB_INLINE GenericFunction *::upb_handlers_gethandler( 4372 const upb_handlers *h, upb_selector_t s); 4373 friend UPB_INLINE const void *::upb_handlers_gethandlerdata( 4374 const upb_handlers *h, upb_selector_t s); 4375 #else 4376 struct upb_handlers { 4377 #endif 4378 upb_refcounted base; 4379 4380 const upb_msgdef *msg; 4381 const upb_handlers **sub; 4382 const void *top_closure_type; 4383 upb_inttable cleanup_; 4384 upb_status status_; /* Used only when mutable. */ 4385 upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */ 4386 }; 4387 4388 #ifdef __cplusplus 4389 4390 namespace upb { 4391 4392 /* Convenience macros for creating a Handler object that is wrapped with a 4393 * type-safe wrapper function that converts the "void*" parameters/returns 4394 * of the underlying C API into nice C++ function. 4395 * 4396 * Sample usage: 4397 * void OnValue1(MyClosure* c, const MyHandlerData* d, int32_t val) { 4398 * // do stuff ... 4399 * } 4400 * 4401 * // Handler that doesn't need any data bound to it. 4402 * void OnValue2(MyClosure* c, int32_t val) { 4403 * // do stuff ... 4404 * } 4405 * 4406 * // Handler that returns bool so it can return failure if necessary. 4407 * bool OnValue3(MyClosure* c, int32_t val) { 4408 * // do stuff ... 4409 * return ok; 4410 * } 4411 * 4412 * // Member function handler. 4413 * class MyClosure { 4414 * public: 4415 * void OnValue(int32_t val) { 4416 * // do stuff ... 4417 * } 4418 * }; 4419 * 4420 * // Takes ownership of the MyHandlerData. 4421 * handlers->SetInt32Handler(f1, UpbBind(OnValue1, new MyHandlerData(...))); 4422 * handlers->SetInt32Handler(f2, UpbMakeHandler(OnValue2)); 4423 * handlers->SetInt32Handler(f1, UpbMakeHandler(OnValue3)); 4424 * handlers->SetInt32Handler(f2, UpbMakeHandler(&MyClosure::OnValue)); 4425 */ 4426 4427 #ifdef UPB_CXX11 4428 4429 /* In C++11, the "template" disambiguator can appear even outside templates, 4430 * so all calls can safely use this pair of macros. */ 4431 4432 #define UpbMakeHandler(f) upb::MatchFunc(f).template GetFunc<f>() 4433 4434 /* We have to be careful to only evaluate "d" once. */ 4435 #define UpbBind(f, d) upb::MatchFunc(f).template GetFunc<f>((d)) 4436 4437 #else 4438 4439 /* Prior to C++11, the "template" disambiguator may only appear inside a 4440 * template, so the regular macro must not use "template" */ 4441 4442 #define UpbMakeHandler(f) upb::MatchFunc(f).GetFunc<f>() 4443 4444 #define UpbBind(f, d) upb::MatchFunc(f).GetFunc<f>((d)) 4445 4446 #endif /* UPB_CXX11 */ 4447 4448 /* This macro must be used in C++98 for calls from inside a template. But we 4449 * define this variant in all cases; code that wants to be compatible with both 4450 * C++98 and C++11 should always use this macro when calling from a template. */ 4451 #define UpbMakeHandlerT(f) upb::MatchFunc(f).template GetFunc<f>() 4452 4453 /* We have to be careful to only evaluate "d" once. */ 4454 #define UpbBindT(f, d) upb::MatchFunc(f).template GetFunc<f>((d)) 4455 4456 /* Handler: a struct that contains the (handler, data, deleter) tuple that is 4457 * used to register all handlers. Users can Make() these directly but it's 4458 * more convenient to use the UpbMakeHandler/UpbBind macros above. */ 4459 template <class T> class Handler { 4460 public: 4461 /* The underlying, handler function signature that upb uses internally. */ 4462 typedef T FuncPtr; 4463 4464 /* Intentionally implicit. */ 4465 template <class F> Handler(F func); 4466 ~Handler(); 4467 4468 private: 4469 void AddCleanup(Handlers* h) const { 4470 if (cleanup_func_) { 4471 bool ok = h->AddCleanup(cleanup_data_, cleanup_func_); 4472 UPB_ASSERT_VAR(ok, ok); 4473 } 4474 } 4475 4476 UPB_DISALLOW_COPY_AND_ASSIGN(Handler) 4477 friend class Handlers; 4478 FuncPtr handler_; 4479 mutable HandlerAttributes attr_; 4480 mutable bool registered_; 4481 void *cleanup_data_; 4482 upb_handlerfree *cleanup_func_; 4483 }; 4484 4485 } /* namespace upb */ 4486 4487 #endif /* __cplusplus */ 4488 4489 UPB_BEGIN_EXTERN_C 4490 4491 /* Native C API. */ 4492 4493 /* Handler function typedefs. */ 4494 typedef bool upb_startmsg_handlerfunc(void *c, const void*); 4495 typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status); 4496 typedef void* upb_startfield_handlerfunc(void *c, const void *hd); 4497 typedef bool upb_endfield_handlerfunc(void *c, const void *hd); 4498 typedef bool upb_int32_handlerfunc(void *c, const void *hd, int32_t val); 4499 typedef bool upb_int64_handlerfunc(void *c, const void *hd, int64_t val); 4500 typedef bool upb_uint32_handlerfunc(void *c, const void *hd, uint32_t val); 4501 typedef bool upb_uint64_handlerfunc(void *c, const void *hd, uint64_t val); 4502 typedef bool upb_float_handlerfunc(void *c, const void *hd, float val); 4503 typedef bool upb_double_handlerfunc(void *c, const void *hd, double val); 4504 typedef bool upb_bool_handlerfunc(void *c, const void *hd, bool val); 4505 typedef void *upb_startstr_handlerfunc(void *c, const void *hd, 4506 size_t size_hint); 4507 typedef size_t upb_string_handlerfunc(void *c, const void *hd, const char *buf, 4508 size_t n, const upb_bufhandle* handle); 4509 4510 /* upb_bufhandle */ 4511 size_t upb_bufhandle_objofs(const upb_bufhandle *h); 4512 4513 /* upb_handlerattr */ 4514 void upb_handlerattr_init(upb_handlerattr *attr); 4515 void upb_handlerattr_uninit(upb_handlerattr *attr); 4516 4517 bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd); 4518 bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type); 4519 const void *upb_handlerattr_closuretype(const upb_handlerattr *attr); 4520 bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr, 4521 const void *type); 4522 const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr); 4523 bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok); 4524 bool upb_handlerattr_alwaysok(const upb_handlerattr *attr); 4525 4526 UPB_INLINE const void *upb_handlerattr_handlerdata( 4527 const upb_handlerattr *attr) { 4528 return attr->handler_data_; 4529 } 4530 4531 /* upb_handlers */ 4532 typedef void upb_handlers_callback(const void *closure, upb_handlers *h); 4533 upb_handlers *upb_handlers_new(const upb_msgdef *m, 4534 const void *owner); 4535 const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m, 4536 const void *owner, 4537 upb_handlers_callback *callback, 4538 const void *closure); 4539 4540 /* Include refcounted methods like upb_handlers_ref(). */ 4541 UPB_REFCOUNTED_CMETHODS(upb_handlers, upb_handlers_upcast) 4542 4543 const upb_status *upb_handlers_status(upb_handlers *h); 4544 void upb_handlers_clearerr(upb_handlers *h); 4545 const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h); 4546 bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree); 4547 4548 bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func, 4549 upb_handlerattr *attr); 4550 bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func, 4551 upb_handlerattr *attr); 4552 bool upb_handlers_setint32(upb_handlers *h, const upb_fielddef *f, 4553 upb_int32_handlerfunc *func, upb_handlerattr *attr); 4554 bool upb_handlers_setint64(upb_handlers *h, const upb_fielddef *f, 4555 upb_int64_handlerfunc *func, upb_handlerattr *attr); 4556 bool upb_handlers_setuint32(upb_handlers *h, const upb_fielddef *f, 4557 upb_uint32_handlerfunc *func, 4558 upb_handlerattr *attr); 4559 bool upb_handlers_setuint64(upb_handlers *h, const upb_fielddef *f, 4560 upb_uint64_handlerfunc *func, 4561 upb_handlerattr *attr); 4562 bool upb_handlers_setfloat(upb_handlers *h, const upb_fielddef *f, 4563 upb_float_handlerfunc *func, upb_handlerattr *attr); 4564 bool upb_handlers_setdouble(upb_handlers *h, const upb_fielddef *f, 4565 upb_double_handlerfunc *func, 4566 upb_handlerattr *attr); 4567 bool upb_handlers_setbool(upb_handlers *h, const upb_fielddef *f, 4568 upb_bool_handlerfunc *func, 4569 upb_handlerattr *attr); 4570 bool upb_handlers_setstartstr(upb_handlers *h, const upb_fielddef *f, 4571 upb_startstr_handlerfunc *func, 4572 upb_handlerattr *attr); 4573 bool upb_handlers_setstring(upb_handlers *h, const upb_fielddef *f, 4574 upb_string_handlerfunc *func, 4575 upb_handlerattr *attr); 4576 bool upb_handlers_setendstr(upb_handlers *h, const upb_fielddef *f, 4577 upb_endfield_handlerfunc *func, 4578 upb_handlerattr *attr); 4579 bool upb_handlers_setstartseq(upb_handlers *h, const upb_fielddef *f, 4580 upb_startfield_handlerfunc *func, 4581 upb_handlerattr *attr); 4582 bool upb_handlers_setstartsubmsg(upb_handlers *h, const upb_fielddef *f, 4583 upb_startfield_handlerfunc *func, 4584 upb_handlerattr *attr); 4585 bool upb_handlers_setendsubmsg(upb_handlers *h, const upb_fielddef *f, 4586 upb_endfield_handlerfunc *func, 4587 upb_handlerattr *attr); 4588 bool upb_handlers_setendseq(upb_handlers *h, const upb_fielddef *f, 4589 upb_endfield_handlerfunc *func, 4590 upb_handlerattr *attr); 4591 4592 bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f, 4593 const upb_handlers *sub); 4594 const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h, 4595 const upb_fielddef *f); 4596 const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h, 4597 upb_selector_t sel); 4598 4599 UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h, 4600 upb_selector_t s) { 4601 return (upb_func *)h->table[s].func; 4602 } 4603 4604 bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t s, 4605 upb_handlerattr *attr); 4606 4607 UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h, 4608 upb_selector_t s) { 4609 return upb_handlerattr_handlerdata(&h->table[s].attr); 4610 } 4611 4612 #ifdef __cplusplus 4613 4614 /* Handler types for single fields. 4615 * Right now we only have one for TYPE_BYTES but ones for other types 4616 * should follow. 4617 * 4618 * These follow the same handlers protocol for fields of a message. */ 4619 class upb::BytesHandler { 4620 public: 4621 BytesHandler(); 4622 ~BytesHandler(); 4623 #else 4624 struct upb_byteshandler { 4625 #endif 4626 upb_handlers_tabent table[3]; 4627 }; 4628 4629 void upb_byteshandler_init(upb_byteshandler *h); 4630 4631 /* Caller must ensure that "d" outlives the handlers. 4632 * TODO(haberman): should this have a "freeze" operation? It's not necessary 4633 * for memory management, but could be useful to force immutability and provide 4634 * a convenient moment to verify that all registration succeeded. */ 4635 bool upb_byteshandler_setstartstr(upb_byteshandler *h, 4636 upb_startstr_handlerfunc *func, void *d); 4637 bool upb_byteshandler_setstring(upb_byteshandler *h, 4638 upb_string_handlerfunc *func, void *d); 4639 bool upb_byteshandler_setendstr(upb_byteshandler *h, 4640 upb_endfield_handlerfunc *func, void *d); 4641 4642 /* "Static" methods */ 4643 bool upb_handlers_freeze(upb_handlers *const *handlers, int n, upb_status *s); 4644 upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f); 4645 bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type, 4646 upb_selector_t *s); 4647 UPB_INLINE upb_selector_t upb_handlers_getendselector(upb_selector_t start) { 4648 return start + 1; 4649 } 4650 4651 /* Internal-only. */ 4652 uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f); 4653 uint32_t upb_handlers_selectorcount(const upb_fielddef *f); 4654 4655 UPB_END_EXTERN_C 4656 4657 /* 4658 ** Inline definitions for handlers.h, which are particularly long and a bit 4659 ** tricky. 4660 */ 4661 4662 #ifndef UPB_HANDLERS_INL_H_ 4663 #define UPB_HANDLERS_INL_H_ 4664 4665 #include <limits.h> 4666 4667 /* C inline methods. */ 4668 4669 /* upb_bufhandle */ 4670 UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h) { 4671 h->obj_ = NULL; 4672 h->objtype_ = NULL; 4673 h->buf_ = NULL; 4674 h->objofs_ = 0; 4675 } 4676 UPB_INLINE void upb_bufhandle_uninit(upb_bufhandle *h) { 4677 UPB_UNUSED(h); 4678 } 4679 UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj, 4680 const void *type) { 4681 h->obj_ = obj; 4682 h->objtype_ = type; 4683 } 4684 UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf, 4685 size_t ofs) { 4686 h->buf_ = buf; 4687 h->objofs_ = ofs; 4688 } 4689 UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h) { 4690 return h->obj_; 4691 } 4692 UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h) { 4693 return h->objtype_; 4694 } 4695 UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h) { 4696 return h->buf_; 4697 } 4698 4699 4700 #ifdef __cplusplus 4701 4702 /* Type detection and typedefs for integer types. 4703 * For platforms where there are multiple 32-bit or 64-bit types, we need to be 4704 * able to enumerate them so we can properly create overloads for all variants. 4705 * 4706 * If any platform existed where there were three integer types with the same 4707 * size, this would have to become more complicated. For example, short, int, 4708 * and long could all be 32-bits. Even more diabolically, short, int, long, 4709 * and long long could all be 64 bits and still be standard-compliant. 4710 * However, few platforms are this strange, and it's unlikely that upb will be 4711 * used on the strangest ones. */ 4712 4713 /* Can't count on stdint.h limits like INT32_MAX, because in C++ these are 4714 * only defined when __STDC_LIMIT_MACROS are defined before the *first* include 4715 * of stdint.h. We can't guarantee that someone else didn't include these first 4716 * without defining __STDC_LIMIT_MACROS. */ 4717 #define UPB_INT32_MAX 0x7fffffffLL 4718 #define UPB_INT32_MIN (-UPB_INT32_MAX - 1) 4719 #define UPB_INT64_MAX 0x7fffffffffffffffLL 4720 #define UPB_INT64_MIN (-UPB_INT64_MAX - 1) 4721 4722 #if INT_MAX == UPB_INT32_MAX && INT_MIN == UPB_INT32_MIN 4723 #define UPB_INT_IS_32BITS 1 4724 #endif 4725 4726 #if LONG_MAX == UPB_INT32_MAX && LONG_MIN == UPB_INT32_MIN 4727 #define UPB_LONG_IS_32BITS 1 4728 #endif 4729 4730 #if LONG_MAX == UPB_INT64_MAX && LONG_MIN == UPB_INT64_MIN 4731 #define UPB_LONG_IS_64BITS 1 4732 #endif 4733 4734 #if LLONG_MAX == UPB_INT64_MAX && LLONG_MIN == UPB_INT64_MIN 4735 #define UPB_LLONG_IS_64BITS 1 4736 #endif 4737 4738 /* We use macros instead of typedefs so we can undefine them later and avoid 4739 * leaking them outside this header file. */ 4740 #if UPB_INT_IS_32BITS 4741 #define UPB_INT32_T int 4742 #define UPB_UINT32_T unsigned int 4743 4744 #if UPB_LONG_IS_32BITS 4745 #define UPB_TWO_32BIT_TYPES 1 4746 #define UPB_INT32ALT_T long 4747 #define UPB_UINT32ALT_T unsigned long 4748 #endif /* UPB_LONG_IS_32BITS */ 4749 4750 #elif UPB_LONG_IS_32BITS /* && !UPB_INT_IS_32BITS */ 4751 #define UPB_INT32_T long 4752 #define UPB_UINT32_T unsigned long 4753 #endif /* UPB_INT_IS_32BITS */ 4754 4755 4756 #if UPB_LONG_IS_64BITS 4757 #define UPB_INT64_T long 4758 #define UPB_UINT64_T unsigned long 4759 4760 #if UPB_LLONG_IS_64BITS 4761 #define UPB_TWO_64BIT_TYPES 1 4762 #define UPB_INT64ALT_T long long 4763 #define UPB_UINT64ALT_T unsigned long long 4764 #endif /* UPB_LLONG_IS_64BITS */ 4765 4766 #elif UPB_LLONG_IS_64BITS /* && !UPB_LONG_IS_64BITS */ 4767 #define UPB_INT64_T long long 4768 #define UPB_UINT64_T unsigned long long 4769 #endif /* UPB_LONG_IS_64BITS */ 4770 4771 #undef UPB_INT32_MAX 4772 #undef UPB_INT32_MIN 4773 #undef UPB_INT64_MAX 4774 #undef UPB_INT64_MIN 4775 #undef UPB_INT_IS_32BITS 4776 #undef UPB_LONG_IS_32BITS 4777 #undef UPB_LONG_IS_64BITS 4778 #undef UPB_LLONG_IS_64BITS 4779 4780 4781 namespace upb { 4782 4783 typedef void CleanupFunc(void *ptr); 4784 4785 /* Template to remove "const" from "const T*" and just return "T*". 4786 * 4787 * We define a nonsense default because otherwise it will fail to instantiate as 4788 * a function parameter type even in cases where we don't expect any caller to 4789 * actually match the overload. */ 4790 class CouldntRemoveConst {}; 4791 template <class T> struct remove_constptr { typedef CouldntRemoveConst type; }; 4792 template <class T> struct remove_constptr<const T *> { typedef T *type; }; 4793 4794 /* Template that we use below to remove a template specialization from 4795 * consideration if it matches a specific type. */ 4796 template <class T, class U> struct disable_if_same { typedef void Type; }; 4797 template <class T> struct disable_if_same<T, T> {}; 4798 4799 template <class T> void DeletePointer(void *p) { delete static_cast<T>(p); } 4800 4801 template <class T1, class T2> 4802 struct FirstUnlessVoidOrBool { 4803 typedef T1 value; 4804 }; 4805 4806 template <class T2> 4807 struct FirstUnlessVoidOrBool<void, T2> { 4808 typedef T2 value; 4809 }; 4810 4811 template <class T2> 4812 struct FirstUnlessVoidOrBool<bool, T2> { 4813 typedef T2 value; 4814 }; 4815 4816 template<class T, class U> 4817 struct is_same { 4818 static bool value; 4819 }; 4820 4821 template<class T> 4822 struct is_same<T, T> { 4823 static bool value; 4824 }; 4825 4826 template<class T, class U> 4827 bool is_same<T, U>::value = false; 4828 4829 template<class T> 4830 bool is_same<T, T>::value = true; 4831 4832 /* FuncInfo *******************************************************************/ 4833 4834 /* Info about the user's original, pre-wrapped function. */ 4835 template <class C, class R = void> 4836 struct FuncInfo { 4837 /* The type of the closure that the function takes (its first param). */ 4838 typedef C Closure; 4839 4840 /* The return type. */ 4841 typedef R Return; 4842 }; 4843 4844 /* Func ***********************************************************************/ 4845 4846 /* Func1, Func2, Func3: Template classes representing a function and its 4847 * signature. 4848 * 4849 * Since the function is a template parameter, calling the function can be 4850 * inlined at compile-time and does not require a function pointer at runtime. 4851 * These functions are not bound to a handler data so have no data or cleanup 4852 * handler. */ 4853 struct UnboundFunc { 4854 CleanupFunc *GetCleanup() { return NULL; } 4855 void *GetData() { return NULL; } 4856 }; 4857 4858 template <class R, class P1, R F(P1), class I> 4859 struct Func1 : public UnboundFunc { 4860 typedef R Return; 4861 typedef I FuncInfo; 4862 static R Call(P1 p1) { return F(p1); } 4863 }; 4864 4865 template <class R, class P1, class P2, R F(P1, P2), class I> 4866 struct Func2 : public UnboundFunc { 4867 typedef R Return; 4868 typedef I FuncInfo; 4869 static R Call(P1 p1, P2 p2) { return F(p1, p2); } 4870 }; 4871 4872 template <class R, class P1, class P2, class P3, R F(P1, P2, P3), class I> 4873 struct Func3 : public UnboundFunc { 4874 typedef R Return; 4875 typedef I FuncInfo; 4876 static R Call(P1 p1, P2 p2, P3 p3) { return F(p1, p2, p3); } 4877 }; 4878 4879 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4), 4880 class I> 4881 struct Func4 : public UnboundFunc { 4882 typedef R Return; 4883 typedef I FuncInfo; 4884 static R Call(P1 p1, P2 p2, P3 p3, P4 p4) { return F(p1, p2, p3, p4); } 4885 }; 4886 4887 template <class R, class P1, class P2, class P3, class P4, class P5, 4888 R F(P1, P2, P3, P4, P5), class I> 4889 struct Func5 : public UnboundFunc { 4890 typedef R Return; 4891 typedef I FuncInfo; 4892 static R Call(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { 4893 return F(p1, p2, p3, p4, p5); 4894 } 4895 }; 4896 4897 /* BoundFunc ******************************************************************/ 4898 4899 /* BoundFunc2, BoundFunc3: Like Func2/Func3 except also contains a value that 4900 * shall be bound to the function's second parameter. 4901 * 4902 * Note that the second parameter is a const pointer, but our stored bound value 4903 * is non-const so we can free it when the handlers are destroyed. */ 4904 template <class T> 4905 struct BoundFunc { 4906 typedef typename remove_constptr<T>::type MutableP2; 4907 explicit BoundFunc(MutableP2 data_) : data(data_) {} 4908 CleanupFunc *GetCleanup() { return &DeletePointer<MutableP2>; } 4909 MutableP2 GetData() { return data; } 4910 MutableP2 data; 4911 }; 4912 4913 template <class R, class P1, class P2, R F(P1, P2), class I> 4914 struct BoundFunc2 : public BoundFunc<P2> { 4915 typedef BoundFunc<P2> Base; 4916 typedef I FuncInfo; 4917 explicit BoundFunc2(typename Base::MutableP2 arg) : Base(arg) {} 4918 }; 4919 4920 template <class R, class P1, class P2, class P3, R F(P1, P2, P3), class I> 4921 struct BoundFunc3 : public BoundFunc<P2> { 4922 typedef BoundFunc<P2> Base; 4923 typedef I FuncInfo; 4924 explicit BoundFunc3(typename Base::MutableP2 arg) : Base(arg) {} 4925 }; 4926 4927 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4), 4928 class I> 4929 struct BoundFunc4 : public BoundFunc<P2> { 4930 typedef BoundFunc<P2> Base; 4931 typedef I FuncInfo; 4932 explicit BoundFunc4(typename Base::MutableP2 arg) : Base(arg) {} 4933 }; 4934 4935 template <class R, class P1, class P2, class P3, class P4, class P5, 4936 R F(P1, P2, P3, P4, P5), class I> 4937 struct BoundFunc5 : public BoundFunc<P2> { 4938 typedef BoundFunc<P2> Base; 4939 typedef I FuncInfo; 4940 explicit BoundFunc5(typename Base::MutableP2 arg) : Base(arg) {} 4941 }; 4942 4943 /* FuncSig ********************************************************************/ 4944 4945 /* FuncSig1, FuncSig2, FuncSig3: template classes reflecting a function 4946 * *signature*, but without a specific function attached. 4947 * 4948 * These classes contain member functions that can be invoked with a 4949 * specific function to return a Func/BoundFunc class. */ 4950 template <class R, class P1> 4951 struct FuncSig1 { 4952 template <R F(P1)> 4953 Func1<R, P1, F, FuncInfo<P1, R> > GetFunc() { 4954 return Func1<R, P1, F, FuncInfo<P1, R> >(); 4955 } 4956 }; 4957 4958 template <class R, class P1, class P2> 4959 struct FuncSig2 { 4960 template <R F(P1, P2)> 4961 Func2<R, P1, P2, F, FuncInfo<P1, R> > GetFunc() { 4962 return Func2<R, P1, P2, F, FuncInfo<P1, R> >(); 4963 } 4964 4965 template <R F(P1, P2)> 4966 BoundFunc2<R, P1, P2, F, FuncInfo<P1, R> > GetFunc( 4967 typename remove_constptr<P2>::type param2) { 4968 return BoundFunc2<R, P1, P2, F, FuncInfo<P1, R> >(param2); 4969 } 4970 }; 4971 4972 template <class R, class P1, class P2, class P3> 4973 struct FuncSig3 { 4974 template <R F(P1, P2, P3)> 4975 Func3<R, P1, P2, P3, F, FuncInfo<P1, R> > GetFunc() { 4976 return Func3<R, P1, P2, P3, F, FuncInfo<P1, R> >(); 4977 } 4978 4979 template <R F(P1, P2, P3)> 4980 BoundFunc3<R, P1, P2, P3, F, FuncInfo<P1, R> > GetFunc( 4981 typename remove_constptr<P2>::type param2) { 4982 return BoundFunc3<R, P1, P2, P3, F, FuncInfo<P1, R> >(param2); 4983 } 4984 }; 4985 4986 template <class R, class P1, class P2, class P3, class P4> 4987 struct FuncSig4 { 4988 template <R F(P1, P2, P3, P4)> 4989 Func4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> > GetFunc() { 4990 return Func4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> >(); 4991 } 4992 4993 template <R F(P1, P2, P3, P4)> 4994 BoundFunc4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> > GetFunc( 4995 typename remove_constptr<P2>::type param2) { 4996 return BoundFunc4<R, P1, P2, P3, P4, F, FuncInfo<P1, R> >(param2); 4997 } 4998 }; 4999 5000 template <class R, class P1, class P2, class P3, class P4, class P5> 5001 struct FuncSig5 { 5002 template <R F(P1, P2, P3, P4, P5)> 5003 Func5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> > GetFunc() { 5004 return Func5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> >(); 5005 } 5006 5007 template <R F(P1, P2, P3, P4, P5)> 5008 BoundFunc5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> > GetFunc( 5009 typename remove_constptr<P2>::type param2) { 5010 return BoundFunc5<R, P1, P2, P3, P4, P5, F, FuncInfo<P1, R> >(param2); 5011 } 5012 }; 5013 5014 /* Overloaded template function that can construct the appropriate FuncSig* 5015 * class given a function pointer by deducing the template parameters. */ 5016 template <class R, class P1> 5017 inline FuncSig1<R, P1> MatchFunc(R (*f)(P1)) { 5018 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5019 return FuncSig1<R, P1>(); 5020 } 5021 5022 template <class R, class P1, class P2> 5023 inline FuncSig2<R, P1, P2> MatchFunc(R (*f)(P1, P2)) { 5024 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5025 return FuncSig2<R, P1, P2>(); 5026 } 5027 5028 template <class R, class P1, class P2, class P3> 5029 inline FuncSig3<R, P1, P2, P3> MatchFunc(R (*f)(P1, P2, P3)) { 5030 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5031 return FuncSig3<R, P1, P2, P3>(); 5032 } 5033 5034 template <class R, class P1, class P2, class P3, class P4> 5035 inline FuncSig4<R, P1, P2, P3, P4> MatchFunc(R (*f)(P1, P2, P3, P4)) { 5036 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5037 return FuncSig4<R, P1, P2, P3, P4>(); 5038 } 5039 5040 template <class R, class P1, class P2, class P3, class P4, class P5> 5041 inline FuncSig5<R, P1, P2, P3, P4, P5> MatchFunc(R (*f)(P1, P2, P3, P4, P5)) { 5042 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5043 return FuncSig5<R, P1, P2, P3, P4, P5>(); 5044 } 5045 5046 /* MethodSig ******************************************************************/ 5047 5048 /* CallMethod*: a function template that calls a given method. */ 5049 template <class R, class C, R (C::*F)()> 5050 R CallMethod0(C *obj) { 5051 return ((*obj).*F)(); 5052 } 5053 5054 template <class R, class C, class P1, R (C::*F)(P1)> 5055 R CallMethod1(C *obj, P1 arg1) { 5056 return ((*obj).*F)(arg1); 5057 } 5058 5059 template <class R, class C, class P1, class P2, R (C::*F)(P1, P2)> 5060 R CallMethod2(C *obj, P1 arg1, P2 arg2) { 5061 return ((*obj).*F)(arg1, arg2); 5062 } 5063 5064 template <class R, class C, class P1, class P2, class P3, R (C::*F)(P1, P2, P3)> 5065 R CallMethod3(C *obj, P1 arg1, P2 arg2, P3 arg3) { 5066 return ((*obj).*F)(arg1, arg2, arg3); 5067 } 5068 5069 template <class R, class C, class P1, class P2, class P3, class P4, 5070 R (C::*F)(P1, P2, P3, P4)> 5071 R CallMethod4(C *obj, P1 arg1, P2 arg2, P3 arg3, P4 arg4) { 5072 return ((*obj).*F)(arg1, arg2, arg3, arg4); 5073 } 5074 5075 /* MethodSig: like FuncSig, but for member functions. 5076 * 5077 * GetFunc() returns a normal FuncN object, so after calling GetFunc() no 5078 * more logic is required to special-case methods. */ 5079 template <class R, class C> 5080 struct MethodSig0 { 5081 template <R (C::*F)()> 5082 Func1<R, C *, CallMethod0<R, C, F>, FuncInfo<C *, R> > GetFunc() { 5083 return Func1<R, C *, CallMethod0<R, C, F>, FuncInfo<C *, R> >(); 5084 } 5085 }; 5086 5087 template <class R, class C, class P1> 5088 struct MethodSig1 { 5089 template <R (C::*F)(P1)> 5090 Func2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> > GetFunc() { 5091 return Func2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> >(); 5092 } 5093 5094 template <R (C::*F)(P1)> 5095 BoundFunc2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> > GetFunc( 5096 typename remove_constptr<P1>::type param1) { 5097 return BoundFunc2<R, C *, P1, CallMethod1<R, C, P1, F>, FuncInfo<C *, R> >( 5098 param1); 5099 } 5100 }; 5101 5102 template <class R, class C, class P1, class P2> 5103 struct MethodSig2 { 5104 template <R (C::*F)(P1, P2)> 5105 Func3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>, FuncInfo<C *, R> > 5106 GetFunc() { 5107 return Func3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>, 5108 FuncInfo<C *, R> >(); 5109 } 5110 5111 template <R (C::*F)(P1, P2)> 5112 BoundFunc3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>, FuncInfo<C *, R> > 5113 GetFunc(typename remove_constptr<P1>::type param1) { 5114 return BoundFunc3<R, C *, P1, P2, CallMethod2<R, C, P1, P2, F>, 5115 FuncInfo<C *, R> >(param1); 5116 } 5117 }; 5118 5119 template <class R, class C, class P1, class P2, class P3> 5120 struct MethodSig3 { 5121 template <R (C::*F)(P1, P2, P3)> 5122 Func4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>, FuncInfo<C *, R> > 5123 GetFunc() { 5124 return Func4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>, 5125 FuncInfo<C *, R> >(); 5126 } 5127 5128 template <R (C::*F)(P1, P2, P3)> 5129 BoundFunc4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>, 5130 FuncInfo<C *, R> > 5131 GetFunc(typename remove_constptr<P1>::type param1) { 5132 return BoundFunc4<R, C *, P1, P2, P3, CallMethod3<R, C, P1, P2, P3, F>, 5133 FuncInfo<C *, R> >(param1); 5134 } 5135 }; 5136 5137 template <class R, class C, class P1, class P2, class P3, class P4> 5138 struct MethodSig4 { 5139 template <R (C::*F)(P1, P2, P3, P4)> 5140 Func5<R, C *, P1, P2, P3, P4, CallMethod4<R, C, P1, P2, P3, P4, F>, 5141 FuncInfo<C *, R> > 5142 GetFunc() { 5143 return Func5<R, C *, P1, P2, P3, P4, CallMethod4<R, C, P1, P2, P3, P4, F>, 5144 FuncInfo<C *, R> >(); 5145 } 5146 5147 template <R (C::*F)(P1, P2, P3, P4)> 5148 BoundFunc5<R, C *, P1, P2, P3, P4, CallMethod4<R, C, P1, P2, P3, P4, F>, 5149 FuncInfo<C *, R> > 5150 GetFunc(typename remove_constptr<P1>::type param1) { 5151 return BoundFunc5<R, C *, P1, P2, P3, P4, 5152 CallMethod4<R, C, P1, P2, P3, P4, F>, FuncInfo<C *, R> >( 5153 param1); 5154 } 5155 }; 5156 5157 template <class R, class C> 5158 inline MethodSig0<R, C> MatchFunc(R (C::*f)()) { 5159 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5160 return MethodSig0<R, C>(); 5161 } 5162 5163 template <class R, class C, class P1> 5164 inline MethodSig1<R, C, P1> MatchFunc(R (C::*f)(P1)) { 5165 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5166 return MethodSig1<R, C, P1>(); 5167 } 5168 5169 template <class R, class C, class P1, class P2> 5170 inline MethodSig2<R, C, P1, P2> MatchFunc(R (C::*f)(P1, P2)) { 5171 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5172 return MethodSig2<R, C, P1, P2>(); 5173 } 5174 5175 template <class R, class C, class P1, class P2, class P3> 5176 inline MethodSig3<R, C, P1, P2, P3> MatchFunc(R (C::*f)(P1, P2, P3)) { 5177 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5178 return MethodSig3<R, C, P1, P2, P3>(); 5179 } 5180 5181 template <class R, class C, class P1, class P2, class P3, class P4> 5182 inline MethodSig4<R, C, P1, P2, P3, P4> MatchFunc(R (C::*f)(P1, P2, P3, P4)) { 5183 UPB_UNUSED(f); /* Only used for template parameter deduction. */ 5184 return MethodSig4<R, C, P1, P2, P3, P4>(); 5185 } 5186 5187 /* MaybeWrapReturn ************************************************************/ 5188 5189 /* Template class that attempts to wrap the return value of the function so it 5190 * matches the expected type. There are two main adjustments it may make: 5191 * 5192 * 1. If the function returns void, make it return the expected type and with 5193 * a value that always indicates success. 5194 * 2. If the function returns bool, make it return the expected type with a 5195 * value that indicates success or failure. 5196 * 5197 * The "expected type" for return is: 5198 * 1. void* for start handlers. If the closure parameter has a different type 5199 * we will cast it to void* for the return in the success case. 5200 * 2. size_t for string buffer handlers. 5201 * 3. bool for everything else. */ 5202 5203 /* Template parameters are FuncN type and desired return type. */ 5204 template <class F, class R, class Enable = void> 5205 struct MaybeWrapReturn; 5206 5207 /* If the return type matches, return the given function unwrapped. */ 5208 template <class F> 5209 struct MaybeWrapReturn<F, typename F::Return> { 5210 typedef F Func; 5211 }; 5212 5213 /* Function wrapper that munges the return value from void to (bool)true. */ 5214 template <class P1, class P2, void F(P1, P2)> 5215 bool ReturnTrue2(P1 p1, P2 p2) { 5216 F(p1, p2); 5217 return true; 5218 } 5219 5220 template <class P1, class P2, class P3, void F(P1, P2, P3)> 5221 bool ReturnTrue3(P1 p1, P2 p2, P3 p3) { 5222 F(p1, p2, p3); 5223 return true; 5224 } 5225 5226 /* Function wrapper that munges the return value from void to (void*)arg1 */ 5227 template <class P1, class P2, void F(P1, P2)> 5228 void *ReturnClosure2(P1 p1, P2 p2) { 5229 F(p1, p2); 5230 return p1; 5231 } 5232 5233 template <class P1, class P2, class P3, void F(P1, P2, P3)> 5234 void *ReturnClosure3(P1 p1, P2 p2, P3 p3) { 5235 F(p1, p2, p3); 5236 return p1; 5237 } 5238 5239 /* Function wrapper that munges the return value from R to void*. */ 5240 template <class R, class P1, class P2, R F(P1, P2)> 5241 void *CastReturnToVoidPtr2(P1 p1, P2 p2) { 5242 return F(p1, p2); 5243 } 5244 5245 template <class R, class P1, class P2, class P3, R F(P1, P2, P3)> 5246 void *CastReturnToVoidPtr3(P1 p1, P2 p2, P3 p3) { 5247 return F(p1, p2, p3); 5248 } 5249 5250 /* Function wrapper that munges the return value from bool to void*. */ 5251 template <class P1, class P2, bool F(P1, P2)> 5252 void *ReturnClosureOrBreak2(P1 p1, P2 p2) { 5253 return F(p1, p2) ? p1 : UPB_BREAK; 5254 } 5255 5256 template <class P1, class P2, class P3, bool F(P1, P2, P3)> 5257 void *ReturnClosureOrBreak3(P1 p1, P2 p2, P3 p3) { 5258 return F(p1, p2, p3) ? p1 : UPB_BREAK; 5259 } 5260 5261 /* For the string callback, which takes five params, returns the size param. */ 5262 template <class P1, class P2, 5263 void F(P1, P2, const char *, size_t, const BufferHandle *)> 5264 size_t ReturnStringLen(P1 p1, P2 p2, const char *p3, size_t p4, 5265 const BufferHandle *p5) { 5266 F(p1, p2, p3, p4, p5); 5267 return p4; 5268 } 5269 5270 /* For the string callback, which takes five params, returns the size param or 5271 * zero. */ 5272 template <class P1, class P2, 5273 bool F(P1, P2, const char *, size_t, const BufferHandle *)> 5274 size_t ReturnNOr0(P1 p1, P2 p2, const char *p3, size_t p4, 5275 const BufferHandle *p5) { 5276 return F(p1, p2, p3, p4, p5) ? p4 : 0; 5277 } 5278 5279 /* If we have a function returning void but want a function returning bool, wrap 5280 * it in a function that returns true. */ 5281 template <class P1, class P2, void F(P1, P2), class I> 5282 struct MaybeWrapReturn<Func2<void, P1, P2, F, I>, bool> { 5283 typedef Func2<bool, P1, P2, ReturnTrue2<P1, P2, F>, I> Func; 5284 }; 5285 5286 template <class P1, class P2, class P3, void F(P1, P2, P3), class I> 5287 struct MaybeWrapReturn<Func3<void, P1, P2, P3, F, I>, bool> { 5288 typedef Func3<bool, P1, P2, P3, ReturnTrue3<P1, P2, P3, F>, I> Func; 5289 }; 5290 5291 /* If our function returns void but we want one returning void*, wrap it in a 5292 * function that returns the first argument. */ 5293 template <class P1, class P2, void F(P1, P2), class I> 5294 struct MaybeWrapReturn<Func2<void, P1, P2, F, I>, void *> { 5295 typedef Func2<void *, P1, P2, ReturnClosure2<P1, P2, F>, I> Func; 5296 }; 5297 5298 template <class P1, class P2, class P3, void F(P1, P2, P3), class I> 5299 struct MaybeWrapReturn<Func3<void, P1, P2, P3, F, I>, void *> { 5300 typedef Func3<void *, P1, P2, P3, ReturnClosure3<P1, P2, P3, F>, I> Func; 5301 }; 5302 5303 /* If our function returns R* but we want one returning void*, wrap it in a 5304 * function that casts to void*. */ 5305 template <class R, class P1, class P2, R *F(P1, P2), class I> 5306 struct MaybeWrapReturn<Func2<R *, P1, P2, F, I>, void *, 5307 typename disable_if_same<R *, void *>::Type> { 5308 typedef Func2<void *, P1, P2, CastReturnToVoidPtr2<R *, P1, P2, F>, I> Func; 5309 }; 5310 5311 template <class R, class P1, class P2, class P3, R *F(P1, P2, P3), class I> 5312 struct MaybeWrapReturn<Func3<R *, P1, P2, P3, F, I>, void *, 5313 typename disable_if_same<R *, void *>::Type> { 5314 typedef Func3<void *, P1, P2, P3, CastReturnToVoidPtr3<R *, P1, P2, P3, F>, I> 5315 Func; 5316 }; 5317 5318 /* If our function returns bool but we want one returning void*, wrap it in a 5319 * function that returns either the first param or UPB_BREAK. */ 5320 template <class P1, class P2, bool F(P1, P2), class I> 5321 struct MaybeWrapReturn<Func2<bool, P1, P2, F, I>, void *> { 5322 typedef Func2<void *, P1, P2, ReturnClosureOrBreak2<P1, P2, F>, I> Func; 5323 }; 5324 5325 template <class P1, class P2, class P3, bool F(P1, P2, P3), class I> 5326 struct MaybeWrapReturn<Func3<bool, P1, P2, P3, F, I>, void *> { 5327 typedef Func3<void *, P1, P2, P3, ReturnClosureOrBreak3<P1, P2, P3, F>, I> 5328 Func; 5329 }; 5330 5331 /* If our function returns void but we want one returning size_t, wrap it in a 5332 * function that returns the size argument. */ 5333 template <class P1, class P2, 5334 void F(P1, P2, const char *, size_t, const BufferHandle *), class I> 5335 struct MaybeWrapReturn< 5336 Func5<void, P1, P2, const char *, size_t, const BufferHandle *, F, I>, 5337 size_t> { 5338 typedef Func5<size_t, P1, P2, const char *, size_t, const BufferHandle *, 5339 ReturnStringLen<P1, P2, F>, I> Func; 5340 }; 5341 5342 /* If our function returns bool but we want one returning size_t, wrap it in a 5343 * function that returns either 0 or the buf size. */ 5344 template <class P1, class P2, 5345 bool F(P1, P2, const char *, size_t, const BufferHandle *), class I> 5346 struct MaybeWrapReturn< 5347 Func5<bool, P1, P2, const char *, size_t, const BufferHandle *, F, I>, 5348 size_t> { 5349 typedef Func5<size_t, P1, P2, const char *, size_t, const BufferHandle *, 5350 ReturnNOr0<P1, P2, F>, I> Func; 5351 }; 5352 5353 /* ConvertParams **************************************************************/ 5354 5355 /* Template class that converts the function parameters if necessary, and 5356 * ignores the HandlerData parameter if appropriate. 5357 * 5358 * Template parameter is the are FuncN function type. */ 5359 template <class F, class T> 5360 struct ConvertParams; 5361 5362 /* Function that discards the handler data parameter. */ 5363 template <class R, class P1, R F(P1)> 5364 R IgnoreHandlerData2(void *p1, const void *hd) { 5365 UPB_UNUSED(hd); 5366 return F(static_cast<P1>(p1)); 5367 } 5368 5369 template <class R, class P1, class P2Wrapper, class P2Wrapped, 5370 R F(P1, P2Wrapped)> 5371 R IgnoreHandlerData3(void *p1, const void *hd, P2Wrapper p2) { 5372 UPB_UNUSED(hd); 5373 return F(static_cast<P1>(p1), p2); 5374 } 5375 5376 template <class R, class P1, class P2, class P3, R F(P1, P2, P3)> 5377 R IgnoreHandlerData4(void *p1, const void *hd, P2 p2, P3 p3) { 5378 UPB_UNUSED(hd); 5379 return F(static_cast<P1>(p1), p2, p3); 5380 } 5381 5382 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4)> 5383 R IgnoreHandlerData5(void *p1, const void *hd, P2 p2, P3 p3, P4 p4) { 5384 UPB_UNUSED(hd); 5385 return F(static_cast<P1>(p1), p2, p3, p4); 5386 } 5387 5388 template <class R, class P1, R F(P1, const char*, size_t)> 5389 R IgnoreHandlerDataIgnoreHandle(void *p1, const void *hd, const char *p2, 5390 size_t p3, const BufferHandle *handle) { 5391 UPB_UNUSED(hd); 5392 UPB_UNUSED(handle); 5393 return F(static_cast<P1>(p1), p2, p3); 5394 } 5395 5396 /* Function that casts the handler data parameter. */ 5397 template <class R, class P1, class P2, R F(P1, P2)> 5398 R CastHandlerData2(void *c, const void *hd) { 5399 return F(static_cast<P1>(c), static_cast<P2>(hd)); 5400 } 5401 5402 template <class R, class P1, class P2, class P3Wrapper, class P3Wrapped, 5403 R F(P1, P2, P3Wrapped)> 5404 R CastHandlerData3(void *c, const void *hd, P3Wrapper p3) { 5405 return F(static_cast<P1>(c), static_cast<P2>(hd), p3); 5406 } 5407 5408 template <class R, class P1, class P2, class P3, class P4, class P5, 5409 R F(P1, P2, P3, P4, P5)> 5410 R CastHandlerData5(void *c, const void *hd, P3 p3, P4 p4, P5 p5) { 5411 return F(static_cast<P1>(c), static_cast<P2>(hd), p3, p4, p5); 5412 } 5413 5414 template <class R, class P1, class P2, R F(P1, P2, const char *, size_t)> 5415 R CastHandlerDataIgnoreHandle(void *c, const void *hd, const char *p3, 5416 size_t p4, const BufferHandle *handle) { 5417 UPB_UNUSED(handle); 5418 return F(static_cast<P1>(c), static_cast<P2>(hd), p3, p4); 5419 } 5420 5421 /* For unbound functions, ignore the handler data. */ 5422 template <class R, class P1, R F(P1), class I, class T> 5423 struct ConvertParams<Func1<R, P1, F, I>, T> { 5424 typedef Func2<R, void *, const void *, IgnoreHandlerData2<R, P1, F>, I> Func; 5425 }; 5426 5427 template <class R, class P1, class P2, R F(P1, P2), class I, 5428 class R2, class P1_2, class P2_2, class P3_2> 5429 struct ConvertParams<Func2<R, P1, P2, F, I>, 5430 R2 (*)(P1_2, P2_2, P3_2)> { 5431 typedef Func3<R, void *, const void *, P3_2, 5432 IgnoreHandlerData3<R, P1, P3_2, P2, F>, I> Func; 5433 }; 5434 5435 /* For StringBuffer only; this ignores both the handler data and the 5436 * BufferHandle. */ 5437 template <class R, class P1, R F(P1, const char *, size_t), class I, class T> 5438 struct ConvertParams<Func3<R, P1, const char *, size_t, F, I>, T> { 5439 typedef Func5<R, void *, const void *, const char *, size_t, 5440 const BufferHandle *, IgnoreHandlerDataIgnoreHandle<R, P1, F>, 5441 I> Func; 5442 }; 5443 5444 template <class R, class P1, class P2, class P3, class P4, R F(P1, P2, P3, P4), 5445 class I, class T> 5446 struct ConvertParams<Func4<R, P1, P2, P3, P4, F, I>, T> { 5447 typedef Func5<R, void *, const void *, P2, P3, P4, 5448 IgnoreHandlerData5<R, P1, P2, P3, P4, F>, I> Func; 5449 }; 5450 5451 /* For bound functions, cast the handler data. */ 5452 template <class R, class P1, class P2, R F(P1, P2), class I, class T> 5453 struct ConvertParams<BoundFunc2<R, P1, P2, F, I>, T> { 5454 typedef Func2<R, void *, const void *, CastHandlerData2<R, P1, P2, F>, I> 5455 Func; 5456 }; 5457 5458 template <class R, class P1, class P2, class P3, R F(P1, P2, P3), class I, 5459 class R2, class P1_2, class P2_2, class P3_2> 5460 struct ConvertParams<BoundFunc3<R, P1, P2, P3, F, I>, 5461 R2 (*)(P1_2, P2_2, P3_2)> { 5462 typedef Func3<R, void *, const void *, P3_2, 5463 CastHandlerData3<R, P1, P2, P3_2, P3, F>, I> Func; 5464 }; 5465 5466 /* For StringBuffer only; this ignores the BufferHandle. */ 5467 template <class R, class P1, class P2, R F(P1, P2, const char *, size_t), 5468 class I, class T> 5469 struct ConvertParams<BoundFunc4<R, P1, P2, const char *, size_t, F, I>, T> { 5470 typedef Func5<R, void *, const void *, const char *, size_t, 5471 const BufferHandle *, CastHandlerDataIgnoreHandle<R, P1, P2, F>, 5472 I> Func; 5473 }; 5474 5475 template <class R, class P1, class P2, class P3, class P4, class P5, 5476 R F(P1, P2, P3, P4, P5), class I, class T> 5477 struct ConvertParams<BoundFunc5<R, P1, P2, P3, P4, P5, F, I>, T> { 5478 typedef Func5<R, void *, const void *, P3, P4, P5, 5479 CastHandlerData5<R, P1, P2, P3, P4, P5, F>, I> Func; 5480 }; 5481 5482 /* utype/ltype are upper/lower-case, ctype is canonical C type, vtype is 5483 * variant C type. */ 5484 #define TYPE_METHODS(utype, ltype, ctype, vtype) \ 5485 template <> struct CanonicalType<vtype> { \ 5486 typedef ctype Type; \ 5487 }; \ 5488 template <> \ 5489 inline bool Handlers::SetValueHandler<vtype>( \ 5490 const FieldDef *f, \ 5491 const Handlers::utype ## Handler& handler) { \ 5492 assert(!handler.registered_); \ 5493 handler.AddCleanup(this); \ 5494 handler.registered_ = true; \ 5495 return upb_handlers_set##ltype(this, f, handler.handler_, &handler.attr_); \ 5496 } \ 5497 5498 TYPE_METHODS(Double, double, double, double) 5499 TYPE_METHODS(Float, float, float, float) 5500 TYPE_METHODS(UInt64, uint64, uint64_t, UPB_UINT64_T) 5501 TYPE_METHODS(UInt32, uint32, uint32_t, UPB_UINT32_T) 5502 TYPE_METHODS(Int64, int64, int64_t, UPB_INT64_T) 5503 TYPE_METHODS(Int32, int32, int32_t, UPB_INT32_T) 5504 TYPE_METHODS(Bool, bool, bool, bool) 5505 5506 #ifdef UPB_TWO_32BIT_TYPES 5507 TYPE_METHODS(Int32, int32, int32_t, UPB_INT32ALT_T) 5508 TYPE_METHODS(UInt32, uint32, uint32_t, UPB_UINT32ALT_T) 5509 #endif 5510 5511 #ifdef UPB_TWO_64BIT_TYPES 5512 TYPE_METHODS(Int64, int64, int64_t, UPB_INT64ALT_T) 5513 TYPE_METHODS(UInt64, uint64, uint64_t, UPB_UINT64ALT_T) 5514 #endif 5515 #undef TYPE_METHODS 5516 5517 template <> struct CanonicalType<Status*> { 5518 typedef Status* Type; 5519 }; 5520 5521 /* Type methods that are only one-per-canonical-type and not 5522 * one-per-cvariant. */ 5523 5524 #define TYPE_METHODS(utype, ctype) \ 5525 inline bool Handlers::Set##utype##Handler(const FieldDef *f, \ 5526 const utype##Handler &h) { \ 5527 return SetValueHandler<ctype>(f, h); \ 5528 } \ 5529 5530 TYPE_METHODS(Double, double) 5531 TYPE_METHODS(Float, float) 5532 TYPE_METHODS(UInt64, uint64_t) 5533 TYPE_METHODS(UInt32, uint32_t) 5534 TYPE_METHODS(Int64, int64_t) 5535 TYPE_METHODS(Int32, int32_t) 5536 TYPE_METHODS(Bool, bool) 5537 #undef TYPE_METHODS 5538 5539 template <class F> struct ReturnOf; 5540 5541 template <class R, class P1, class P2> 5542 struct ReturnOf<R (*)(P1, P2)> { 5543 typedef R Return; 5544 }; 5545 5546 template <class R, class P1, class P2, class P3> 5547 struct ReturnOf<R (*)(P1, P2, P3)> { 5548 typedef R Return; 5549 }; 5550 5551 template <class R, class P1, class P2, class P3, class P4> 5552 struct ReturnOf<R (*)(P1, P2, P3, P4)> { 5553 typedef R Return; 5554 }; 5555 5556 template <class R, class P1, class P2, class P3, class P4, class P5> 5557 struct ReturnOf<R (*)(P1, P2, P3, P4, P5)> { 5558 typedef R Return; 5559 }; 5560 5561 template<class T> const void *UniquePtrForType() { 5562 static const char ch = 0; 5563 return &ch; 5564 } 5565 5566 template <class T> 5567 template <class F> 5568 inline Handler<T>::Handler(F func) 5569 : registered_(false), 5570 cleanup_data_(func.GetData()), 5571 cleanup_func_(func.GetCleanup()) { 5572 upb_handlerattr_sethandlerdata(&attr_, func.GetData()); 5573 typedef typename ReturnOf<T>::Return Return; 5574 typedef typename ConvertParams<F, T>::Func ConvertedParamsFunc; 5575 typedef typename MaybeWrapReturn<ConvertedParamsFunc, Return>::Func 5576 ReturnWrappedFunc; 5577 handler_ = ReturnWrappedFunc().Call; 5578 5579 /* Set attributes based on what templates can statically tell us about the 5580 * user's function. */ 5581 5582 /* If the original function returns void, then we know that we wrapped it to 5583 * always return ok. */ 5584 bool always_ok = is_same<typename F::FuncInfo::Return, void>::value; 5585 attr_.SetAlwaysOk(always_ok); 5586 5587 /* Closure parameter and return type. */ 5588 attr_.SetClosureType(UniquePtrForType<typename F::FuncInfo::Closure>()); 5589 5590 /* We use the closure type (from the first parameter) if the return type is 5591 * void or bool, since these are the two cases we wrap to return the closure's 5592 * type anyway. 5593 * 5594 * This is all nonsense for non START* handlers, but it doesn't matter because 5595 * in that case the value will be ignored. */ 5596 typedef typename FirstUnlessVoidOrBool<typename F::FuncInfo::Return, 5597 typename F::FuncInfo::Closure>::value 5598 EffectiveReturn; 5599 attr_.SetReturnClosureType(UniquePtrForType<EffectiveReturn>()); 5600 } 5601 5602 template <class T> 5603 inline Handler<T>::~Handler() { 5604 assert(registered_); 5605 } 5606 5607 inline HandlerAttributes::HandlerAttributes() { upb_handlerattr_init(this); } 5608 inline HandlerAttributes::~HandlerAttributes() { upb_handlerattr_uninit(this); } 5609 inline bool HandlerAttributes::SetHandlerData(const void *hd) { 5610 return upb_handlerattr_sethandlerdata(this, hd); 5611 } 5612 inline const void* HandlerAttributes::handler_data() const { 5613 return upb_handlerattr_handlerdata(this); 5614 } 5615 inline bool HandlerAttributes::SetClosureType(const void *type) { 5616 return upb_handlerattr_setclosuretype(this, type); 5617 } 5618 inline const void* HandlerAttributes::closure_type() const { 5619 return upb_handlerattr_closuretype(this); 5620 } 5621 inline bool HandlerAttributes::SetReturnClosureType(const void *type) { 5622 return upb_handlerattr_setreturnclosuretype(this, type); 5623 } 5624 inline const void* HandlerAttributes::return_closure_type() const { 5625 return upb_handlerattr_returnclosuretype(this); 5626 } 5627 inline bool HandlerAttributes::SetAlwaysOk(bool always_ok) { 5628 return upb_handlerattr_setalwaysok(this, always_ok); 5629 } 5630 inline bool HandlerAttributes::always_ok() const { 5631 return upb_handlerattr_alwaysok(this); 5632 } 5633 5634 inline BufferHandle::BufferHandle() { upb_bufhandle_init(this); } 5635 inline BufferHandle::~BufferHandle() { upb_bufhandle_uninit(this); } 5636 inline const char* BufferHandle::buffer() const { 5637 return upb_bufhandle_buf(this); 5638 } 5639 inline size_t BufferHandle::object_offset() const { 5640 return upb_bufhandle_objofs(this); 5641 } 5642 inline void BufferHandle::SetBuffer(const char* buf, size_t ofs) { 5643 upb_bufhandle_setbuf(this, buf, ofs); 5644 } 5645 template <class T> 5646 void BufferHandle::SetAttachedObject(const T* obj) { 5647 upb_bufhandle_setobj(this, obj, UniquePtrForType<T>()); 5648 } 5649 template <class T> 5650 const T* BufferHandle::GetAttachedObject() const { 5651 return upb_bufhandle_objtype(this) == UniquePtrForType<T>() 5652 ? static_cast<const T *>(upb_bufhandle_obj(this)) 5653 : NULL; 5654 } 5655 5656 inline reffed_ptr<Handlers> Handlers::New(const MessageDef *m) { 5657 upb_handlers *h = upb_handlers_new(m, &h); 5658 return reffed_ptr<Handlers>(h, &h); 5659 } 5660 inline reffed_ptr<const Handlers> Handlers::NewFrozen( 5661 const MessageDef *m, upb_handlers_callback *callback, 5662 const void *closure) { 5663 const upb_handlers *h = upb_handlers_newfrozen(m, &h, callback, closure); 5664 return reffed_ptr<const Handlers>(h, &h); 5665 } 5666 inline const Status* Handlers::status() { 5667 return upb_handlers_status(this); 5668 } 5669 inline void Handlers::ClearError() { 5670 return upb_handlers_clearerr(this); 5671 } 5672 inline bool Handlers::Freeze(Status *s) { 5673 upb::Handlers* h = this; 5674 return upb_handlers_freeze(&h, 1, s); 5675 } 5676 inline bool Handlers::Freeze(Handlers *const *handlers, int n, Status *s) { 5677 return upb_handlers_freeze(handlers, n, s); 5678 } 5679 inline bool Handlers::Freeze(const std::vector<Handlers*>& h, Status* status) { 5680 return upb_handlers_freeze((Handlers* const*)&h[0], h.size(), status); 5681 } 5682 inline const MessageDef *Handlers::message_def() const { 5683 return upb_handlers_msgdef(this); 5684 } 5685 inline bool Handlers::AddCleanup(void *p, upb_handlerfree *func) { 5686 return upb_handlers_addcleanup(this, p, func); 5687 } 5688 inline bool Handlers::SetStartMessageHandler( 5689 const Handlers::StartMessageHandler &handler) { 5690 assert(!handler.registered_); 5691 handler.registered_ = true; 5692 handler.AddCleanup(this); 5693 return upb_handlers_setstartmsg(this, handler.handler_, &handler.attr_); 5694 } 5695 inline bool Handlers::SetEndMessageHandler( 5696 const Handlers::EndMessageHandler &handler) { 5697 assert(!handler.registered_); 5698 handler.registered_ = true; 5699 handler.AddCleanup(this); 5700 return upb_handlers_setendmsg(this, handler.handler_, &handler.attr_); 5701 } 5702 inline bool Handlers::SetStartStringHandler(const FieldDef *f, 5703 const StartStringHandler &handler) { 5704 assert(!handler.registered_); 5705 handler.registered_ = true; 5706 handler.AddCleanup(this); 5707 return upb_handlers_setstartstr(this, f, handler.handler_, &handler.attr_); 5708 } 5709 inline bool Handlers::SetEndStringHandler(const FieldDef *f, 5710 const EndFieldHandler &handler) { 5711 assert(!handler.registered_); 5712 handler.registered_ = true; 5713 handler.AddCleanup(this); 5714 return upb_handlers_setendstr(this, f, handler.handler_, &handler.attr_); 5715 } 5716 inline bool Handlers::SetStringHandler(const FieldDef *f, 5717 const StringHandler& handler) { 5718 assert(!handler.registered_); 5719 handler.registered_ = true; 5720 handler.AddCleanup(this); 5721 return upb_handlers_setstring(this, f, handler.handler_, &handler.attr_); 5722 } 5723 inline bool Handlers::SetStartSequenceHandler( 5724 const FieldDef *f, const StartFieldHandler &handler) { 5725 assert(!handler.registered_); 5726 handler.registered_ = true; 5727 handler.AddCleanup(this); 5728 return upb_handlers_setstartseq(this, f, handler.handler_, &handler.attr_); 5729 } 5730 inline bool Handlers::SetStartSubMessageHandler( 5731 const FieldDef *f, const StartFieldHandler &handler) { 5732 assert(!handler.registered_); 5733 handler.registered_ = true; 5734 handler.AddCleanup(this); 5735 return upb_handlers_setstartsubmsg(this, f, handler.handler_, &handler.attr_); 5736 } 5737 inline bool Handlers::SetEndSubMessageHandler(const FieldDef *f, 5738 const EndFieldHandler &handler) { 5739 assert(!handler.registered_); 5740 handler.registered_ = true; 5741 handler.AddCleanup(this); 5742 return upb_handlers_setendsubmsg(this, f, handler.handler_, &handler.attr_); 5743 } 5744 inline bool Handlers::SetEndSequenceHandler(const FieldDef *f, 5745 const EndFieldHandler &handler) { 5746 assert(!handler.registered_); 5747 handler.registered_ = true; 5748 handler.AddCleanup(this); 5749 return upb_handlers_setendseq(this, f, handler.handler_, &handler.attr_); 5750 } 5751 inline bool Handlers::SetSubHandlers(const FieldDef *f, const Handlers *sub) { 5752 return upb_handlers_setsubhandlers(this, f, sub); 5753 } 5754 inline const Handlers *Handlers::GetSubHandlers(const FieldDef *f) const { 5755 return upb_handlers_getsubhandlers(this, f); 5756 } 5757 inline const Handlers *Handlers::GetSubHandlers(Handlers::Selector sel) const { 5758 return upb_handlers_getsubhandlers_sel(this, sel); 5759 } 5760 inline bool Handlers::GetSelector(const FieldDef *f, Handlers::Type type, 5761 Handlers::Selector *s) { 5762 return upb_handlers_getselector(f, type, s); 5763 } 5764 inline Handlers::Selector Handlers::GetEndSelector(Handlers::Selector start) { 5765 return upb_handlers_getendselector(start); 5766 } 5767 inline Handlers::GenericFunction *Handlers::GetHandler( 5768 Handlers::Selector selector) { 5769 return upb_handlers_gethandler(this, selector); 5770 } 5771 inline const void *Handlers::GetHandlerData(Handlers::Selector selector) { 5772 return upb_handlers_gethandlerdata(this, selector); 5773 } 5774 5775 inline BytesHandler::BytesHandler() { 5776 upb_byteshandler_init(this); 5777 } 5778 5779 inline BytesHandler::~BytesHandler() {} 5780 5781 } /* namespace upb */ 5782 5783 #endif /* __cplusplus */ 5784 5785 5786 #undef UPB_TWO_32BIT_TYPES 5787 #undef UPB_TWO_64BIT_TYPES 5788 #undef UPB_INT32_T 5789 #undef UPB_UINT32_T 5790 #undef UPB_INT32ALT_T 5791 #undef UPB_UINT32ALT_T 5792 #undef UPB_INT64_T 5793 #undef UPB_UINT64_T 5794 #undef UPB_INT64ALT_T 5795 #undef UPB_UINT64ALT_T 5796 5797 #endif /* UPB_HANDLERS_INL_H_ */ 5798 5799 #endif /* UPB_HANDLERS_H */ 5800 /* 5801 ** upb::Sink (upb_sink) 5802 ** upb::BytesSink (upb_bytessink) 5803 ** 5804 ** A upb_sink is an object that binds a upb_handlers object to some runtime 5805 ** state. It is the object that can actually receive data via the upb_handlers 5806 ** interface. 5807 ** 5808 ** Unlike upb_def and upb_handlers, upb_sink is never frozen, immutable, or 5809 ** thread-safe. You can create as many of them as you want, but each one may 5810 ** only be used in a single thread at a time. 5811 ** 5812 ** If we compare with class-based OOP, a you can think of a upb_def as an 5813 ** abstract base class, a upb_handlers as a concrete derived class, and a 5814 ** upb_sink as an object (class instance). 5815 */ 5816 5817 #ifndef UPB_SINK_H 5818 #define UPB_SINK_H 5819 5820 5821 #ifdef __cplusplus 5822 namespace upb { 5823 class BufferSource; 5824 class BytesSink; 5825 class Sink; 5826 } 5827 #endif 5828 5829 UPB_DECLARE_TYPE(upb::BufferSource, upb_bufsrc) 5830 UPB_DECLARE_TYPE(upb::BytesSink, upb_bytessink) 5831 UPB_DECLARE_TYPE(upb::Sink, upb_sink) 5832 5833 #ifdef __cplusplus 5834 5835 /* A upb::Sink is an object that binds a upb::Handlers object to some runtime 5836 * state. It represents an endpoint to which data can be sent. 5837 * 5838 * TODO(haberman): right now all of these functions take selectors. Should they 5839 * take selectorbase instead? 5840 * 5841 * ie. instead of calling: 5842 * sink->StartString(FOO_FIELD_START_STRING, ...) 5843 * a selector base would let you say: 5844 * sink->StartString(FOO_FIELD, ...) 5845 * 5846 * This would make call sites a little nicer and require emitting fewer selector 5847 * definitions in .h files. 5848 * 5849 * But the current scheme has the benefit that you can retrieve a function 5850 * pointer for any handler with handlers->GetHandler(selector), without having 5851 * to have a separate GetHandler() function for each handler type. The JIT 5852 * compiler uses this. To accommodate we'd have to expose a separate 5853 * GetHandler() for every handler type. 5854 * 5855 * Also to ponder: selectors right now are independent of a specific Handlers 5856 * instance. In other words, they allocate a number to every possible handler 5857 * that *could* be registered, without knowing anything about what handlers 5858 * *are* registered. That means that using selectors as table offsets prohibits 5859 * us from compacting the handler table at Freeze() time. If the table is very 5860 * sparse, this could be wasteful. 5861 * 5862 * Having another selector-like thing that is specific to a Handlers instance 5863 * would allow this compacting, but then it would be impossible to write code 5864 * ahead-of-time that can be bound to any Handlers instance at runtime. For 5865 * example, a .proto file parser written as straight C will not know what 5866 * Handlers it will be bound to, so when it calls sink->StartString() what 5867 * selector will it pass? It needs a selector like we have today, that is 5868 * independent of any particular upb::Handlers. 5869 * 5870 * Is there a way then to allow Handlers table compaction? */ 5871 class upb::Sink { 5872 public: 5873 /* Constructor with no initialization; must be Reset() before use. */ 5874 Sink() {} 5875 5876 /* Constructs a new sink for the given frozen handlers and closure. 5877 * 5878 * TODO: once the Handlers know the expected closure type, verify that T 5879 * matches it. */ 5880 template <class T> Sink(const Handlers* handlers, T* closure); 5881 5882 /* Resets the value of the sink. */ 5883 template <class T> void Reset(const Handlers* handlers, T* closure); 5884 5885 /* Returns the top-level object that is bound to this sink. 5886 * 5887 * TODO: once the Handlers know the expected closure type, verify that T 5888 * matches it. */ 5889 template <class T> T* GetObject() const; 5890 5891 /* Functions for pushing data into the sink. 5892 * 5893 * These return false if processing should stop (either due to error or just 5894 * to suspend). 5895 * 5896 * These may not be called from within one of the same sink's handlers (in 5897 * other words, handlers are not re-entrant). */ 5898 5899 /* Should be called at the start and end of every message; both the top-level 5900 * message and submessages. This means that submessages should use the 5901 * following sequence: 5902 * sink->StartSubMessage(startsubmsg_selector); 5903 * sink->StartMessage(); 5904 * // ... 5905 * sink->EndMessage(&status); 5906 * sink->EndSubMessage(endsubmsg_selector); */ 5907 bool StartMessage(); 5908 bool EndMessage(Status* status); 5909 5910 /* Putting of individual values. These work for both repeated and 5911 * non-repeated fields, but for repeated fields you must wrap them in 5912 * calls to StartSequence()/EndSequence(). */ 5913 bool PutInt32(Handlers::Selector s, int32_t val); 5914 bool PutInt64(Handlers::Selector s, int64_t val); 5915 bool PutUInt32(Handlers::Selector s, uint32_t val); 5916 bool PutUInt64(Handlers::Selector s, uint64_t val); 5917 bool PutFloat(Handlers::Selector s, float val); 5918 bool PutDouble(Handlers::Selector s, double val); 5919 bool PutBool(Handlers::Selector s, bool val); 5920 5921 /* Putting of string/bytes values. Each string can consist of zero or more 5922 * non-contiguous buffers of data. 5923 * 5924 * For StartString(), the function will write a sink for the string to "sub." 5925 * The sub-sink must be used for any/all PutStringBuffer() calls. */ 5926 bool StartString(Handlers::Selector s, size_t size_hint, Sink* sub); 5927 size_t PutStringBuffer(Handlers::Selector s, const char *buf, size_t len, 5928 const BufferHandle *handle); 5929 bool EndString(Handlers::Selector s); 5930 5931 /* For submessage fields. 5932 * 5933 * For StartSubMessage(), the function will write a sink for the string to 5934 * "sub." The sub-sink must be used for any/all handlers called within the 5935 * submessage. */ 5936 bool StartSubMessage(Handlers::Selector s, Sink* sub); 5937 bool EndSubMessage(Handlers::Selector s); 5938 5939 /* For repeated fields of any type, the sequence of values must be wrapped in 5940 * these calls. 5941 * 5942 * For StartSequence(), the function will write a sink for the string to 5943 * "sub." The sub-sink must be used for any/all handlers called within the 5944 * sequence. */ 5945 bool StartSequence(Handlers::Selector s, Sink* sub); 5946 bool EndSequence(Handlers::Selector s); 5947 5948 /* Copy and assign specifically allowed. 5949 * We don't even bother making these members private because so many 5950 * functions need them and this is mainly just a dumb data container anyway. 5951 */ 5952 #else 5953 struct upb_sink { 5954 #endif 5955 const upb_handlers *handlers; 5956 void *closure; 5957 }; 5958 5959 #ifdef __cplusplus 5960 class upb::BytesSink { 5961 public: 5962 BytesSink() {} 5963 5964 /* Constructs a new sink for the given frozen handlers and closure. 5965 * 5966 * TODO(haberman): once the Handlers know the expected closure type, verify 5967 * that T matches it. */ 5968 template <class T> BytesSink(const BytesHandler* handler, T* closure); 5969 5970 /* Resets the value of the sink. */ 5971 template <class T> void Reset(const BytesHandler* handler, T* closure); 5972 5973 bool Start(size_t size_hint, void **subc); 5974 size_t PutBuffer(void *subc, const char *buf, size_t len, 5975 const BufferHandle *handle); 5976 bool End(); 5977 #else 5978 struct upb_bytessink { 5979 #endif 5980 const upb_byteshandler *handler; 5981 void *closure; 5982 }; 5983 5984 #ifdef __cplusplus 5985 5986 /* A class for pushing a flat buffer of data to a BytesSink. 5987 * You can construct an instance of this to get a resumable source, 5988 * or just call the static PutBuffer() to do a non-resumable push all in one 5989 * go. */ 5990 class upb::BufferSource { 5991 public: 5992 BufferSource(); 5993 BufferSource(const char* buf, size_t len, BytesSink* sink); 5994 5995 /* Returns true if the entire buffer was pushed successfully. Otherwise the 5996 * next call to PutNext() will resume where the previous one left off. 5997 * TODO(haberman): implement this. */ 5998 bool PutNext(); 5999 6000 /* A static version; with this version is it not possible to resume in the 6001 * case of failure or a partially-consumed buffer. */ 6002 static bool PutBuffer(const char* buf, size_t len, BytesSink* sink); 6003 6004 template <class T> static bool PutBuffer(const T& str, BytesSink* sink) { 6005 return PutBuffer(str.c_str(), str.size(), sink); 6006 } 6007 #else 6008 struct upb_bufsrc { 6009 char dummy; 6010 #endif 6011 }; 6012 6013 UPB_BEGIN_EXTERN_C 6014 6015 /* Inline definitions. */ 6016 6017 UPB_INLINE void upb_bytessink_reset(upb_bytessink *s, const upb_byteshandler *h, 6018 void *closure) { 6019 s->handler = h; 6020 s->closure = closure; 6021 } 6022 6023 UPB_INLINE bool upb_bytessink_start(upb_bytessink *s, size_t size_hint, 6024 void **subc) { 6025 typedef upb_startstr_handlerfunc func; 6026 func *start; 6027 *subc = s->closure; 6028 if (!s->handler) return true; 6029 start = (func *)s->handler->table[UPB_STARTSTR_SELECTOR].func; 6030 6031 if (!start) return true; 6032 *subc = start(s->closure, upb_handlerattr_handlerdata( 6033 &s->handler->table[UPB_STARTSTR_SELECTOR].attr), 6034 size_hint); 6035 return *subc != NULL; 6036 } 6037 6038 UPB_INLINE size_t upb_bytessink_putbuf(upb_bytessink *s, void *subc, 6039 const char *buf, size_t size, 6040 const upb_bufhandle* handle) { 6041 typedef upb_string_handlerfunc func; 6042 func *putbuf; 6043 if (!s->handler) return true; 6044 putbuf = (func *)s->handler->table[UPB_STRING_SELECTOR].func; 6045 6046 if (!putbuf) return true; 6047 return putbuf(subc, upb_handlerattr_handlerdata( 6048 &s->handler->table[UPB_STRING_SELECTOR].attr), 6049 buf, size, handle); 6050 } 6051 6052 UPB_INLINE bool upb_bytessink_end(upb_bytessink *s) { 6053 typedef upb_endfield_handlerfunc func; 6054 func *end; 6055 if (!s->handler) return true; 6056 end = (func *)s->handler->table[UPB_ENDSTR_SELECTOR].func; 6057 6058 if (!end) return true; 6059 return end(s->closure, 6060 upb_handlerattr_handlerdata( 6061 &s->handler->table[UPB_ENDSTR_SELECTOR].attr)); 6062 } 6063 6064 UPB_INLINE bool upb_bufsrc_putbuf(const char *buf, size_t len, 6065 upb_bytessink *sink) { 6066 void *subc; 6067 bool ret; 6068 upb_bufhandle handle; 6069 upb_bufhandle_init(&handle); 6070 upb_bufhandle_setbuf(&handle, buf, 0); 6071 ret = upb_bytessink_start(sink, len, &subc); 6072 if (ret && len != 0) { 6073 ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len); 6074 } 6075 if (ret) { 6076 ret = upb_bytessink_end(sink); 6077 } 6078 upb_bufhandle_uninit(&handle); 6079 return ret; 6080 } 6081 6082 #define PUTVAL(type, ctype) \ 6083 UPB_INLINE bool upb_sink_put##type(upb_sink *s, upb_selector_t sel, \ 6084 ctype val) { \ 6085 typedef upb_##type##_handlerfunc functype; \ 6086 functype *func; \ 6087 const void *hd; \ 6088 if (!s->handlers) return true; \ 6089 func = (functype *)upb_handlers_gethandler(s->handlers, sel); \ 6090 if (!func) return true; \ 6091 hd = upb_handlers_gethandlerdata(s->handlers, sel); \ 6092 return func(s->closure, hd, val); \ 6093 } 6094 6095 PUTVAL(int32, int32_t) 6096 PUTVAL(int64, int64_t) 6097 PUTVAL(uint32, uint32_t) 6098 PUTVAL(uint64, uint64_t) 6099 PUTVAL(float, float) 6100 PUTVAL(double, double) 6101 PUTVAL(bool, bool) 6102 #undef PUTVAL 6103 6104 UPB_INLINE void upb_sink_reset(upb_sink *s, const upb_handlers *h, void *c) { 6105 s->handlers = h; 6106 s->closure = c; 6107 } 6108 6109 UPB_INLINE size_t upb_sink_putstring(upb_sink *s, upb_selector_t sel, 6110 const char *buf, size_t n, 6111 const upb_bufhandle *handle) { 6112 typedef upb_string_handlerfunc func; 6113 func *handler; 6114 const void *hd; 6115 if (!s->handlers) return n; 6116 handler = (func *)upb_handlers_gethandler(s->handlers, sel); 6117 6118 if (!handler) return n; 6119 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6120 return handler(s->closure, hd, buf, n, handle); 6121 } 6122 6123 UPB_INLINE bool upb_sink_startmsg(upb_sink *s) { 6124 typedef upb_startmsg_handlerfunc func; 6125 func *startmsg; 6126 const void *hd; 6127 if (!s->handlers) return true; 6128 startmsg = (func*)upb_handlers_gethandler(s->handlers, UPB_STARTMSG_SELECTOR); 6129 6130 if (!startmsg) return true; 6131 hd = upb_handlers_gethandlerdata(s->handlers, UPB_STARTMSG_SELECTOR); 6132 return startmsg(s->closure, hd); 6133 } 6134 6135 UPB_INLINE bool upb_sink_endmsg(upb_sink *s, upb_status *status) { 6136 typedef upb_endmsg_handlerfunc func; 6137 func *endmsg; 6138 const void *hd; 6139 if (!s->handlers) return true; 6140 endmsg = (func *)upb_handlers_gethandler(s->handlers, UPB_ENDMSG_SELECTOR); 6141 6142 if (!endmsg) return true; 6143 hd = upb_handlers_gethandlerdata(s->handlers, UPB_ENDMSG_SELECTOR); 6144 return endmsg(s->closure, hd, status); 6145 } 6146 6147 UPB_INLINE bool upb_sink_startseq(upb_sink *s, upb_selector_t sel, 6148 upb_sink *sub) { 6149 typedef upb_startfield_handlerfunc func; 6150 func *startseq; 6151 const void *hd; 6152 sub->closure = s->closure; 6153 sub->handlers = s->handlers; 6154 if (!s->handlers) return true; 6155 startseq = (func*)upb_handlers_gethandler(s->handlers, sel); 6156 6157 if (!startseq) return true; 6158 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6159 sub->closure = startseq(s->closure, hd); 6160 return sub->closure ? true : false; 6161 } 6162 6163 UPB_INLINE bool upb_sink_endseq(upb_sink *s, upb_selector_t sel) { 6164 typedef upb_endfield_handlerfunc func; 6165 func *endseq; 6166 const void *hd; 6167 if (!s->handlers) return true; 6168 endseq = (func*)upb_handlers_gethandler(s->handlers, sel); 6169 6170 if (!endseq) return true; 6171 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6172 return endseq(s->closure, hd); 6173 } 6174 6175 UPB_INLINE bool upb_sink_startstr(upb_sink *s, upb_selector_t sel, 6176 size_t size_hint, upb_sink *sub) { 6177 typedef upb_startstr_handlerfunc func; 6178 func *startstr; 6179 const void *hd; 6180 sub->closure = s->closure; 6181 sub->handlers = s->handlers; 6182 if (!s->handlers) return true; 6183 startstr = (func*)upb_handlers_gethandler(s->handlers, sel); 6184 6185 if (!startstr) return true; 6186 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6187 sub->closure = startstr(s->closure, hd, size_hint); 6188 return sub->closure ? true : false; 6189 } 6190 6191 UPB_INLINE bool upb_sink_endstr(upb_sink *s, upb_selector_t sel) { 6192 typedef upb_endfield_handlerfunc func; 6193 func *endstr; 6194 const void *hd; 6195 if (!s->handlers) return true; 6196 endstr = (func*)upb_handlers_gethandler(s->handlers, sel); 6197 6198 if (!endstr) return true; 6199 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6200 return endstr(s->closure, hd); 6201 } 6202 6203 UPB_INLINE bool upb_sink_startsubmsg(upb_sink *s, upb_selector_t sel, 6204 upb_sink *sub) { 6205 typedef upb_startfield_handlerfunc func; 6206 func *startsubmsg; 6207 const void *hd; 6208 sub->closure = s->closure; 6209 if (!s->handlers) { 6210 sub->handlers = NULL; 6211 return true; 6212 } 6213 sub->handlers = upb_handlers_getsubhandlers_sel(s->handlers, sel); 6214 startsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel); 6215 6216 if (!startsubmsg) return true; 6217 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6218 sub->closure = startsubmsg(s->closure, hd); 6219 return sub->closure ? true : false; 6220 } 6221 6222 UPB_INLINE bool upb_sink_endsubmsg(upb_sink *s, upb_selector_t sel) { 6223 typedef upb_endfield_handlerfunc func; 6224 func *endsubmsg; 6225 const void *hd; 6226 if (!s->handlers) return true; 6227 endsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel); 6228 6229 if (!endsubmsg) return s->closure; 6230 hd = upb_handlers_gethandlerdata(s->handlers, sel); 6231 return endsubmsg(s->closure, hd); 6232 } 6233 6234 UPB_END_EXTERN_C 6235 6236 #ifdef __cplusplus 6237 6238 namespace upb { 6239 6240 template <class T> Sink::Sink(const Handlers* handlers, T* closure) { 6241 upb_sink_reset(this, handlers, closure); 6242 } 6243 template <class T> 6244 inline void Sink::Reset(const Handlers* handlers, T* closure) { 6245 upb_sink_reset(this, handlers, closure); 6246 } 6247 inline bool Sink::StartMessage() { 6248 return upb_sink_startmsg(this); 6249 } 6250 inline bool Sink::EndMessage(Status* status) { 6251 return upb_sink_endmsg(this, status); 6252 } 6253 inline bool Sink::PutInt32(Handlers::Selector sel, int32_t val) { 6254 return upb_sink_putint32(this, sel, val); 6255 } 6256 inline bool Sink::PutInt64(Handlers::Selector sel, int64_t val) { 6257 return upb_sink_putint64(this, sel, val); 6258 } 6259 inline bool Sink::PutUInt32(Handlers::Selector sel, uint32_t val) { 6260 return upb_sink_putuint32(this, sel, val); 6261 } 6262 inline bool Sink::PutUInt64(Handlers::Selector sel, uint64_t val) { 6263 return upb_sink_putuint64(this, sel, val); 6264 } 6265 inline bool Sink::PutFloat(Handlers::Selector sel, float val) { 6266 return upb_sink_putfloat(this, sel, val); 6267 } 6268 inline bool Sink::PutDouble(Handlers::Selector sel, double val) { 6269 return upb_sink_putdouble(this, sel, val); 6270 } 6271 inline bool Sink::PutBool(Handlers::Selector sel, bool val) { 6272 return upb_sink_putbool(this, sel, val); 6273 } 6274 inline bool Sink::StartString(Handlers::Selector sel, size_t size_hint, 6275 Sink *sub) { 6276 return upb_sink_startstr(this, sel, size_hint, sub); 6277 } 6278 inline size_t Sink::PutStringBuffer(Handlers::Selector sel, const char *buf, 6279 size_t len, const BufferHandle* handle) { 6280 return upb_sink_putstring(this, sel, buf, len, handle); 6281 } 6282 inline bool Sink::EndString(Handlers::Selector sel) { 6283 return upb_sink_endstr(this, sel); 6284 } 6285 inline bool Sink::StartSubMessage(Handlers::Selector sel, Sink* sub) { 6286 return upb_sink_startsubmsg(this, sel, sub); 6287 } 6288 inline bool Sink::EndSubMessage(Handlers::Selector sel) { 6289 return upb_sink_endsubmsg(this, sel); 6290 } 6291 inline bool Sink::StartSequence(Handlers::Selector sel, Sink* sub) { 6292 return upb_sink_startseq(this, sel, sub); 6293 } 6294 inline bool Sink::EndSequence(Handlers::Selector sel) { 6295 return upb_sink_endseq(this, sel); 6296 } 6297 6298 template <class T> 6299 BytesSink::BytesSink(const BytesHandler* handler, T* closure) { 6300 Reset(handler, closure); 6301 } 6302 6303 template <class T> 6304 void BytesSink::Reset(const BytesHandler *handler, T *closure) { 6305 upb_bytessink_reset(this, handler, closure); 6306 } 6307 inline bool BytesSink::Start(size_t size_hint, void **subc) { 6308 return upb_bytessink_start(this, size_hint, subc); 6309 } 6310 inline size_t BytesSink::PutBuffer(void *subc, const char *buf, size_t len, 6311 const BufferHandle *handle) { 6312 return upb_bytessink_putbuf(this, subc, buf, len, handle); 6313 } 6314 inline bool BytesSink::End() { 6315 return upb_bytessink_end(this); 6316 } 6317 6318 inline bool BufferSource::PutBuffer(const char *buf, size_t len, 6319 BytesSink *sink) { 6320 return upb_bufsrc_putbuf(buf, len, sink); 6321 } 6322 6323 } /* namespace upb */ 6324 #endif 6325 6326 #endif 6327 /* 6328 ** For handlers that do very tiny, very simple operations, the function call 6329 ** overhead of calling a handler can be significant. This file allows the 6330 ** user to define handlers that do something very simple like store the value 6331 ** to memory and/or set a hasbit. JIT compilers can then special-case these 6332 ** handlers and emit specialized code for them instead of actually calling the 6333 ** handler. 6334 ** 6335 ** The functionality is very simple/limited right now but may expand to be able 6336 ** to call another function. 6337 */ 6338 6339 #ifndef UPB_SHIM_H 6340 #define UPB_SHIM_H 6341 6342 6343 typedef struct { 6344 size_t offset; 6345 int32_t hasbit; 6346 } upb_shim_data; 6347 6348 #ifdef __cplusplus 6349 6350 namespace upb { 6351 6352 struct Shim { 6353 typedef upb_shim_data Data; 6354 6355 /* Sets a handler for the given field that writes the value to the given 6356 * offset and, if hasbit >= 0, sets a bit at the given bit offset. Returns 6357 * true if the handler was set successfully. */ 6358 static bool Set(Handlers *h, const FieldDef *f, size_t ofs, int32_t hasbit); 6359 6360 /* If this handler is a shim, returns the corresponding upb::Shim::Data and 6361 * stores the type in "type". Otherwise returns NULL. */ 6362 static const Data* GetData(const Handlers* h, Handlers::Selector s, 6363 FieldDef::Type* type); 6364 }; 6365 6366 } /* namespace upb */ 6367 6368 #endif 6369 6370 UPB_BEGIN_EXTERN_C 6371 6372 /* C API. */ 6373 bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset, 6374 int32_t hasbit); 6375 const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s, 6376 upb_fieldtype_t *type); 6377 6378 UPB_END_EXTERN_C 6379 6380 #ifdef __cplusplus 6381 /* C++ Wrappers. */ 6382 namespace upb { 6383 inline bool Shim::Set(Handlers* h, const FieldDef* f, size_t ofs, 6384 int32_t hasbit) { 6385 return upb_shim_set(h, f, ofs, hasbit); 6386 } 6387 inline const Shim::Data* Shim::GetData(const Handlers* h, Handlers::Selector s, 6388 FieldDef::Type* type) { 6389 return upb_shim_getdata(h, s, type); 6390 } 6391 } /* namespace upb */ 6392 #endif 6393 6394 #endif /* UPB_SHIM_H */ 6395 /* 6396 ** upb::SymbolTable (upb_symtab) 6397 ** 6398 ** A symtab (symbol table) stores a name->def map of upb_defs. Clients could 6399 ** always create such tables themselves, but upb_symtab has logic for resolving 6400 ** symbolic references, and in particular, for keeping a whole set of consistent 6401 ** defs when replacing some subset of those defs. This logic is nontrivial. 6402 ** 6403 ** This is a mixed C/C++ interface that offers a full API to both languages. 6404 ** See the top-level README for more information. 6405 */ 6406 6407 #ifndef UPB_SYMTAB_H_ 6408 #define UPB_SYMTAB_H_ 6409 6410 6411 #ifdef __cplusplus 6412 #include <vector> 6413 namespace upb { class SymbolTable; } 6414 #endif 6415 6416 UPB_DECLARE_DERIVED_TYPE(upb::SymbolTable, upb::RefCounted, 6417 upb_symtab, upb_refcounted) 6418 6419 typedef struct { 6420 UPB_PRIVATE_FOR_CPP 6421 upb_strtable_iter iter; 6422 upb_deftype_t type; 6423 } upb_symtab_iter; 6424 6425 #ifdef __cplusplus 6426 6427 /* Non-const methods in upb::SymbolTable are NOT thread-safe. */ 6428 class upb::SymbolTable { 6429 public: 6430 /* Returns a new symbol table with a single ref owned by "owner." 6431 * Returns NULL if memory allocation failed. */ 6432 static reffed_ptr<SymbolTable> New(); 6433 6434 /* Include RefCounted base methods. */ 6435 UPB_REFCOUNTED_CPPMETHODS 6436 6437 /* For all lookup functions, the returned pointer is not owned by the 6438 * caller; it may be invalidated by any non-const call or unref of the 6439 * SymbolTable! To protect against this, take a ref if desired. */ 6440 6441 /* Freezes the symbol table: prevents further modification of it. 6442 * After the Freeze() operation is successful, the SymbolTable must only be 6443 * accessed via a const pointer. 6444 * 6445 * Unlike with upb::MessageDef/upb::EnumDef/etc, freezing a SymbolTable is not 6446 * a necessary step in using a SymbolTable. If you have no need for it to be 6447 * immutable, there is no need to freeze it ever. However sometimes it is 6448 * useful, and SymbolTables that are statically compiled into the binary are 6449 * always frozen by nature. */ 6450 void Freeze(); 6451 6452 /* Resolves the given symbol using the rules described in descriptor.proto, 6453 * namely: 6454 * 6455 * If the name starts with a '.', it is fully-qualified. Otherwise, 6456 * C++-like scoping rules are used to find the type (i.e. first the nested 6457 * types within this message are searched, then within the parent, on up 6458 * to the root namespace). 6459 * 6460 * If not found, returns NULL. */ 6461 const Def* Resolve(const char* base, const char* sym) const; 6462 6463 /* Finds an entry in the symbol table with this exact name. If not found, 6464 * returns NULL. */ 6465 const Def* Lookup(const char *sym) const; 6466 const MessageDef* LookupMessage(const char *sym) const; 6467 const EnumDef* LookupEnum(const char *sym) const; 6468 6469 /* TODO: introduce a C++ iterator, but make it nice and templated so that if 6470 * you ask for an iterator of MessageDef the iterated elements are strongly 6471 * typed as MessageDef*. */ 6472 6473 /* Adds the given mutable defs to the symtab, resolving all symbols 6474 * (including enum default values) and finalizing the defs. Only one def per 6475 * name may be in the list, but defs can replace existing defs in the symtab. 6476 * All defs must have a name -- anonymous defs are not allowed. Anonymous 6477 * defs can still be frozen by calling upb_def_freeze() directly. 6478 * 6479 * Any existing defs that can reach defs that are being replaced will 6480 * themselves be replaced also, so that the resulting set of defs is fully 6481 * consistent. 6482 * 6483 * This logic implemented in this method is a convenience; ultimately it 6484 * calls some combination of upb_fielddef_setsubdef(), upb_def_dup(), and 6485 * upb_freeze(), any of which the client could call themself. However, since 6486 * the logic for doing so is nontrivial, we provide it here. 6487 * 6488 * The entire operation either succeeds or fails. If the operation fails, 6489 * the symtab is unchanged, false is returned, and status indicates the 6490 * error. The caller passes a ref on all defs to the symtab (even if the 6491 * operation fails). 6492 * 6493 * TODO(haberman): currently failure will leave the symtab unchanged, but may 6494 * leave the defs themselves partially resolved. Does this matter? If so we 6495 * could do a prepass that ensures that all symbols are resolvable and bail 6496 * if not, so we don't mutate anything until we know the operation will 6497 * succeed. 6498 * 6499 * TODO(haberman): since the defs must be mutable, refining a frozen def 6500 * requires making mutable copies of the entire tree. This is wasteful if 6501 * only a few messages are changing. We may want to add a way of adding a 6502 * tree of frozen defs to the symtab (perhaps an alternate constructor where 6503 * you pass the root of the tree?) */ 6504 bool Add(Def*const* defs, size_t n, void* ref_donor, Status* status); 6505 6506 bool Add(const std::vector<Def*>& defs, void *owner, Status* status) { 6507 return Add((Def*const*)&defs[0], defs.size(), owner, status); 6508 } 6509 6510 /* Resolves all subdefs for messages in this file and attempts to freeze the 6511 * file. If this succeeds, adds all the symbols to this SymbolTable 6512 * (replacing any existing ones with the same names). */ 6513 bool AddFile(FileDef* file, Status* s); 6514 6515 private: 6516 UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable) 6517 }; 6518 6519 #endif /* __cplusplus */ 6520 6521 UPB_BEGIN_EXTERN_C 6522 6523 /* Native C API. */ 6524 6525 /* Include refcounted methods like upb_symtab_ref(). */ 6526 UPB_REFCOUNTED_CMETHODS(upb_symtab, upb_symtab_upcast) 6527 6528 upb_symtab *upb_symtab_new(const void *owner); 6529 void upb_symtab_freeze(upb_symtab *s); 6530 const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base, 6531 const char *sym); 6532 const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym); 6533 const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym); 6534 const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym); 6535 bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n, 6536 void *ref_donor, upb_status *status); 6537 bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status* status); 6538 6539 /* upb_symtab_iter i; 6540 * for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i); 6541 * upb_symtab_next(&i)) { 6542 * const upb_def *def = upb_symtab_iter_def(&i); 6543 * // ... 6544 * } 6545 * 6546 * For C we don't have separate iterators for const and non-const. 6547 * It is the caller's responsibility to cast the upb_fielddef* to 6548 * const if the upb_msgdef* is const. */ 6549 void upb_symtab_begin(upb_symtab_iter *iter, const upb_symtab *s, 6550 upb_deftype_t type); 6551 void upb_symtab_next(upb_symtab_iter *iter); 6552 bool upb_symtab_done(const upb_symtab_iter *iter); 6553 const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter); 6554 6555 UPB_END_EXTERN_C 6556 6557 #ifdef __cplusplus 6558 /* C++ inline wrappers. */ 6559 namespace upb { 6560 inline reffed_ptr<SymbolTable> SymbolTable::New() { 6561 upb_symtab *s = upb_symtab_new(&s); 6562 return reffed_ptr<SymbolTable>(s, &s); 6563 } 6564 6565 inline void SymbolTable::Freeze() { 6566 return upb_symtab_freeze(this); 6567 } 6568 inline const Def *SymbolTable::Resolve(const char *base, 6569 const char *sym) const { 6570 return upb_symtab_resolve(this, base, sym); 6571 } 6572 inline const Def* SymbolTable::Lookup(const char *sym) const { 6573 return upb_symtab_lookup(this, sym); 6574 } 6575 inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const { 6576 return upb_symtab_lookupmsg(this, sym); 6577 } 6578 inline bool SymbolTable::Add( 6579 Def*const* defs, size_t n, void* ref_donor, Status* status) { 6580 return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status); 6581 } 6582 inline bool SymbolTable::AddFile(FileDef* file, Status* s) { 6583 return upb_symtab_addfile(this, file, s); 6584 } 6585 } /* namespace upb */ 6586 #endif 6587 6588 #endif /* UPB_SYMTAB_H_ */ 6589 /* 6590 ** upb::descriptor::Reader (upb_descreader) 6591 ** 6592 ** Provides a way of building upb::Defs from data in descriptor.proto format. 6593 */ 6594 6595 #ifndef UPB_DESCRIPTOR_H 6596 #define UPB_DESCRIPTOR_H 6597 6598 6599 #ifdef __cplusplus 6600 namespace upb { 6601 namespace descriptor { 6602 class Reader; 6603 } /* namespace descriptor */ 6604 } /* namespace upb */ 6605 #endif 6606 6607 UPB_DECLARE_TYPE(upb::descriptor::Reader, upb_descreader) 6608 6609 #ifdef __cplusplus 6610 6611 /* Class that receives descriptor data according to the descriptor.proto schema 6612 * and use it to build upb::Defs corresponding to that schema. */ 6613 class upb::descriptor::Reader { 6614 public: 6615 /* These handlers must have come from NewHandlers() and must outlive the 6616 * Reader. 6617 * 6618 * TODO: generate the handlers statically (like we do with the 6619 * descriptor.proto defs) so that there is no need to pass this parameter (or 6620 * to build/memory-manage the handlers at runtime at all). Unfortunately this 6621 * is a bit tricky to implement for Handlers, but necessary to simplify this 6622 * interface. */ 6623 static Reader* Create(Environment* env, const Handlers* handlers); 6624 6625 /* The reader's input; this is where descriptor.proto data should be sent. */ 6626 Sink* input(); 6627 6628 /* Use to get the FileDefs that have been parsed. */ 6629 size_t file_count() const; 6630 FileDef* file(size_t i) const; 6631 6632 /* Builds and returns handlers for the reader, owned by "owner." */ 6633 static Handlers* NewHandlers(const void* owner); 6634 6635 private: 6636 UPB_DISALLOW_POD_OPS(Reader, upb::descriptor::Reader) 6637 }; 6638 6639 #endif 6640 6641 UPB_BEGIN_EXTERN_C 6642 6643 /* C API. */ 6644 upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h); 6645 upb_sink *upb_descreader_input(upb_descreader *r); 6646 size_t upb_descreader_filecount(const upb_descreader *r); 6647 upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i); 6648 const upb_handlers *upb_descreader_newhandlers(const void *owner); 6649 6650 UPB_END_EXTERN_C 6651 6652 #ifdef __cplusplus 6653 /* C++ implementation details. ************************************************/ 6654 namespace upb { 6655 namespace descriptor { 6656 inline Reader* Reader::Create(Environment* e, const Handlers *h) { 6657 return upb_descreader_create(e, h); 6658 } 6659 inline Sink* Reader::input() { return upb_descreader_input(this); } 6660 inline size_t Reader::file_count() const { 6661 return upb_descreader_filecount(this); 6662 } 6663 inline FileDef* Reader::file(size_t i) const { 6664 return upb_descreader_file(this, i); 6665 } 6666 } /* namespace descriptor */ 6667 } /* namespace upb */ 6668 #endif 6669 6670 #endif /* UPB_DESCRIPTOR_H */ 6671 /* This file contains accessors for a set of compiled-in defs. 6672 * Note that unlike Google's protobuf, it does *not* define 6673 * generated classes or any other kind of data structure for 6674 * actually storing protobufs. It only contains *defs* which 6675 * let you reflect over a protobuf *schema*. 6676 */ 6677 /* This file was generated by upbc (the upb compiler) from the input 6678 * file: 6679 * 6680 * upb/descriptor/descriptor.proto 6681 * 6682 * Do not edit -- your changes will be discarded when the file is 6683 * regenerated. */ 6684 6685 #ifndef UPB_DESCRIPTOR_DESCRIPTOR_PROTO_UPB_H_ 6686 #define UPB_DESCRIPTOR_DESCRIPTOR_PROTO_UPB_H_ 6687 6688 6689 UPB_BEGIN_EXTERN_C 6690 6691 /* Enums */ 6692 6693 typedef enum { 6694 google_protobuf_FieldDescriptorProto_LABEL_OPTIONAL = 1, 6695 google_protobuf_FieldDescriptorProto_LABEL_REQUIRED = 2, 6696 google_protobuf_FieldDescriptorProto_LABEL_REPEATED = 3 6697 } google_protobuf_FieldDescriptorProto_Label; 6698 6699 typedef enum { 6700 google_protobuf_FieldDescriptorProto_TYPE_DOUBLE = 1, 6701 google_protobuf_FieldDescriptorProto_TYPE_FLOAT = 2, 6702 google_protobuf_FieldDescriptorProto_TYPE_INT64 = 3, 6703 google_protobuf_FieldDescriptorProto_TYPE_UINT64 = 4, 6704 google_protobuf_FieldDescriptorProto_TYPE_INT32 = 5, 6705 google_protobuf_FieldDescriptorProto_TYPE_FIXED64 = 6, 6706 google_protobuf_FieldDescriptorProto_TYPE_FIXED32 = 7, 6707 google_protobuf_FieldDescriptorProto_TYPE_BOOL = 8, 6708 google_protobuf_FieldDescriptorProto_TYPE_STRING = 9, 6709 google_protobuf_FieldDescriptorProto_TYPE_GROUP = 10, 6710 google_protobuf_FieldDescriptorProto_TYPE_MESSAGE = 11, 6711 google_protobuf_FieldDescriptorProto_TYPE_BYTES = 12, 6712 google_protobuf_FieldDescriptorProto_TYPE_UINT32 = 13, 6713 google_protobuf_FieldDescriptorProto_TYPE_ENUM = 14, 6714 google_protobuf_FieldDescriptorProto_TYPE_SFIXED32 = 15, 6715 google_protobuf_FieldDescriptorProto_TYPE_SFIXED64 = 16, 6716 google_protobuf_FieldDescriptorProto_TYPE_SINT32 = 17, 6717 google_protobuf_FieldDescriptorProto_TYPE_SINT64 = 18 6718 } google_protobuf_FieldDescriptorProto_Type; 6719 6720 typedef enum { 6721 google_protobuf_FieldOptions_STRING = 0, 6722 google_protobuf_FieldOptions_CORD = 1, 6723 google_protobuf_FieldOptions_STRING_PIECE = 2 6724 } google_protobuf_FieldOptions_CType; 6725 6726 typedef enum { 6727 google_protobuf_FieldOptions_JS_NORMAL = 0, 6728 google_protobuf_FieldOptions_JS_STRING = 1, 6729 google_protobuf_FieldOptions_JS_NUMBER = 2 6730 } google_protobuf_FieldOptions_JSType; 6731 6732 typedef enum { 6733 google_protobuf_FileOptions_SPEED = 1, 6734 google_protobuf_FileOptions_CODE_SIZE = 2, 6735 google_protobuf_FileOptions_LITE_RUNTIME = 3 6736 } google_protobuf_FileOptions_OptimizeMode; 6737 6738 /* MessageDefs: call these functions to get a ref to a msgdef. */ 6739 const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner); 6740 const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner); 6741 const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner); 6742 const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner); 6743 const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner); 6744 const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner); 6745 const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner); 6746 const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner); 6747 const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner); 6748 const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner); 6749 const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner); 6750 const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner); 6751 const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner); 6752 const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner); 6753 const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner); 6754 const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner); 6755 const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner); 6756 const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner); 6757 const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner); 6758 const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner); 6759 const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner); 6760 const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner); 6761 6762 /* EnumDefs: call these functions to get a ref to an enumdef. */ 6763 const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner); 6764 const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner); 6765 const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner); 6766 const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner); 6767 const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner); 6768 6769 /* Functions to test whether this message is of a certain type. */ 6770 UPB_INLINE bool upbdefs_google_protobuf_DescriptorProto_is(const upb_msgdef *m) { 6771 return strcmp(upb_msgdef_fullname(m), "google.protobuf.DescriptorProto") == 0; 6772 } 6773 UPB_INLINE bool upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(const upb_msgdef *m) { 6774 return strcmp(upb_msgdef_fullname(m), "google.protobuf.DescriptorProto.ExtensionRange") == 0; 6775 } 6776 UPB_INLINE bool upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(const upb_msgdef *m) { 6777 return strcmp(upb_msgdef_fullname(m), "google.protobuf.DescriptorProto.ReservedRange") == 0; 6778 } 6779 UPB_INLINE bool upbdefs_google_protobuf_EnumDescriptorProto_is(const upb_msgdef *m) { 6780 return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumDescriptorProto") == 0; 6781 } 6782 UPB_INLINE bool upbdefs_google_protobuf_EnumOptions_is(const upb_msgdef *m) { 6783 return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumOptions") == 0; 6784 } 6785 UPB_INLINE bool upbdefs_google_protobuf_EnumValueDescriptorProto_is(const upb_msgdef *m) { 6786 return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumValueDescriptorProto") == 0; 6787 } 6788 UPB_INLINE bool upbdefs_google_protobuf_EnumValueOptions_is(const upb_msgdef *m) { 6789 return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumValueOptions") == 0; 6790 } 6791 UPB_INLINE bool upbdefs_google_protobuf_FieldDescriptorProto_is(const upb_msgdef *m) { 6792 return strcmp(upb_msgdef_fullname(m), "google.protobuf.FieldDescriptorProto") == 0; 6793 } 6794 UPB_INLINE bool upbdefs_google_protobuf_FieldOptions_is(const upb_msgdef *m) { 6795 return strcmp(upb_msgdef_fullname(m), "google.protobuf.FieldOptions") == 0; 6796 } 6797 UPB_INLINE bool upbdefs_google_protobuf_FileDescriptorProto_is(const upb_msgdef *m) { 6798 return strcmp(upb_msgdef_fullname(m), "google.protobuf.FileDescriptorProto") == 0; 6799 } 6800 UPB_INLINE bool upbdefs_google_protobuf_FileDescriptorSet_is(const upb_msgdef *m) { 6801 return strcmp(upb_msgdef_fullname(m), "google.protobuf.FileDescriptorSet") == 0; 6802 } 6803 UPB_INLINE bool upbdefs_google_protobuf_FileOptions_is(const upb_msgdef *m) { 6804 return strcmp(upb_msgdef_fullname(m), "google.protobuf.FileOptions") == 0; 6805 } 6806 UPB_INLINE bool upbdefs_google_protobuf_MessageOptions_is(const upb_msgdef *m) { 6807 return strcmp(upb_msgdef_fullname(m), "google.protobuf.MessageOptions") == 0; 6808 } 6809 UPB_INLINE bool upbdefs_google_protobuf_MethodDescriptorProto_is(const upb_msgdef *m) { 6810 return strcmp(upb_msgdef_fullname(m), "google.protobuf.MethodDescriptorProto") == 0; 6811 } 6812 UPB_INLINE bool upbdefs_google_protobuf_MethodOptions_is(const upb_msgdef *m) { 6813 return strcmp(upb_msgdef_fullname(m), "google.protobuf.MethodOptions") == 0; 6814 } 6815 UPB_INLINE bool upbdefs_google_protobuf_OneofDescriptorProto_is(const upb_msgdef *m) { 6816 return strcmp(upb_msgdef_fullname(m), "google.protobuf.OneofDescriptorProto") == 0; 6817 } 6818 UPB_INLINE bool upbdefs_google_protobuf_ServiceDescriptorProto_is(const upb_msgdef *m) { 6819 return strcmp(upb_msgdef_fullname(m), "google.protobuf.ServiceDescriptorProto") == 0; 6820 } 6821 UPB_INLINE bool upbdefs_google_protobuf_ServiceOptions_is(const upb_msgdef *m) { 6822 return strcmp(upb_msgdef_fullname(m), "google.protobuf.ServiceOptions") == 0; 6823 } 6824 UPB_INLINE bool upbdefs_google_protobuf_SourceCodeInfo_is(const upb_msgdef *m) { 6825 return strcmp(upb_msgdef_fullname(m), "google.protobuf.SourceCodeInfo") == 0; 6826 } 6827 UPB_INLINE bool upbdefs_google_protobuf_SourceCodeInfo_Location_is(const upb_msgdef *m) { 6828 return strcmp(upb_msgdef_fullname(m), "google.protobuf.SourceCodeInfo.Location") == 0; 6829 } 6830 UPB_INLINE bool upbdefs_google_protobuf_UninterpretedOption_is(const upb_msgdef *m) { 6831 return strcmp(upb_msgdef_fullname(m), "google.protobuf.UninterpretedOption") == 0; 6832 } 6833 UPB_INLINE bool upbdefs_google_protobuf_UninterpretedOption_NamePart_is(const upb_msgdef *m) { 6834 return strcmp(upb_msgdef_fullname(m), "google.protobuf.UninterpretedOption.NamePart") == 0; 6835 } 6836 6837 /* Functions to test whether this enum is of a certain type. */ 6838 UPB_INLINE bool upbdefs_google_protobuf_FieldDescriptorProto_Label_is(const upb_enumdef *e) { 6839 return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldDescriptorProto.Label") == 0; 6840 } 6841 UPB_INLINE bool upbdefs_google_protobuf_FieldDescriptorProto_Type_is(const upb_enumdef *e) { 6842 return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldDescriptorProto.Type") == 0; 6843 } 6844 UPB_INLINE bool upbdefs_google_protobuf_FieldOptions_CType_is(const upb_enumdef *e) { 6845 return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldOptions.CType") == 0; 6846 } 6847 UPB_INLINE bool upbdefs_google_protobuf_FieldOptions_JSType_is(const upb_enumdef *e) { 6848 return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldOptions.JSType") == 0; 6849 } 6850 UPB_INLINE bool upbdefs_google_protobuf_FileOptions_OptimizeMode_is(const upb_enumdef *e) { 6851 return strcmp(upb_enumdef_fullname(e), "google.protobuf.FileOptions.OptimizeMode") == 0; 6852 } 6853 6854 6855 /* Functions to get a fielddef from a msgdef reference. */ 6856 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_end(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 2); } 6857 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_start(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 1); } 6858 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_end(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 2); } 6859 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_start(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 1); } 6860 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_enum_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 4); } 6861 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 6); } 6862 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension_range(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 5); } 6863 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_field(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6864 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6865 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_nested_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6866 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_oneof_decl(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 8); } 6867 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 7); } 6868 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 10); } 6869 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_range(const upb_msgdef *m) { assert(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 9); } 6870 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6871 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6872 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6873 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_allow_alias(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 2); } 6874 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 3); } 6875 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 999); } 6876 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6877 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_number(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6878 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6879 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 1); } 6880 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 999); } 6881 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_default_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); } 6882 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_extendee(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6883 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_json_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); } 6884 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_label(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); } 6885 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6886 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_number(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6887 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_oneof_index(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); } 6888 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); } 6889 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); } 6890 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); } 6891 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_ctype(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 1); } 6892 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 3); } 6893 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_jstype(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 6); } 6894 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_lazy(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 5); } 6895 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_packed(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 2); } 6896 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 999); } 6897 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_weak(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 10); } 6898 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_dependency(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6899 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_enum_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); } 6900 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_extension(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); } 6901 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_message_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); } 6902 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6903 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); } 6904 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6905 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_public_dependency(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); } 6906 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_service(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); } 6907 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_source_code_info(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); } 6908 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_syntax(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 12); } 6909 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_weak_dependency(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 11); } 6910 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorSet_f_file(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileDescriptorSet_is(m)); return upb_msgdef_itof(m, 1); } 6911 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_enable_arenas(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 31); } 6912 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_generic_services(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 16); } 6913 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_csharp_namespace(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 37); } 6914 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 23); } 6915 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_go_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 11); } 6916 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generate_equals_and_hash(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 20); } 6917 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generic_services(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 17); } 6918 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_multiple_files(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 10); } 6919 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_outer_classname(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 8); } 6920 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 1); } 6921 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_string_check_utf8(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 27); } 6922 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_javanano_use_deprecated_package(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 38); } 6923 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_objc_class_prefix(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 36); } 6924 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_optimize_for(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 9); } 6925 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_py_generic_services(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 18); } 6926 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 999); } 6927 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 3); } 6928 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_map_entry(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 7); } 6929 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_message_set_wire_format(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 1); } 6930 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_no_standard_descriptor_accessor(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 2); } 6931 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 999); } 6932 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_client_streaming(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); } 6933 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_input_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6934 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6935 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); } 6936 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_output_type(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6937 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_server_streaming(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); } 6938 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 33); } 6939 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 999); } 6940 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_OneofDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_OneofDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6941 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_method(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); } 6942 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); } 6943 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_options(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); } 6944 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_deprecated(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 33); } 6945 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_uninterpreted_option(const upb_msgdef *m) { assert(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 999); } 6946 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_comments(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 3); } 6947 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_detached_comments(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 6); } 6948 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_path(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 1); } 6949 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_span(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 2); } 6950 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_trailing_comments(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 4); } 6951 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_f_location(const upb_msgdef *m) { assert(upbdefs_google_protobuf_SourceCodeInfo_is(m)); return upb_msgdef_itof(m, 1); } 6952 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_is_extension(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 2); } 6953 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_name_part(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 1); } 6954 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_aggregate_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 8); } 6955 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_double_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 6); } 6956 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_identifier_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 3); } 6957 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_name(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 2); } 6958 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_negative_int_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 5); } 6959 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_positive_int_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 4); } 6960 UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_string_value(const upb_msgdef *m) { assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 7); } 6961 6962 UPB_END_EXTERN_C 6963 6964 #ifdef __cplusplus 6965 6966 namespace upbdefs { 6967 namespace google { 6968 namespace protobuf { 6969 6970 class DescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 6971 public: 6972 DescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 6973 : reffed_ptr(m, ref_donor) { 6974 assert(upbdefs_google_protobuf_DescriptorProto_is(m)); 6975 } 6976 6977 static DescriptorProto get() { 6978 const ::upb::MessageDef* m = upbdefs_google_protobuf_DescriptorProto_get(&m); 6979 return DescriptorProto(m, &m); 6980 } 6981 6982 class ExtensionRange : public ::upb::reffed_ptr<const ::upb::MessageDef> { 6983 public: 6984 ExtensionRange(const ::upb::MessageDef* m, const void *ref_donor = NULL) 6985 : reffed_ptr(m, ref_donor) { 6986 assert(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); 6987 } 6988 6989 static ExtensionRange get() { 6990 const ::upb::MessageDef* m = upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(&m); 6991 return ExtensionRange(m, &m); 6992 } 6993 }; 6994 6995 class ReservedRange : public ::upb::reffed_ptr<const ::upb::MessageDef> { 6996 public: 6997 ReservedRange(const ::upb::MessageDef* m, const void *ref_donor = NULL) 6998 : reffed_ptr(m, ref_donor) { 6999 assert(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); 7000 } 7001 7002 static ReservedRange get() { 7003 const ::upb::MessageDef* m = upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(&m); 7004 return ReservedRange(m, &m); 7005 } 7006 }; 7007 }; 7008 7009 class EnumDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7010 public: 7011 EnumDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7012 : reffed_ptr(m, ref_donor) { 7013 assert(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); 7014 } 7015 7016 static EnumDescriptorProto get() { 7017 const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumDescriptorProto_get(&m); 7018 return EnumDescriptorProto(m, &m); 7019 } 7020 }; 7021 7022 class EnumOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7023 public: 7024 EnumOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7025 : reffed_ptr(m, ref_donor) { 7026 assert(upbdefs_google_protobuf_EnumOptions_is(m)); 7027 } 7028 7029 static EnumOptions get() { 7030 const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumOptions_get(&m); 7031 return EnumOptions(m, &m); 7032 } 7033 }; 7034 7035 class EnumValueDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7036 public: 7037 EnumValueDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7038 : reffed_ptr(m, ref_donor) { 7039 assert(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); 7040 } 7041 7042 static EnumValueDescriptorProto get() { 7043 const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumValueDescriptorProto_get(&m); 7044 return EnumValueDescriptorProto(m, &m); 7045 } 7046 }; 7047 7048 class EnumValueOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7049 public: 7050 EnumValueOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7051 : reffed_ptr(m, ref_donor) { 7052 assert(upbdefs_google_protobuf_EnumValueOptions_is(m)); 7053 } 7054 7055 static EnumValueOptions get() { 7056 const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumValueOptions_get(&m); 7057 return EnumValueOptions(m, &m); 7058 } 7059 }; 7060 7061 class FieldDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7062 public: 7063 FieldDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7064 : reffed_ptr(m, ref_donor) { 7065 assert(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); 7066 } 7067 7068 static FieldDescriptorProto get() { 7069 const ::upb::MessageDef* m = upbdefs_google_protobuf_FieldDescriptorProto_get(&m); 7070 return FieldDescriptorProto(m, &m); 7071 } 7072 7073 class Label : public ::upb::reffed_ptr<const ::upb::EnumDef> { 7074 public: 7075 Label(const ::upb::EnumDef* e, const void *ref_donor = NULL) 7076 : reffed_ptr(e, ref_donor) { 7077 assert(upbdefs_google_protobuf_FieldDescriptorProto_Label_is(e)); 7078 } 7079 static Label get() { 7080 const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldDescriptorProto_Label_get(&e); 7081 return Label(e, &e); 7082 } 7083 }; 7084 7085 class Type : public ::upb::reffed_ptr<const ::upb::EnumDef> { 7086 public: 7087 Type(const ::upb::EnumDef* e, const void *ref_donor = NULL) 7088 : reffed_ptr(e, ref_donor) { 7089 assert(upbdefs_google_protobuf_FieldDescriptorProto_Type_is(e)); 7090 } 7091 static Type get() { 7092 const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldDescriptorProto_Type_get(&e); 7093 return Type(e, &e); 7094 } 7095 }; 7096 }; 7097 7098 class FieldOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7099 public: 7100 FieldOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7101 : reffed_ptr(m, ref_donor) { 7102 assert(upbdefs_google_protobuf_FieldOptions_is(m)); 7103 } 7104 7105 static FieldOptions get() { 7106 const ::upb::MessageDef* m = upbdefs_google_protobuf_FieldOptions_get(&m); 7107 return FieldOptions(m, &m); 7108 } 7109 7110 class CType : public ::upb::reffed_ptr<const ::upb::EnumDef> { 7111 public: 7112 CType(const ::upb::EnumDef* e, const void *ref_donor = NULL) 7113 : reffed_ptr(e, ref_donor) { 7114 assert(upbdefs_google_protobuf_FieldOptions_CType_is(e)); 7115 } 7116 static CType get() { 7117 const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldOptions_CType_get(&e); 7118 return CType(e, &e); 7119 } 7120 }; 7121 7122 class JSType : public ::upb::reffed_ptr<const ::upb::EnumDef> { 7123 public: 7124 JSType(const ::upb::EnumDef* e, const void *ref_donor = NULL) 7125 : reffed_ptr(e, ref_donor) { 7126 assert(upbdefs_google_protobuf_FieldOptions_JSType_is(e)); 7127 } 7128 static JSType get() { 7129 const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldOptions_JSType_get(&e); 7130 return JSType(e, &e); 7131 } 7132 }; 7133 }; 7134 7135 class FileDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7136 public: 7137 FileDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7138 : reffed_ptr(m, ref_donor) { 7139 assert(upbdefs_google_protobuf_FileDescriptorProto_is(m)); 7140 } 7141 7142 static FileDescriptorProto get() { 7143 const ::upb::MessageDef* m = upbdefs_google_protobuf_FileDescriptorProto_get(&m); 7144 return FileDescriptorProto(m, &m); 7145 } 7146 }; 7147 7148 class FileDescriptorSet : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7149 public: 7150 FileDescriptorSet(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7151 : reffed_ptr(m, ref_donor) { 7152 assert(upbdefs_google_protobuf_FileDescriptorSet_is(m)); 7153 } 7154 7155 static FileDescriptorSet get() { 7156 const ::upb::MessageDef* m = upbdefs_google_protobuf_FileDescriptorSet_get(&m); 7157 return FileDescriptorSet(m, &m); 7158 } 7159 }; 7160 7161 class FileOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7162 public: 7163 FileOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7164 : reffed_ptr(m, ref_donor) { 7165 assert(upbdefs_google_protobuf_FileOptions_is(m)); 7166 } 7167 7168 static FileOptions get() { 7169 const ::upb::MessageDef* m = upbdefs_google_protobuf_FileOptions_get(&m); 7170 return FileOptions(m, &m); 7171 } 7172 7173 class OptimizeMode : public ::upb::reffed_ptr<const ::upb::EnumDef> { 7174 public: 7175 OptimizeMode(const ::upb::EnumDef* e, const void *ref_donor = NULL) 7176 : reffed_ptr(e, ref_donor) { 7177 assert(upbdefs_google_protobuf_FileOptions_OptimizeMode_is(e)); 7178 } 7179 static OptimizeMode get() { 7180 const ::upb::EnumDef* e = upbdefs_google_protobuf_FileOptions_OptimizeMode_get(&e); 7181 return OptimizeMode(e, &e); 7182 } 7183 }; 7184 }; 7185 7186 class MessageOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7187 public: 7188 MessageOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7189 : reffed_ptr(m, ref_donor) { 7190 assert(upbdefs_google_protobuf_MessageOptions_is(m)); 7191 } 7192 7193 static MessageOptions get() { 7194 const ::upb::MessageDef* m = upbdefs_google_protobuf_MessageOptions_get(&m); 7195 return MessageOptions(m, &m); 7196 } 7197 }; 7198 7199 class MethodDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7200 public: 7201 MethodDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7202 : reffed_ptr(m, ref_donor) { 7203 assert(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); 7204 } 7205 7206 static MethodDescriptorProto get() { 7207 const ::upb::MessageDef* m = upbdefs_google_protobuf_MethodDescriptorProto_get(&m); 7208 return MethodDescriptorProto(m, &m); 7209 } 7210 }; 7211 7212 class MethodOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7213 public: 7214 MethodOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7215 : reffed_ptr(m, ref_donor) { 7216 assert(upbdefs_google_protobuf_MethodOptions_is(m)); 7217 } 7218 7219 static MethodOptions get() { 7220 const ::upb::MessageDef* m = upbdefs_google_protobuf_MethodOptions_get(&m); 7221 return MethodOptions(m, &m); 7222 } 7223 }; 7224 7225 class OneofDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7226 public: 7227 OneofDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7228 : reffed_ptr(m, ref_donor) { 7229 assert(upbdefs_google_protobuf_OneofDescriptorProto_is(m)); 7230 } 7231 7232 static OneofDescriptorProto get() { 7233 const ::upb::MessageDef* m = upbdefs_google_protobuf_OneofDescriptorProto_get(&m); 7234 return OneofDescriptorProto(m, &m); 7235 } 7236 }; 7237 7238 class ServiceDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7239 public: 7240 ServiceDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7241 : reffed_ptr(m, ref_donor) { 7242 assert(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); 7243 } 7244 7245 static ServiceDescriptorProto get() { 7246 const ::upb::MessageDef* m = upbdefs_google_protobuf_ServiceDescriptorProto_get(&m); 7247 return ServiceDescriptorProto(m, &m); 7248 } 7249 }; 7250 7251 class ServiceOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7252 public: 7253 ServiceOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7254 : reffed_ptr(m, ref_donor) { 7255 assert(upbdefs_google_protobuf_ServiceOptions_is(m)); 7256 } 7257 7258 static ServiceOptions get() { 7259 const ::upb::MessageDef* m = upbdefs_google_protobuf_ServiceOptions_get(&m); 7260 return ServiceOptions(m, &m); 7261 } 7262 }; 7263 7264 class SourceCodeInfo : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7265 public: 7266 SourceCodeInfo(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7267 : reffed_ptr(m, ref_donor) { 7268 assert(upbdefs_google_protobuf_SourceCodeInfo_is(m)); 7269 } 7270 7271 static SourceCodeInfo get() { 7272 const ::upb::MessageDef* m = upbdefs_google_protobuf_SourceCodeInfo_get(&m); 7273 return SourceCodeInfo(m, &m); 7274 } 7275 7276 class Location : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7277 public: 7278 Location(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7279 : reffed_ptr(m, ref_donor) { 7280 assert(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); 7281 } 7282 7283 static Location get() { 7284 const ::upb::MessageDef* m = upbdefs_google_protobuf_SourceCodeInfo_Location_get(&m); 7285 return Location(m, &m); 7286 } 7287 }; 7288 }; 7289 7290 class UninterpretedOption : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7291 public: 7292 UninterpretedOption(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7293 : reffed_ptr(m, ref_donor) { 7294 assert(upbdefs_google_protobuf_UninterpretedOption_is(m)); 7295 } 7296 7297 static UninterpretedOption get() { 7298 const ::upb::MessageDef* m = upbdefs_google_protobuf_UninterpretedOption_get(&m); 7299 return UninterpretedOption(m, &m); 7300 } 7301 7302 class NamePart : public ::upb::reffed_ptr<const ::upb::MessageDef> { 7303 public: 7304 NamePart(const ::upb::MessageDef* m, const void *ref_donor = NULL) 7305 : reffed_ptr(m, ref_donor) { 7306 assert(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); 7307 } 7308 7309 static NamePart get() { 7310 const ::upb::MessageDef* m = upbdefs_google_protobuf_UninterpretedOption_NamePart_get(&m); 7311 return NamePart(m, &m); 7312 } 7313 }; 7314 }; 7315 7316 } /* namespace protobuf */ 7317 } /* namespace google */ 7318 } /* namespace upbdefs */ 7319 7320 #endif /* __cplusplus */ 7321 7322 #endif /* UPB_DESCRIPTOR_DESCRIPTOR_PROTO_UPB_H_ */ 7323 /* 7324 ** Internal-only definitions for the decoder. 7325 */ 7326 7327 #ifndef UPB_DECODER_INT_H_ 7328 #define UPB_DECODER_INT_H_ 7329 7330 /* 7331 ** upb::pb::Decoder 7332 ** 7333 ** A high performance, streaming, resumable decoder for the binary protobuf 7334 ** format. 7335 ** 7336 ** This interface works the same regardless of what decoder backend is being 7337 ** used. A client of this class does not need to know whether decoding is using 7338 ** a JITted decoder (DynASM, LLVM, etc) or an interpreted decoder. By default, 7339 ** it will always use the fastest available decoder. However, you can call 7340 ** set_allow_jit(false) to disable any JIT decoder that might be available. 7341 ** This is primarily useful for testing purposes. 7342 */ 7343 7344 #ifndef UPB_DECODER_H_ 7345 #define UPB_DECODER_H_ 7346 7347 7348 #ifdef __cplusplus 7349 namespace upb { 7350 namespace pb { 7351 class CodeCache; 7352 class Decoder; 7353 class DecoderMethod; 7354 class DecoderMethodOptions; 7355 } /* namespace pb */ 7356 } /* namespace upb */ 7357 #endif 7358 7359 UPB_DECLARE_TYPE(upb::pb::CodeCache, upb_pbcodecache) 7360 UPB_DECLARE_TYPE(upb::pb::Decoder, upb_pbdecoder) 7361 UPB_DECLARE_TYPE(upb::pb::DecoderMethodOptions, upb_pbdecodermethodopts) 7362 7363 UPB_DECLARE_DERIVED_TYPE(upb::pb::DecoderMethod, upb::RefCounted, 7364 upb_pbdecodermethod, upb_refcounted) 7365 7366 /* The maximum number of bytes we are required to buffer internally between 7367 * calls to the decoder. The value is 14: a 5 byte unknown tag plus ten-byte 7368 * varint, less one because we are buffering an incomplete value. 7369 * 7370 * Should only be used by unit tests. */ 7371 #define UPB_DECODER_MAX_RESIDUAL_BYTES 14 7372 7373 #ifdef __cplusplus 7374 7375 /* The parameters one uses to construct a DecoderMethod. 7376 * TODO(haberman): move allowjit here? Seems more convenient for users. 7377 * TODO(haberman): move this to be heap allocated for ABI stability. */ 7378 class upb::pb::DecoderMethodOptions { 7379 public: 7380 /* Parameter represents the destination handlers that this method will push 7381 * to. */ 7382 explicit DecoderMethodOptions(const Handlers* dest_handlers); 7383 7384 /* Should the decoder push submessages to lazy handlers for fields that have 7385 * them? The caller should set this iff the lazy handlers expect data that is 7386 * in protobuf binary format and the caller wishes to lazy parse it. */ 7387 void set_lazy(bool lazy); 7388 #else 7389 struct upb_pbdecodermethodopts { 7390 #endif 7391 const upb_handlers *handlers; 7392 bool lazy; 7393 }; 7394 7395 #ifdef __cplusplus 7396 7397 /* Represents the code to parse a protobuf according to a destination 7398 * Handlers. */ 7399 class upb::pb::DecoderMethod { 7400 public: 7401 /* Include base methods from upb::ReferenceCounted. */ 7402 UPB_REFCOUNTED_CPPMETHODS 7403 7404 /* The destination handlers that are statically bound to this method. 7405 * This method is only capable of outputting to a sink that uses these 7406 * handlers. */ 7407 const Handlers* dest_handlers() const; 7408 7409 /* The input handlers for this decoder method. */ 7410 const BytesHandler* input_handler() const; 7411 7412 /* Whether this method is native. */ 7413 bool is_native() const; 7414 7415 /* Convenience method for generating a DecoderMethod without explicitly 7416 * creating a CodeCache. */ 7417 static reffed_ptr<const DecoderMethod> New(const DecoderMethodOptions& opts); 7418 7419 private: 7420 UPB_DISALLOW_POD_OPS(DecoderMethod, upb::pb::DecoderMethod) 7421 }; 7422 7423 #endif 7424 7425 /* Preallocation hint: decoder won't allocate more bytes than this when first 7426 * constructed. This hint may be an overestimate for some build configurations. 7427 * But if the decoder library is upgraded without recompiling the application, 7428 * it may be an underestimate. */ 7429 #define UPB_PB_DECODER_SIZE 4416 7430 7431 #ifdef __cplusplus 7432 7433 /* A Decoder receives binary protobuf data on its input sink and pushes the 7434 * decoded data to its output sink. */ 7435 class upb::pb::Decoder { 7436 public: 7437 /* Constructs a decoder instance for the given method, which must outlive this 7438 * decoder. Any errors during parsing will be set on the given status, which 7439 * must also outlive this decoder. 7440 * 7441 * The sink must match the given method. */ 7442 static Decoder* Create(Environment* env, const DecoderMethod* method, 7443 Sink* output); 7444 7445 /* Returns the DecoderMethod this decoder is parsing from. */ 7446 const DecoderMethod* method() const; 7447 7448 /* The sink on which this decoder receives input. */ 7449 BytesSink* input(); 7450 7451 /* Returns number of bytes successfully parsed. 7452 * 7453 * This can be useful for determining the stream position where an error 7454 * occurred. 7455 * 7456 * This value may not be up-to-date when called from inside a parsing 7457 * callback. */ 7458 uint64_t BytesParsed() const; 7459 7460 /* Gets/sets the parsing nexting limit. If the total number of nested 7461 * submessages and repeated fields hits this limit, parsing will fail. This 7462 * is a resource limit that controls the amount of memory used by the parsing 7463 * stack. 7464 * 7465 * Setting the limit will fail if the parser is currently suspended at a depth 7466 * greater than this, or if memory allocation of the stack fails. */ 7467 size_t max_nesting() const; 7468 bool set_max_nesting(size_t max); 7469 7470 void Reset(); 7471 7472 static const size_t kSize = UPB_PB_DECODER_SIZE; 7473 7474 private: 7475 UPB_DISALLOW_POD_OPS(Decoder, upb::pb::Decoder) 7476 }; 7477 7478 #endif /* __cplusplus */ 7479 7480 #ifdef __cplusplus 7481 7482 /* A class for caching protobuf processing code, whether bytecode for the 7483 * interpreted decoder or machine code for the JIT. 7484 * 7485 * This class is not thread-safe. 7486 * 7487 * TODO(haberman): move this to be heap allocated for ABI stability. */ 7488 class upb::pb::CodeCache { 7489 public: 7490 CodeCache(); 7491 ~CodeCache(); 7492 7493 /* Whether the cache is allowed to generate machine code. Defaults to true. 7494 * There is no real reason to turn it off except for testing or if you are 7495 * having a specific problem with the JIT. 7496 * 7497 * Note that allow_jit = true does not *guarantee* that the code will be JIT 7498 * compiled. If this platform is not supported or the JIT was not compiled 7499 * in, the code may still be interpreted. */ 7500 bool allow_jit() const; 7501 7502 /* This may only be called when the object is first constructed, and prior to 7503 * any code generation, otherwise returns false and does nothing. */ 7504 bool set_allow_jit(bool allow); 7505 7506 /* Returns a DecoderMethod that can push data to the given handlers. 7507 * If a suitable method already exists, it will be returned from the cache. 7508 * 7509 * Specifying the destination handlers here allows the DecoderMethod to be 7510 * statically bound to the destination handlers if possible, which can allow 7511 * more efficient decoding. However the returned method may or may not 7512 * actually be statically bound. But in all cases, the returned method can 7513 * push data to the given handlers. */ 7514 const DecoderMethod *GetDecoderMethod(const DecoderMethodOptions& opts); 7515 7516 /* If/when someone needs to explicitly create a dynamically-bound 7517 * DecoderMethod*, we can add a method to get it here. */ 7518 7519 private: 7520 UPB_DISALLOW_COPY_AND_ASSIGN(CodeCache) 7521 #else 7522 struct upb_pbcodecache { 7523 #endif 7524 bool allow_jit_; 7525 7526 /* Array of mgroups. */ 7527 upb_inttable groups; 7528 }; 7529 7530 UPB_BEGIN_EXTERN_C 7531 7532 upb_pbdecoder *upb_pbdecoder_create(upb_env *e, 7533 const upb_pbdecodermethod *method, 7534 upb_sink *output); 7535 const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d); 7536 upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d); 7537 uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d); 7538 size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d); 7539 bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max); 7540 void upb_pbdecoder_reset(upb_pbdecoder *d); 7541 7542 void upb_pbdecodermethodopts_init(upb_pbdecodermethodopts *opts, 7543 const upb_handlers *h); 7544 void upb_pbdecodermethodopts_setlazy(upb_pbdecodermethodopts *opts, bool lazy); 7545 7546 7547 /* Include refcounted methods like upb_pbdecodermethod_ref(). */ 7548 UPB_REFCOUNTED_CMETHODS(upb_pbdecodermethod, upb_pbdecodermethod_upcast) 7549 7550 const upb_handlers *upb_pbdecodermethod_desthandlers( 7551 const upb_pbdecodermethod *m); 7552 const upb_byteshandler *upb_pbdecodermethod_inputhandler( 7553 const upb_pbdecodermethod *m); 7554 bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m); 7555 const upb_pbdecodermethod *upb_pbdecodermethod_new( 7556 const upb_pbdecodermethodopts *opts, const void *owner); 7557 7558 void upb_pbcodecache_init(upb_pbcodecache *c); 7559 void upb_pbcodecache_uninit(upb_pbcodecache *c); 7560 bool upb_pbcodecache_allowjit(const upb_pbcodecache *c); 7561 bool upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow); 7562 const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod( 7563 upb_pbcodecache *c, const upb_pbdecodermethodopts *opts); 7564 7565 UPB_END_EXTERN_C 7566 7567 #ifdef __cplusplus 7568 7569 namespace upb { 7570 7571 namespace pb { 7572 7573 /* static */ 7574 inline Decoder* Decoder::Create(Environment* env, const DecoderMethod* m, 7575 Sink* sink) { 7576 return upb_pbdecoder_create(env, m, sink); 7577 } 7578 inline const DecoderMethod* Decoder::method() const { 7579 return upb_pbdecoder_method(this); 7580 } 7581 inline BytesSink* Decoder::input() { 7582 return upb_pbdecoder_input(this); 7583 } 7584 inline uint64_t Decoder::BytesParsed() const { 7585 return upb_pbdecoder_bytesparsed(this); 7586 } 7587 inline size_t Decoder::max_nesting() const { 7588 return upb_pbdecoder_maxnesting(this); 7589 } 7590 inline bool Decoder::set_max_nesting(size_t max) { 7591 return upb_pbdecoder_setmaxnesting(this, max); 7592 } 7593 inline void Decoder::Reset() { upb_pbdecoder_reset(this); } 7594 7595 inline DecoderMethodOptions::DecoderMethodOptions(const Handlers* h) { 7596 upb_pbdecodermethodopts_init(this, h); 7597 } 7598 inline void DecoderMethodOptions::set_lazy(bool lazy) { 7599 upb_pbdecodermethodopts_setlazy(this, lazy); 7600 } 7601 7602 inline const Handlers* DecoderMethod::dest_handlers() const { 7603 return upb_pbdecodermethod_desthandlers(this); 7604 } 7605 inline const BytesHandler* DecoderMethod::input_handler() const { 7606 return upb_pbdecodermethod_inputhandler(this); 7607 } 7608 inline bool DecoderMethod::is_native() const { 7609 return upb_pbdecodermethod_isnative(this); 7610 } 7611 /* static */ 7612 inline reffed_ptr<const DecoderMethod> DecoderMethod::New( 7613 const DecoderMethodOptions &opts) { 7614 const upb_pbdecodermethod *m = upb_pbdecodermethod_new(&opts, &m); 7615 return reffed_ptr<const DecoderMethod>(m, &m); 7616 } 7617 7618 inline CodeCache::CodeCache() { 7619 upb_pbcodecache_init(this); 7620 } 7621 inline CodeCache::~CodeCache() { 7622 upb_pbcodecache_uninit(this); 7623 } 7624 inline bool CodeCache::allow_jit() const { 7625 return upb_pbcodecache_allowjit(this); 7626 } 7627 inline bool CodeCache::set_allow_jit(bool allow) { 7628 return upb_pbcodecache_setallowjit(this, allow); 7629 } 7630 inline const DecoderMethod *CodeCache::GetDecoderMethod( 7631 const DecoderMethodOptions& opts) { 7632 return upb_pbcodecache_getdecodermethod(this, &opts); 7633 } 7634 7635 } /* namespace pb */ 7636 } /* namespace upb */ 7637 7638 #endif /* __cplusplus */ 7639 7640 #endif /* UPB_DECODER_H_ */ 7641 7642 /* C++ names are not actually used since this type isn't exposed to users. */ 7643 #ifdef __cplusplus 7644 namespace upb { 7645 namespace pb { 7646 class MessageGroup; 7647 } /* namespace pb */ 7648 } /* namespace upb */ 7649 #endif 7650 UPB_DECLARE_DERIVED_TYPE(upb::pb::MessageGroup, upb::RefCounted, 7651 mgroup, upb_refcounted) 7652 7653 /* Opcode definitions. The canonical meaning of each opcode is its 7654 * implementation in the interpreter (the JIT is written to match this). 7655 * 7656 * All instructions have the opcode in the low byte. 7657 * Instruction format for most instructions is: 7658 * 7659 * +-------------------+--------+ 7660 * | arg (24) | op (8) | 7661 * +-------------------+--------+ 7662 * 7663 * Exceptions are indicated below. A few opcodes are multi-word. */ 7664 typedef enum { 7665 /* Opcodes 1-8, 13, 15-18 parse their respective descriptor types. 7666 * Arg for all of these is the upb selector for this field. */ 7667 #define T(type) OP_PARSE_ ## type = UPB_DESCRIPTOR_TYPE_ ## type 7668 T(DOUBLE), T(FLOAT), T(INT64), T(UINT64), T(INT32), T(FIXED64), T(FIXED32), 7669 T(BOOL), T(UINT32), T(SFIXED32), T(SFIXED64), T(SINT32), T(SINT64), 7670 #undef T 7671 OP_STARTMSG = 9, /* No arg. */ 7672 OP_ENDMSG = 10, /* No arg. */ 7673 OP_STARTSEQ = 11, 7674 OP_ENDSEQ = 12, 7675 OP_STARTSUBMSG = 14, 7676 OP_ENDSUBMSG = 19, 7677 OP_STARTSTR = 20, 7678 OP_STRING = 21, 7679 OP_ENDSTR = 22, 7680 7681 OP_PUSHTAGDELIM = 23, /* No arg. */ 7682 OP_PUSHLENDELIM = 24, /* No arg. */ 7683 OP_POP = 25, /* No arg. */ 7684 OP_SETDELIM = 26, /* No arg. */ 7685 OP_SETBIGGROUPNUM = 27, /* two words: 7686 * | unused (24) | opc (8) | 7687 * | groupnum (32) | */ 7688 OP_CHECKDELIM = 28, 7689 OP_CALL = 29, 7690 OP_RET = 30, 7691 OP_BRANCH = 31, 7692 7693 /* Different opcodes depending on how many bytes expected. */ 7694 OP_TAG1 = 32, /* | match tag (16) | jump target (8) | opc (8) | */ 7695 OP_TAG2 = 33, /* | match tag (16) | jump target (8) | opc (8) | */ 7696 OP_TAGN = 34, /* three words: */ 7697 /* | unused (16) | jump target(8) | opc (8) | */ 7698 /* | match tag 1 (32) | */ 7699 /* | match tag 2 (32) | */ 7700 7701 OP_SETDISPATCH = 35, /* N words: */ 7702 /* | unused (24) | opc | */ 7703 /* | upb_inttable* (32 or 64) | */ 7704 7705 OP_DISPATCH = 36, /* No arg. */ 7706 7707 OP_HALT = 37 /* No arg. */ 7708 } opcode; 7709 7710 #define OP_MAX OP_HALT 7711 7712 UPB_INLINE opcode getop(uint32_t instr) { return instr & 0xff; } 7713 7714 /* Method group; represents a set of decoder methods that had their code 7715 * emitted together, and must therefore be freed together. Immutable once 7716 * created. It is possible we may want to expose this to users at some point. 7717 * 7718 * Overall ownership of Decoder objects looks like this: 7719 * 7720 * +----------+ 7721 * | | <---> DecoderMethod 7722 * | method | 7723 * CodeCache ---> | group | <---> DecoderMethod 7724 * | | 7725 * | (mgroup) | <---> DecoderMethod 7726 * +----------+ 7727 */ 7728 struct mgroup { 7729 upb_refcounted base; 7730 7731 /* Maps upb_msgdef/upb_handlers -> upb_pbdecodermethod. We own refs on the 7732 * methods. */ 7733 upb_inttable methods; 7734 7735 /* When we add the ability to link to previously existing mgroups, we'll 7736 * need an array of mgroups we reference here, and own refs on them. */ 7737 7738 /* The bytecode for our methods, if any exists. Owned by us. */ 7739 uint32_t *bytecode; 7740 uint32_t *bytecode_end; 7741 7742 #ifdef UPB_USE_JIT_X64 7743 /* JIT-generated machine code, if any. */ 7744 upb_string_handlerfunc *jit_code; 7745 /* The size of the jit_code (required to munmap()). */ 7746 size_t jit_size; 7747 char *debug_info; 7748 void *dl; 7749 #endif 7750 }; 7751 7752 /* The maximum that any submessages can be nested. Matches proto2's limit. 7753 * This specifies the size of the decoder's statically-sized array and therefore 7754 * setting it high will cause the upb::pb::Decoder object to be larger. 7755 * 7756 * If necessary we can add a runtime-settable property to Decoder that allow 7757 * this to be larger than the compile-time setting, but this would add 7758 * complexity, particularly since we would have to decide how/if to give users 7759 * the ability to set a custom memory allocation function. */ 7760 #define UPB_DECODER_MAX_NESTING 64 7761 7762 /* Internal-only struct used by the decoder. */ 7763 typedef struct { 7764 /* Space optimization note: we store two pointers here that the JIT 7765 * doesn't need at all; the upb_handlers* inside the sink and 7766 * the dispatch table pointer. We can optimze so that the JIT uses 7767 * smaller stack frames than the interpreter. The only thing we need 7768 * to guarantee is that the fallback routines can find end_ofs. */ 7769 upb_sink sink; 7770 7771 /* The absolute stream offset of the end-of-frame delimiter. 7772 * Non-delimited frames (groups and non-packed repeated fields) reuse the 7773 * delimiter of their parent, even though the frame may not end there. 7774 * 7775 * NOTE: the JIT stores a slightly different value here for non-top frames. 7776 * It stores the value relative to the end of the enclosed message. But the 7777 * top frame is still stored the same way, which is important for ensuring 7778 * that calls from the JIT into C work correctly. */ 7779 uint64_t end_ofs; 7780 const uint32_t *base; 7781 7782 /* 0 indicates a length-delimited field. 7783 * A positive number indicates a known group. 7784 * A negative number indicates an unknown group. */ 7785 int32_t groupnum; 7786 upb_inttable *dispatch; /* Not used by the JIT. */ 7787 } upb_pbdecoder_frame; 7788 7789 struct upb_pbdecodermethod { 7790 upb_refcounted base; 7791 7792 /* While compiling, the base is relative in "ofs", after compiling it is 7793 * absolute in "ptr". */ 7794 union { 7795 uint32_t ofs; /* PC offset of method. */ 7796 void *ptr; /* Pointer to bytecode or machine code for this method. */ 7797 } code_base; 7798 7799 /* The decoder method group to which this method belongs. We own a ref. 7800 * Owning a ref on the entire group is more coarse-grained than is strictly 7801 * necessary; all we truly require is that methods we directly reference 7802 * outlive us, while the group could contain many other messages we don't 7803 * require. But the group represents the messages that were 7804 * allocated+compiled together, so it makes the most sense to free them 7805 * together also. */ 7806 const upb_refcounted *group; 7807 7808 /* Whether this method is native code or bytecode. */ 7809 bool is_native_; 7810 7811 /* The handler one calls to invoke this method. */ 7812 upb_byteshandler input_handler_; 7813 7814 /* The destination handlers this method is bound to. We own a ref. */ 7815 const upb_handlers *dest_handlers_; 7816 7817 /* Dispatch table -- used by both bytecode decoder and JIT when encountering a 7818 * field number that wasn't the one we were expecting to see. See 7819 * decoder.int.h for the layout of this table. */ 7820 upb_inttable dispatch; 7821 }; 7822 7823 struct upb_pbdecoder { 7824 upb_env *env; 7825 7826 /* Our input sink. */ 7827 upb_bytessink input_; 7828 7829 /* The decoder method we are parsing with (owned). */ 7830 const upb_pbdecodermethod *method_; 7831 7832 size_t call_len; 7833 const uint32_t *pc, *last; 7834 7835 /* Current input buffer and its stream offset. */ 7836 const char *buf, *ptr, *end, *checkpoint; 7837 7838 /* End of the delimited region, relative to ptr, NULL if not in this buf. */ 7839 const char *delim_end; 7840 7841 /* End of the delimited region, relative to ptr, end if not in this buf. */ 7842 const char *data_end; 7843 7844 /* Overall stream offset of "buf." */ 7845 uint64_t bufstart_ofs; 7846 7847 /* Buffer for residual bytes not parsed from the previous buffer. */ 7848 char residual[UPB_DECODER_MAX_RESIDUAL_BYTES]; 7849 char *residual_end; 7850 7851 /* Bytes of data that should be discarded from the input beore we start 7852 * parsing again. We set this when we internally determine that we can 7853 * safely skip the next N bytes, but this region extends past the current 7854 * user buffer. */ 7855 size_t skip; 7856 7857 /* Stores the user buffer passed to our decode function. */ 7858 const char *buf_param; 7859 size_t size_param; 7860 const upb_bufhandle *handle; 7861 7862 /* Our internal stack. */ 7863 upb_pbdecoder_frame *stack, *top, *limit; 7864 const uint32_t **callstack; 7865 size_t stack_size; 7866 7867 upb_status *status; 7868 7869 #ifdef UPB_USE_JIT_X64 7870 /* Used momentarily by the generated code to store a value while a user 7871 * function is called. */ 7872 uint32_t tmp_len; 7873 7874 const void *saved_rsp; 7875 #endif 7876 }; 7877 7878 /* Decoder entry points; used as handlers. */ 7879 void *upb_pbdecoder_startbc(void *closure, const void *pc, size_t size_hint); 7880 void *upb_pbdecoder_startjit(void *closure, const void *hd, size_t size_hint); 7881 size_t upb_pbdecoder_decode(void *closure, const void *hd, const char *buf, 7882 size_t size, const upb_bufhandle *handle); 7883 bool upb_pbdecoder_end(void *closure, const void *handler_data); 7884 7885 /* Decoder-internal functions that the JIT calls to handle fallback paths. */ 7886 int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf, 7887 size_t size, const upb_bufhandle *handle); 7888 size_t upb_pbdecoder_suspend(upb_pbdecoder *d); 7889 int32_t upb_pbdecoder_skipunknown(upb_pbdecoder *d, int32_t fieldnum, 7890 uint8_t wire_type); 7891 int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d, uint64_t expected); 7892 int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d, uint64_t *u64); 7893 int32_t upb_pbdecoder_decode_f32(upb_pbdecoder *d, uint32_t *u32); 7894 int32_t upb_pbdecoder_decode_f64(upb_pbdecoder *d, uint64_t *u64); 7895 void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg); 7896 7897 /* Error messages that are shared between the bytecode and JIT decoders. */ 7898 extern const char *kPbDecoderStackOverflow; 7899 extern const char *kPbDecoderSubmessageTooLong; 7900 7901 /* Access to decoderplan members needed by the decoder. */ 7902 const char *upb_pbdecoder_getopname(unsigned int op); 7903 7904 /* JIT codegen entry point. */ 7905 void upb_pbdecoder_jit(mgroup *group); 7906 void upb_pbdecoder_freejit(mgroup *group); 7907 UPB_REFCOUNTED_CMETHODS(mgroup, mgroup_upcast) 7908 7909 /* A special label that means "do field dispatch for this message and branch to 7910 * wherever that takes you." */ 7911 #define LABEL_DISPATCH 0 7912 7913 /* A special slot in the dispatch table that stores the epilogue (ENDMSG and/or 7914 * RET) for branching to when we find an appropriate ENDGROUP tag. */ 7915 #define DISPATCH_ENDMSG 0 7916 7917 /* It's important to use this invalid wire type instead of 0 (which is a valid 7918 * wire type). */ 7919 #define NO_WIRE_TYPE 0xff 7920 7921 /* The dispatch table layout is: 7922 * [field number] -> [ 48-bit offset ][ 8-bit wt2 ][ 8-bit wt1 ] 7923 * 7924 * If wt1 matches, jump to the 48-bit offset. If wt2 matches, lookup 7925 * (UPB_MAX_FIELDNUMBER + fieldnum) and jump there. 7926 * 7927 * We need two wire types because of packed/non-packed compatibility. A 7928 * primitive repeated field can use either wire type and be valid. While we 7929 * could key the table on fieldnum+wiretype, the table would be 8x sparser. 7930 * 7931 * Storing two wire types in the primary value allows us to quickly rule out 7932 * the second wire type without needing to do a separate lookup (this case is 7933 * less common than an unknown field). */ 7934 UPB_INLINE uint64_t upb_pbdecoder_packdispatch(uint64_t ofs, uint8_t wt1, 7935 uint8_t wt2) { 7936 return (ofs << 16) | (wt2 << 8) | wt1; 7937 } 7938 7939 UPB_INLINE void upb_pbdecoder_unpackdispatch(uint64_t dispatch, uint64_t *ofs, 7940 uint8_t *wt1, uint8_t *wt2) { 7941 *wt1 = (uint8_t)dispatch; 7942 *wt2 = (uint8_t)(dispatch >> 8); 7943 *ofs = dispatch >> 16; 7944 } 7945 7946 /* All of the functions in decoder.c that return int32_t return values according 7947 * to the following scheme: 7948 * 1. negative values indicate a return code from the following list. 7949 * 2. positive values indicate that error or end of buffer was hit, and 7950 * that the decode function should immediately return the given value 7951 * (the decoder state has already been suspended and is ready to be 7952 * resumed). */ 7953 #define DECODE_OK -1 7954 #define DECODE_MISMATCH -2 /* Used only from checktag_slow(). */ 7955 #define DECODE_ENDGROUP -3 /* Used only from checkunknown(). */ 7956 7957 #define CHECK_RETURN(x) { int32_t ret = x; if (ret >= 0) return ret; } 7958 7959 #endif /* UPB_DECODER_INT_H_ */ 7960 /* 7961 ** A number of routines for varint manipulation (we keep them all around to 7962 ** have multiple approaches available for benchmarking). 7963 */ 7964 7965 #ifndef UPB_VARINT_DECODER_H_ 7966 #define UPB_VARINT_DECODER_H_ 7967 7968 #include <assert.h> 7969 #include <stdint.h> 7970 #include <string.h> 7971 7972 #ifdef __cplusplus 7973 extern "C" { 7974 #endif 7975 7976 /* A list of types as they are encoded on-the-wire. */ 7977 typedef enum { 7978 UPB_WIRE_TYPE_VARINT = 0, 7979 UPB_WIRE_TYPE_64BIT = 1, 7980 UPB_WIRE_TYPE_DELIMITED = 2, 7981 UPB_WIRE_TYPE_START_GROUP = 3, 7982 UPB_WIRE_TYPE_END_GROUP = 4, 7983 UPB_WIRE_TYPE_32BIT = 5 7984 } upb_wiretype_t; 7985 7986 #define UPB_MAX_WIRE_TYPE 5 7987 7988 /* The maximum number of bytes that it takes to encode a 64-bit varint. 7989 * Note that with a better encoding this could be 9 (TODO: write up a 7990 * wiki document about this). */ 7991 #define UPB_PB_VARINT_MAX_LEN 10 7992 7993 /* Array of the "native" (ie. non-packed-repeated) wire type for the given a 7994 * descriptor type (upb_descriptortype_t). */ 7995 extern const uint8_t upb_pb_native_wire_types[]; 7996 7997 /* Zig-zag encoding/decoding **************************************************/ 7998 7999 UPB_INLINE int32_t upb_zzdec_32(uint32_t n) { 8000 return (n >> 1) ^ -(int32_t)(n & 1); 8001 } 8002 UPB_INLINE int64_t upb_zzdec_64(uint64_t n) { 8003 return (n >> 1) ^ -(int64_t)(n & 1); 8004 } 8005 UPB_INLINE uint32_t upb_zzenc_32(int32_t n) { return (n << 1) ^ (n >> 31); } 8006 UPB_INLINE uint64_t upb_zzenc_64(int64_t n) { return (n << 1) ^ (n >> 63); } 8007 8008 /* Decoding *******************************************************************/ 8009 8010 /* All decoding functions return this struct by value. */ 8011 typedef struct { 8012 const char *p; /* NULL if the varint was unterminated. */ 8013 uint64_t val; 8014 } upb_decoderet; 8015 8016 UPB_INLINE upb_decoderet upb_decoderet_make(const char *p, uint64_t val) { 8017 upb_decoderet ret; 8018 ret.p = p; 8019 ret.val = val; 8020 return ret; 8021 } 8022 8023 /* Four functions for decoding a varint of at most eight bytes. They are all 8024 * functionally identical, but are implemented in different ways and likely have 8025 * different performance profiles. We keep them around for performance testing. 8026 * 8027 * Note that these functions may not read byte-by-byte, so they must not be used 8028 * unless there are at least eight bytes left in the buffer! */ 8029 upb_decoderet upb_vdecode_max8_branch32(upb_decoderet r); 8030 upb_decoderet upb_vdecode_max8_branch64(upb_decoderet r); 8031 upb_decoderet upb_vdecode_max8_wright(upb_decoderet r); 8032 upb_decoderet upb_vdecode_max8_massimino(upb_decoderet r); 8033 8034 /* Template for a function that checks the first two bytes with branching 8035 * and dispatches 2-10 bytes with a separate function. Note that this may read 8036 * up to 10 bytes, so it must not be used unless there are at least ten bytes 8037 * left in the buffer! */ 8038 #define UPB_VARINT_DECODER_CHECK2(name, decode_max8_function) \ 8039 UPB_INLINE upb_decoderet upb_vdecode_check2_ ## name(const char *_p) { \ 8040 uint8_t *p = (uint8_t*)_p; \ 8041 upb_decoderet r; \ 8042 if ((*p & 0x80) == 0) { \ 8043 /* Common case: one-byte varint. */ \ 8044 return upb_decoderet_make(_p + 1, *p & 0x7fU); \ 8045 } \ 8046 r = upb_decoderet_make(_p + 2, (*p & 0x7fU) | ((*(p + 1) & 0x7fU) << 7)); \ 8047 if ((*(p + 1) & 0x80) == 0) { \ 8048 /* Two-byte varint. */ \ 8049 return r; \ 8050 } \ 8051 /* Longer varint, fallback to out-of-line function. */ \ 8052 return decode_max8_function(r); \ 8053 } 8054 8055 UPB_VARINT_DECODER_CHECK2(branch32, upb_vdecode_max8_branch32) 8056 UPB_VARINT_DECODER_CHECK2(branch64, upb_vdecode_max8_branch64) 8057 UPB_VARINT_DECODER_CHECK2(wright, upb_vdecode_max8_wright) 8058 UPB_VARINT_DECODER_CHECK2(massimino, upb_vdecode_max8_massimino) 8059 #undef UPB_VARINT_DECODER_CHECK2 8060 8061 /* Our canonical functions for decoding varints, based on the currently 8062 * favored best-performing implementations. */ 8063 UPB_INLINE upb_decoderet upb_vdecode_fast(const char *p) { 8064 if (sizeof(long) == 8) 8065 return upb_vdecode_check2_branch64(p); 8066 else 8067 return upb_vdecode_check2_branch32(p); 8068 } 8069 8070 UPB_INLINE upb_decoderet upb_vdecode_max8_fast(upb_decoderet r) { 8071 return upb_vdecode_max8_massimino(r); 8072 } 8073 8074 8075 /* Encoding *******************************************************************/ 8076 8077 UPB_INLINE int upb_value_size(uint64_t val) { 8078 #ifdef __GNUC__ 8079 int high_bit = 63 - __builtin_clzll(val); /* 0-based, undef if val == 0. */ 8080 #else 8081 int high_bit = 0; 8082 uint64_t tmp = val; 8083 while(tmp >>= 1) high_bit++; 8084 #endif 8085 return val == 0 ? 1 : high_bit / 8 + 1; 8086 } 8087 8088 /* Encodes a 64-bit varint into buf (which must be >=UPB_PB_VARINT_MAX_LEN 8089 * bytes long), returning how many bytes were used. 8090 * 8091 * TODO: benchmark and optimize if necessary. */ 8092 UPB_INLINE size_t upb_vencode64(uint64_t val, char *buf) { 8093 size_t i; 8094 if (val == 0) { buf[0] = 0; return 1; } 8095 i = 0; 8096 while (val) { 8097 uint8_t byte = val & 0x7fU; 8098 val >>= 7; 8099 if (val) byte |= 0x80U; 8100 buf[i++] = byte; 8101 } 8102 return i; 8103 } 8104 8105 UPB_INLINE size_t upb_varint_size(uint64_t val) { 8106 char buf[UPB_PB_VARINT_MAX_LEN]; 8107 return upb_vencode64(val, buf); 8108 } 8109 8110 /* Encodes a 32-bit varint, *not* sign-extended. */ 8111 UPB_INLINE uint64_t upb_vencode32(uint32_t val) { 8112 char buf[UPB_PB_VARINT_MAX_LEN]; 8113 size_t bytes = upb_vencode64(val, buf); 8114 uint64_t ret = 0; 8115 assert(bytes <= 5); 8116 memcpy(&ret, buf, bytes); 8117 assert(ret <= 0xffffffffffU); 8118 return ret; 8119 } 8120 8121 #ifdef __cplusplus 8122 } /* extern "C" */ 8123 #endif 8124 8125 #endif /* UPB_VARINT_DECODER_H_ */ 8126 /* 8127 ** upb::pb::Encoder (upb_pb_encoder) 8128 ** 8129 ** Implements a set of upb_handlers that write protobuf data to the binary wire 8130 ** format. 8131 ** 8132 ** This encoder implementation does not have any access to any out-of-band or 8133 ** precomputed lengths for submessages, so it must buffer submessages internally 8134 ** before it can emit the first byte. 8135 */ 8136 8137 #ifndef UPB_ENCODER_H_ 8138 #define UPB_ENCODER_H_ 8139 8140 8141 #ifdef __cplusplus 8142 namespace upb { 8143 namespace pb { 8144 class Encoder; 8145 } /* namespace pb */ 8146 } /* namespace upb */ 8147 #endif 8148 8149 UPB_DECLARE_TYPE(upb::pb::Encoder, upb_pb_encoder) 8150 8151 #define UPB_PBENCODER_MAX_NESTING 100 8152 8153 /* upb::pb::Encoder ***********************************************************/ 8154 8155 /* Preallocation hint: decoder won't allocate more bytes than this when first 8156 * constructed. This hint may be an overestimate for some build configurations. 8157 * But if the decoder library is upgraded without recompiling the application, 8158 * it may be an underestimate. */ 8159 #define UPB_PB_ENCODER_SIZE 768 8160 8161 #ifdef __cplusplus 8162 8163 class upb::pb::Encoder { 8164 public: 8165 /* Creates a new encoder in the given environment. The Handlers must have 8166 * come from NewHandlers() below. */ 8167 static Encoder* Create(Environment* env, const Handlers* handlers, 8168 BytesSink* output); 8169 8170 /* The input to the encoder. */ 8171 Sink* input(); 8172 8173 /* Creates a new set of handlers for this MessageDef. */ 8174 static reffed_ptr<const Handlers> NewHandlers(const MessageDef* msg); 8175 8176 static const size_t kSize = UPB_PB_ENCODER_SIZE; 8177 8178 private: 8179 UPB_DISALLOW_POD_OPS(Encoder, upb::pb::Encoder) 8180 }; 8181 8182 #endif 8183 8184 UPB_BEGIN_EXTERN_C 8185 8186 const upb_handlers *upb_pb_encoder_newhandlers(const upb_msgdef *m, 8187 const void *owner); 8188 upb_sink *upb_pb_encoder_input(upb_pb_encoder *p); 8189 upb_pb_encoder* upb_pb_encoder_create(upb_env* e, const upb_handlers* h, 8190 upb_bytessink* output); 8191 8192 UPB_END_EXTERN_C 8193 8194 #ifdef __cplusplus 8195 8196 namespace upb { 8197 namespace pb { 8198 inline Encoder* Encoder::Create(Environment* env, const Handlers* handlers, 8199 BytesSink* output) { 8200 return upb_pb_encoder_create(env, handlers, output); 8201 } 8202 inline Sink* Encoder::input() { 8203 return upb_pb_encoder_input(this); 8204 } 8205 inline reffed_ptr<const Handlers> Encoder::NewHandlers( 8206 const upb::MessageDef *md) { 8207 const Handlers* h = upb_pb_encoder_newhandlers(md, &h); 8208 return reffed_ptr<const Handlers>(h, &h); 8209 } 8210 } /* namespace pb */ 8211 } /* namespace upb */ 8212 8213 #endif 8214 8215 #endif /* UPB_ENCODER_H_ */ 8216 /* 8217 ** upb's core components like upb_decoder and upb_msg are carefully designed to 8218 ** avoid depending on each other for maximum orthogonality. In other words, 8219 ** you can use a upb_decoder to decode into *any* kind of structure; upb_msg is 8220 ** just one such structure. A upb_msg can be serialized/deserialized into any 8221 ** format, protobuf binary format is just one such format. 8222 ** 8223 ** However, for convenience we provide functions here for doing common 8224 ** operations like deserializing protobuf binary format into a upb_msg. The 8225 ** compromise is that this file drags in almost all of upb as a dependency, 8226 ** which could be undesirable if you're trying to use a trimmed-down build of 8227 ** upb. 8228 ** 8229 ** While these routines are convenient, they do not reuse any encoding/decoding 8230 ** state. For example, if a decoder is JIT-based, it will be re-JITted every 8231 ** time these functions are called. For this reason, if you are parsing lots 8232 ** of data and efficiency is an issue, these may not be the best functions to 8233 ** use (though they are useful for prototyping, before optimizing). 8234 */ 8235 8236 #ifndef UPB_GLUE_H 8237 #define UPB_GLUE_H 8238 8239 #include <stdbool.h> 8240 8241 #ifdef __cplusplus 8242 #include <vector> 8243 8244 extern "C" { 8245 #endif 8246 8247 /* Loads a binary descriptor and returns a NULL-terminated array of unfrozen 8248 * filedefs. The caller owns the returned array, which must be freed with 8249 * upb_gfree(). */ 8250 upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner, 8251 upb_status *status); 8252 8253 #ifdef __cplusplus 8254 } /* extern "C" */ 8255 8256 namespace upb { 8257 8258 inline bool LoadDescriptor(const char* buf, size_t n, Status* status, 8259 std::vector<reffed_ptr<FileDef> >* files) { 8260 FileDef** parsed_files = upb_loaddescriptor(buf, n, &parsed_files, status); 8261 8262 if (parsed_files) { 8263 FileDef** p = parsed_files; 8264 while (*p) { 8265 files->push_back(reffed_ptr<FileDef>(*p, &parsed_files)); 8266 ++p; 8267 } 8268 free(parsed_files); 8269 return true; 8270 } else { 8271 return false; 8272 } 8273 } 8274 8275 /* Templated so it can accept both string and std::string. */ 8276 template <typename T> 8277 bool LoadDescriptor(const T& desc, Status* status, 8278 std::vector<reffed_ptr<FileDef> >* files) { 8279 return LoadDescriptor(desc.c_str(), desc.size(), status, files); 8280 } 8281 8282 } /* namespace upb */ 8283 8284 #endif 8285 8286 #endif /* UPB_GLUE_H */ 8287 /* 8288 ** upb::pb::TextPrinter (upb_textprinter) 8289 ** 8290 ** Handlers for writing to protobuf text format. 8291 */ 8292 8293 #ifndef UPB_TEXT_H_ 8294 #define UPB_TEXT_H_ 8295 8296 8297 #ifdef __cplusplus 8298 namespace upb { 8299 namespace pb { 8300 class TextPrinter; 8301 } /* namespace pb */ 8302 } /* namespace upb */ 8303 #endif 8304 8305 UPB_DECLARE_TYPE(upb::pb::TextPrinter, upb_textprinter) 8306 8307 #ifdef __cplusplus 8308 8309 class upb::pb::TextPrinter { 8310 public: 8311 /* The given handlers must have come from NewHandlers(). It must outlive the 8312 * TextPrinter. */ 8313 static TextPrinter *Create(Environment *env, const upb::Handlers *handlers, 8314 BytesSink *output); 8315 8316 void SetSingleLineMode(bool single_line); 8317 8318 Sink* input(); 8319 8320 /* If handler caching becomes a requirement we can add a code cache as in 8321 * decoder.h */ 8322 static reffed_ptr<const Handlers> NewHandlers(const MessageDef* md); 8323 }; 8324 8325 #endif 8326 8327 UPB_BEGIN_EXTERN_C 8328 8329 /* C API. */ 8330 upb_textprinter *upb_textprinter_create(upb_env *env, const upb_handlers *h, 8331 upb_bytessink *output); 8332 void upb_textprinter_setsingleline(upb_textprinter *p, bool single_line); 8333 upb_sink *upb_textprinter_input(upb_textprinter *p); 8334 8335 const upb_handlers *upb_textprinter_newhandlers(const upb_msgdef *m, 8336 const void *owner); 8337 8338 UPB_END_EXTERN_C 8339 8340 #ifdef __cplusplus 8341 8342 namespace upb { 8343 namespace pb { 8344 inline TextPrinter *TextPrinter::Create(Environment *env, 8345 const upb::Handlers *handlers, 8346 BytesSink *output) { 8347 return upb_textprinter_create(env, handlers, output); 8348 } 8349 inline void TextPrinter::SetSingleLineMode(bool single_line) { 8350 upb_textprinter_setsingleline(this, single_line); 8351 } 8352 inline Sink* TextPrinter::input() { 8353 return upb_textprinter_input(this); 8354 } 8355 inline reffed_ptr<const Handlers> TextPrinter::NewHandlers( 8356 const MessageDef *md) { 8357 const Handlers* h = upb_textprinter_newhandlers(md, &h); 8358 return reffed_ptr<const Handlers>(h, &h); 8359 } 8360 } /* namespace pb */ 8361 } /* namespace upb */ 8362 8363 #endif 8364 8365 #endif /* UPB_TEXT_H_ */ 8366 /* 8367 ** upb::json::Parser (upb_json_parser) 8368 ** 8369 ** Parses JSON according to a specific schema. 8370 ** Support for parsing arbitrary JSON (schema-less) will be added later. 8371 */ 8372 8373 #ifndef UPB_JSON_PARSER_H_ 8374 #define UPB_JSON_PARSER_H_ 8375 8376 8377 #ifdef __cplusplus 8378 namespace upb { 8379 namespace json { 8380 class Parser; 8381 class ParserMethod; 8382 } /* namespace json */ 8383 } /* namespace upb */ 8384 #endif 8385 8386 UPB_DECLARE_TYPE(upb::json::Parser, upb_json_parser) 8387 UPB_DECLARE_DERIVED_TYPE(upb::json::ParserMethod, upb::RefCounted, 8388 upb_json_parsermethod, upb_refcounted) 8389 8390 /* upb::json::Parser **********************************************************/ 8391 8392 /* Preallocation hint: parser won't allocate more bytes than this when first 8393 * constructed. This hint may be an overestimate for some build configurations. 8394 * But if the parser library is upgraded without recompiling the application, 8395 * it may be an underestimate. */ 8396 #define UPB_JSON_PARSER_SIZE 4112 8397 8398 #ifdef __cplusplus 8399 8400 /* Parses an incoming BytesStream, pushing the results to the destination 8401 * sink. */ 8402 class upb::json::Parser { 8403 public: 8404 static Parser* Create(Environment* env, const ParserMethod* method, 8405 Sink* output); 8406 8407 BytesSink* input(); 8408 8409 private: 8410 UPB_DISALLOW_POD_OPS(Parser, upb::json::Parser) 8411 }; 8412 8413 class upb::json::ParserMethod { 8414 public: 8415 /* Include base methods from upb::ReferenceCounted. */ 8416 UPB_REFCOUNTED_CPPMETHODS 8417 8418 /* Returns handlers for parsing according to the specified schema. */ 8419 static reffed_ptr<const ParserMethod> New(const upb::MessageDef* md); 8420 8421 /* The destination handlers that are statically bound to this method. 8422 * This method is only capable of outputting to a sink that uses these 8423 * handlers. */ 8424 const Handlers* dest_handlers() const; 8425 8426 /* The input handlers for this decoder method. */ 8427 const BytesHandler* input_handler() const; 8428 8429 private: 8430 UPB_DISALLOW_POD_OPS(ParserMethod, upb::json::ParserMethod) 8431 }; 8432 8433 #endif 8434 8435 UPB_BEGIN_EXTERN_C 8436 8437 upb_json_parser* upb_json_parser_create(upb_env* e, 8438 const upb_json_parsermethod* m, 8439 upb_sink* output); 8440 upb_bytessink *upb_json_parser_input(upb_json_parser *p); 8441 8442 upb_json_parsermethod* upb_json_parsermethod_new(const upb_msgdef* md, 8443 const void* owner); 8444 const upb_handlers *upb_json_parsermethod_desthandlers( 8445 const upb_json_parsermethod *m); 8446 const upb_byteshandler *upb_json_parsermethod_inputhandler( 8447 const upb_json_parsermethod *m); 8448 8449 /* Include refcounted methods like upb_json_parsermethod_ref(). */ 8450 UPB_REFCOUNTED_CMETHODS(upb_json_parsermethod, upb_json_parsermethod_upcast) 8451 8452 UPB_END_EXTERN_C 8453 8454 #ifdef __cplusplus 8455 8456 namespace upb { 8457 namespace json { 8458 inline Parser* Parser::Create(Environment* env, const ParserMethod* method, 8459 Sink* output) { 8460 return upb_json_parser_create(env, method, output); 8461 } 8462 inline BytesSink* Parser::input() { 8463 return upb_json_parser_input(this); 8464 } 8465 8466 inline const Handlers* ParserMethod::dest_handlers() const { 8467 return upb_json_parsermethod_desthandlers(this); 8468 } 8469 inline const BytesHandler* ParserMethod::input_handler() const { 8470 return upb_json_parsermethod_inputhandler(this); 8471 } 8472 /* static */ 8473 inline reffed_ptr<const ParserMethod> ParserMethod::New( 8474 const MessageDef* md) { 8475 const upb_json_parsermethod *m = upb_json_parsermethod_new(md, &m); 8476 return reffed_ptr<const ParserMethod>(m, &m); 8477 } 8478 8479 } /* namespace json */ 8480 } /* namespace upb */ 8481 8482 #endif 8483 8484 8485 #endif /* UPB_JSON_PARSER_H_ */ 8486 /* 8487 ** upb::json::Printer 8488 ** 8489 ** Handlers that emit JSON according to a specific protobuf schema. 8490 */ 8491 8492 #ifndef UPB_JSON_TYPED_PRINTER_H_ 8493 #define UPB_JSON_TYPED_PRINTER_H_ 8494 8495 8496 #ifdef __cplusplus 8497 namespace upb { 8498 namespace json { 8499 class Printer; 8500 } /* namespace json */ 8501 } /* namespace upb */ 8502 #endif 8503 8504 UPB_DECLARE_TYPE(upb::json::Printer, upb_json_printer) 8505 8506 8507 /* upb::json::Printer *********************************************************/ 8508 8509 #define UPB_JSON_PRINTER_SIZE 176 8510 8511 #ifdef __cplusplus 8512 8513 /* Prints an incoming stream of data to a BytesSink in JSON format. */ 8514 class upb::json::Printer { 8515 public: 8516 static Printer* Create(Environment* env, const upb::Handlers* handlers, 8517 BytesSink* output); 8518 8519 /* The input to the printer. */ 8520 Sink* input(); 8521 8522 /* Returns handlers for printing according to the specified schema. 8523 * If preserve_proto_fieldnames is true, the output JSON will use the 8524 * original .proto field names (ie. {"my_field":3}) instead of using 8525 * camelCased names, which is the default: (eg. {"myField":3}). */ 8526 static reffed_ptr<const Handlers> NewHandlers(const upb::MessageDef* md, 8527 bool preserve_proto_fieldnames); 8528 8529 static const size_t kSize = UPB_JSON_PRINTER_SIZE; 8530 8531 private: 8532 UPB_DISALLOW_POD_OPS(Printer, upb::json::Printer) 8533 }; 8534 8535 #endif 8536 8537 UPB_BEGIN_EXTERN_C 8538 8539 /* Native C API. */ 8540 upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h, 8541 upb_bytessink *output); 8542 upb_sink *upb_json_printer_input(upb_json_printer *p); 8543 const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md, 8544 bool preserve_fieldnames, 8545 const void *owner); 8546 8547 UPB_END_EXTERN_C 8548 8549 #ifdef __cplusplus 8550 8551 namespace upb { 8552 namespace json { 8553 inline Printer* Printer::Create(Environment* env, const upb::Handlers* handlers, 8554 BytesSink* output) { 8555 return upb_json_printer_create(env, handlers, output); 8556 } 8557 inline Sink* Printer::input() { return upb_json_printer_input(this); } 8558 inline reffed_ptr<const Handlers> Printer::NewHandlers( 8559 const upb::MessageDef *md, bool preserve_proto_fieldnames) { 8560 const Handlers* h = upb_json_printer_newhandlers( 8561 md, preserve_proto_fieldnames, &h); 8562 return reffed_ptr<const Handlers>(h, &h); 8563 } 8564 } /* namespace json */ 8565 } /* namespace upb */ 8566 8567 #endif 8568 8569 #endif /* UPB_JSON_TYPED_PRINTER_H_ */ 8570