Removed old-style C++ handlers that relied on UB in favor of more normal ones.

pull/13171/head
Joshua Haberman 6 years ago
parent 0553eff64a
commit d2f9bec5c6
  1. 2
      CMakeLists.txt
  2. 33
      tests/pb/test_encoder.cc
  3. 2
      tests/test_util.h
  4. 6
      upb/bindings/stdc++/string.h
  5. 1149
      upb/def.h
  6. 284
      upb/handlers-inl.h
  7. 171
      upb/handlers.c
  8. 816
      upb/handlers.h
  9. 44
      upb/json/printer.c
  10. 8
      upb/pb/compile_decoder.c
  11. 221
      upb/pb/decoder.h
  12. 10
      upb/pb/encoder.c
  13. 70
      upb/pb/encoder.h
  14. 6
      upb/pb/textprinter.c
  15. 6
      upb/sink.c
  16. 603
      upb/sink.h
  17. 69
      upb/upb.h

@ -70,7 +70,6 @@ add_library(upb
upb/msgfactory.c
upb/port_def.inc
upb/port_undef.inc
upb/refcounted.c
upb/sink.c
upb/structs.int.h
upb/table.c
@ -84,7 +83,6 @@ add_library(upb
upb/handlers.h
upb/msg.h
upb/msgfactory.h
upb/refcounted.h
upb/sink.h
upb/upb.h)
add_library(upb_pb

@ -18,12 +18,9 @@ std::string read_string(const char *filename) {
void test_pb_roundtrip() {
std::string input = read_string("google/protobuf/descriptor.pb");
upb::SymbolTable* symtab = upb::SymbolTable::New();
upb::HandlerCache* encoder_cache = upb::pb::Encoder::NewCache();
upb::pb::CodeCache* decoder_cache = upb::pb::CodeCache::New(encoder_cache);
ASSERT(symtab);
ASSERT(encoder_cache);
ASSERT(decoder_cache);
upb::SymbolTable symtab;
upb::HandlerCache encoder_cache(upb::pb::EncoderPtr::NewCache());
upb::pb::CodeCache decoder_cache(&encoder_cache);
upb::Arena arena;
google_protobuf_FileDescriptorSet *set =
google_protobuf_FileDescriptorSet_parsenew(
@ -34,32 +31,28 @@ void test_pb_roundtrip() {
google_protobuf_FileDescriptorSet_file(set, &n);
ASSERT(n == 1);
upb::Status status;
bool ok = symtab->AddFile(files[0], &status);
bool ok = symtab.AddFile(files[0], &status);
if (!ok) {
fprintf(stderr, "Error building def: %s\n", upb_status_errmsg(&status));
ASSERT(false);
}
const upb::MessageDef *md =
symtab->LookupMessage("google.protobuf.FileDescriptorSet");
upb::MessageDefPtr md =
symtab.LookupMessage("google.protobuf.FileDescriptorSet");
ASSERT(md);
const upb::Handlers* encoder_handlers = encoder_cache->Get(md);
const upb::Handlers *encoder_handlers = encoder_cache.Get(md);
ASSERT(encoder_handlers);
const upb::pb::DecoderMethod* method = decoder_cache->Get(md);
ASSERT(method);
const upb::pb::DecoderMethodPtr method = decoder_cache.Get(md);
upb::InlinedEnvironment<512> env;
std::string output;
upb::StringSink string_sink(&output);
upb::pb::Encoder* encoder =
upb::pb::Encoder::Create(&env, encoder_handlers, string_sink.input());
upb::pb::Decoder* decoder =
upb::pb::Decoder::Create(&env, method, encoder->input());
ok = upb::BufferSource::PutBuffer(input, decoder->input());
upb::pb::EncoderPtr encoder =
upb::pb::EncoderPtr::Create(&env, encoder_handlers, string_sink.input());
upb::pb::DecoderPtr decoder =
upb::pb::DecoderPtr::Create(&env, method, encoder.input());
ok = upb::PutBuffer(input, decoder.input());
ASSERT(ok);
ASSERT(input == output);
upb::pb::CodeCache::Free(decoder_cache);
upb::HandlerCache::Free(encoder_cache);
upb::SymbolTable::Free(symtab);
}
extern "C" {

@ -12,7 +12,7 @@
#ifdef __cplusplus
upb::BufferHandle global_handle;
upb_bufhandle global_handle;
/* A convenience class for parser tests. Provides some useful features:
*

@ -9,7 +9,7 @@ namespace upb {
template <class T>
class FillStringHandler {
public:
static void SetHandler(BytesHandler* handler) {
static void SetHandler(upb_byteshandler* handler) {
upb_byteshandler_setstartstr(handler, &FillStringHandler::StartString,
NULL);
upb_byteshandler_setstring(handler, &FillStringHandler::StringBuf, NULL);
@ -28,7 +28,7 @@ class FillStringHandler {
}
static size_t StringBuf(void* c, const void* hd, const char* buf, size_t n,
const BufferHandle* h) {
const upb_bufhandle* h) {
UPB_UNUSED(hd);
UPB_UNUSED(h);
@ -55,7 +55,7 @@ class StringSink {
BytesSink* input() { return &input_; }
private:
BytesHandler handler_;
upb_byteshandler handler_;
BytesSink input_;
};

File diff suppressed because it is too large Load Diff

@ -8,39 +8,6 @@
#include <limits.h>
/* C inline methods. */
/* upb_bufhandle */
UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h) {
h->obj_ = NULL;
h->objtype_ = NULL;
h->buf_ = NULL;
h->objofs_ = 0;
}
UPB_INLINE void upb_bufhandle_uninit(upb_bufhandle *h) {
UPB_UNUSED(h);
}
UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj,
const void *type) {
h->obj_ = obj;
h->objtype_ = type;
}
UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf,
size_t ofs) {
h->buf_ = buf;
h->objofs_ = ofs;
}
UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h) {
return h->obj_;
}
UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h) {
return h->objtype_;
}
UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h) {
return h->buf_;
}
#ifdef __cplusplus
/* Type detection and typedefs for integer types.
@ -604,9 +571,9 @@ void *ReturnClosureOrBreak3(P1 p1, P2 p2, P3 p3) {
/* For the string callback, which takes five params, returns the size param. */
template <class P1, class P2,
void F(P1, P2, const char *, size_t, const BufferHandle *)>
void F(P1, P2, const char *, size_t, const upb_bufhandle *)>
size_t ReturnStringLen(P1 p1, P2 p2, const char *p3, size_t p4,
const BufferHandle *p5) {
const upb_bufhandle *p5) {
F(p1, p2, p3, p4, p5);
return p4;
}
@ -614,9 +581,9 @@ size_t ReturnStringLen(P1 p1, P2 p2, const char *p3, size_t p4,
/* For the string callback, which takes five params, returns the size param or
* zero. */
template <class P1, class P2,
bool F(P1, P2, const char *, size_t, const BufferHandle *)>
bool F(P1, P2, const char *, size_t, const upb_bufhandle *)>
size_t ReturnNOr0(P1 p1, P2 p2, const char *p3, size_t p4,
const BufferHandle *p5) {
const upb_bufhandle *p5) {
return F(p1, p2, p3, p4, p5) ? p4 : 0;
}
@ -675,22 +642,22 @@ struct MaybeWrapReturn<Func3<bool, P1, P2, P3, F, I>, void *> {
/* If our function returns void but we want one returning size_t, wrap it in a
* function that returns the size argument. */
template <class P1, class P2,
void F(P1, P2, const char *, size_t, const BufferHandle *), class I>
void F(P1, P2, const char *, size_t, const upb_bufhandle *), class I>
struct MaybeWrapReturn<
Func5<void, P1, P2, const char *, size_t, const BufferHandle *, F, I>,
Func5<void, P1, P2, const char *, size_t, const upb_bufhandle *, F, I>,
size_t> {
typedef Func5<size_t, P1, P2, const char *, size_t, const BufferHandle *,
typedef Func5<size_t, P1, P2, const char *, size_t, const upb_bufhandle *,
ReturnStringLen<P1, P2, F>, I> Func;
};
/* If our function returns bool but we want one returning size_t, wrap it in a
* function that returns either 0 or the buf size. */
template <class P1, class P2,
bool F(P1, P2, const char *, size_t, const BufferHandle *), class I>
bool F(P1, P2, const char *, size_t, const upb_bufhandle *), class I>
struct MaybeWrapReturn<
Func5<bool, P1, P2, const char *, size_t, const BufferHandle *, F, I>,
Func5<bool, P1, P2, const char *, size_t, const upb_bufhandle *, F, I>,
size_t> {
typedef Func5<size_t, P1, P2, const char *, size_t, const BufferHandle *,
typedef Func5<size_t, P1, P2, const char *, size_t, const upb_bufhandle *,
ReturnNOr0<P1, P2, F>, I> Func;
};
@ -731,7 +698,7 @@ R IgnoreHandlerData5(void *p1, const void *hd, P2 p2, P3 p3, P4 p4) {
template <class R, class P1, R F(P1, const char*, size_t)>
R IgnoreHandlerDataIgnoreHandle(void *p1, const void *hd, const char *p2,
size_t p3, const BufferHandle *handle) {
size_t p3, const upb_bufhandle *handle) {
UPB_UNUSED(hd);
UPB_UNUSED(handle);
return F(static_cast<P1>(p1), p2, p3);
@ -757,7 +724,7 @@ R CastHandlerData5(void *c, const void *hd, P3 p3, P4 p4, P5 p5) {
template <class R, class P1, class P2, R F(P1, P2, const char *, size_t)>
R CastHandlerDataIgnoreHandle(void *c, const void *hd, const char *p3,
size_t p4, const BufferHandle *handle) {
size_t p4, const upb_bufhandle *handle) {
UPB_UNUSED(handle);
return F(static_cast<P1>(c), static_cast<P2>(hd), p3, p4);
}
@ -777,11 +744,11 @@ struct ConvertParams<Func2<R, P1, P2, F, I>,
};
/* For StringBuffer only; this ignores both the handler data and the
* BufferHandle. */
* upb_bufhandle. */
template <class R, class P1, R F(P1, const char *, size_t), class I, class T>
struct ConvertParams<Func3<R, P1, const char *, size_t, F, I>, T> {
typedef Func5<R, void *, const void *, const char *, size_t,
const BufferHandle *, IgnoreHandlerDataIgnoreHandle<R, P1, F>,
const upb_bufhandle *, IgnoreHandlerDataIgnoreHandle<R, P1, F>,
I> Func;
};
@ -807,13 +774,14 @@ struct ConvertParams<BoundFunc3<R, P1, P2, P3, F, I>,
CastHandlerData3<R, P1, P2, P3_2, P3, F>, I> Func;
};
/* For StringBuffer only; this ignores the BufferHandle. */
/* For StringBuffer only; this ignores the upb_bufhandle. */
template <class R, class P1, class P2, R F(P1, P2, const char *, size_t),
class I, class T>
struct ConvertParams<BoundFunc4<R, P1, P2, const char *, size_t, F, I>, T> {
typedef Func5<R, void *, const void *, const char *, size_t,
const BufferHandle *, CastHandlerDataIgnoreHandle<R, P1, P2, F>,
I> Func;
const upb_bufhandle *,
CastHandlerDataIgnoreHandle<R, P1, P2, F>, I>
Func;
};
template <class R, class P1, class P2, class P3, class P4, class P5,
@ -826,18 +794,17 @@ struct ConvertParams<BoundFunc5<R, P1, P2, P3, P4, P5, F, I>, T> {
/* utype/ltype are upper/lower-case, ctype is canonical C type, vtype is
* variant C type. */
#define TYPE_METHODS(utype, ltype, ctype, vtype) \
template <> struct CanonicalType<vtype> { \
template <> \
struct CanonicalType<vtype> { \
typedef ctype Type; \
}; \
template <> \
inline bool Handlers::SetValueHandler<vtype>( \
const FieldDef *f, \
const Handlers::utype ## Handler& handler) { \
UPB_ASSERT(!handler.registered_); \
handler.AddCleanup(this); \
handler.registered_ = true; \
return upb_handlers_set##ltype(this, f, handler.handler_, &handler.attr_); \
} \
inline bool HandlersPtr::SetValueHandler<vtype>( \
FieldDefPtr f, const HandlersPtr::utype##Handler &handler) { \
handler.AddCleanup(ptr()); \
return upb_handlers_set##ltype(ptr(), f.ptr(), handler.handler(), \
&handler.attr()); \
}
TYPE_METHODS(Double, double, double, double)
TYPE_METHODS(Float, float, float, float)
@ -862,24 +829,6 @@ template <> struct CanonicalType<Status*> {
typedef Status* Type;
};
/* Type methods that are only one-per-canonical-type and not
* one-per-cvariant. */
#define TYPE_METHODS(utype, ctype) \
inline bool Handlers::Set##utype##Handler(const FieldDef *f, \
const utype##Handler &h) { \
return SetValueHandler<ctype>(f, h); \
} \
TYPE_METHODS(Double, double)
TYPE_METHODS(Float, float)
TYPE_METHODS(UInt64, uint64_t)
TYPE_METHODS(UInt32, uint32_t)
TYPE_METHODS(Int64, int64_t)
TYPE_METHODS(Int32, int32_t)
TYPE_METHODS(Bool, bool)
#undef TYPE_METHODS
template <class F> struct ReturnOf;
template <class R, class P1, class P2>
@ -902,10 +851,6 @@ struct ReturnOf<R (*)(P1, P2, P3, P4, P5)> {
typedef R Return;
};
template<class T> const void *UniquePtrForType() {
static const char ch = 0;
return &ch;
}
template <class T>
template <class F>
@ -926,10 +871,10 @@ inline Handler<T>::Handler(F func)
/* If the original function returns void, then we know that we wrapped it to
* always return ok. */
bool always_ok = is_same<typename F::FuncInfo::Return, void>::value;
attr_.SetAlwaysOk(always_ok);
attr_.alwaysok = always_ok;
/* Closure parameter and return type. */
attr_.SetClosureType(UniquePtrForType<typename F::FuncInfo::Closure>());
attr_.closure_type = UniquePtrForType<typename F::FuncInfo::Closure>();
/* We use the closure type (from the first parameter) if the return type is
* void or bool, since these are the two cases we wrap to return the closure's
@ -940,176 +885,19 @@ inline Handler<T>::Handler(F func)
typedef typename FirstUnlessVoidOrBool<typename F::FuncInfo::Return,
typename F::FuncInfo::Closure>::value
EffectiveReturn;
attr_.SetReturnClosureType(UniquePtrForType<EffectiveReturn>());
attr_.return_closure_type = UniquePtrForType<EffectiveReturn>();
}
template <class T>
inline Handler<T>::~Handler() {
UPB_ASSERT(registered_);
}
inline HandlerAttributes::HandlerAttributes() { upb_handlerattr_init(this); }
inline HandlerAttributes::~HandlerAttributes() { upb_handlerattr_uninit(this); }
inline bool HandlerAttributes::SetHandlerData(const void *hd) {
return upb_handlerattr_sethandlerdata(this, hd);
}
inline const void* HandlerAttributes::handler_data() const {
return upb_handlerattr_handlerdata(this);
}
inline bool HandlerAttributes::SetClosureType(const void *type) {
return upb_handlerattr_setclosuretype(this, type);
}
inline const void* HandlerAttributes::closure_type() const {
return upb_handlerattr_closuretype(this);
}
inline bool HandlerAttributes::SetReturnClosureType(const void *type) {
return upb_handlerattr_setreturnclosuretype(this, type);
}
inline const void* HandlerAttributes::return_closure_type() const {
return upb_handlerattr_returnclosuretype(this);
}
inline bool HandlerAttributes::SetAlwaysOk(bool always_ok) {
return upb_handlerattr_setalwaysok(this, always_ok);
}
inline bool HandlerAttributes::always_ok() const {
return upb_handlerattr_alwaysok(this);
}
inline BufferHandle::BufferHandle() { upb_bufhandle_init(this); }
inline BufferHandle::~BufferHandle() { upb_bufhandle_uninit(this); }
inline const char* BufferHandle::buffer() const {
return upb_bufhandle_buf(this);
}
inline size_t BufferHandle::object_offset() const {
return upb_bufhandle_objofs(this);
}
inline void BufferHandle::SetBuffer(const char* buf, size_t ofs) {
upb_bufhandle_setbuf(this, buf, ofs);
}
template <class T>
void BufferHandle::SetAttachedObject(const T* obj) {
upb_bufhandle_setobj(this, obj, UniquePtrForType<T>());
}
template <class T>
const T* BufferHandle::GetAttachedObject() const {
return upb_bufhandle_objtype(this) == UniquePtrForType<T>()
? static_cast<const T *>(upb_bufhandle_obj(this))
: NULL;
}
inline const Status* Handlers::status() {
return upb_handlers_status(this);
}
inline void Handlers::ClearError() {
return upb_handlers_clearerr(this);
}
inline const MessageDef *Handlers::message_def() const {
return upb_handlers_msgdef(this);
}
inline bool Handlers::AddCleanup(void *p, upb_handlerfree *func) {
return upb_handlers_addcleanup(this, p, func);
}
inline bool Handlers::SetStartMessageHandler(
const Handlers::StartMessageHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartmsg(this, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndMessageHandler(
const Handlers::EndMessageHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendmsg(this, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartStringHandler(const FieldDef *f,
const StartStringHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartstr(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndStringHandler(const FieldDef *f,
const EndFieldHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendstr(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStringHandler(const FieldDef *f,
const StringHandler& handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstring(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartSequenceHandler(
const FieldDef *f, const StartFieldHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartseq(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartSubMessageHandler(
const FieldDef *f, const StartFieldHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartsubmsg(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndSubMessageHandler(const FieldDef *f,
const EndFieldHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendsubmsg(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndSequenceHandler(const FieldDef *f,
const EndFieldHandler &handler) {
UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendseq(this, f, handler.handler_, &handler.attr_);
}
inline const Handlers *Handlers::GetSubHandlers(const FieldDef *f) const {
return upb_handlers_getsubhandlers(this, f);
}
inline const Handlers *Handlers::GetSubHandlers(Handlers::Selector sel) const {
return upb_handlers_getsubhandlers_sel(this, sel);
}
inline bool Handlers::GetSelector(const FieldDef *f, Handlers::Type type,
Handlers::Selector *s) {
return upb_handlers_getselector(f, type, s);
}
inline Handlers::Selector Handlers::GetEndSelector(Handlers::Selector start) {
return upb_handlers_getendselector(start);
}
inline Handlers::GenericFunction *Handlers::GetHandler(
Handlers::Selector selector) {
return upb_handlers_gethandler(this, selector);
}
inline const void *Handlers::GetHandlerData(Handlers::Selector selector) {
return upb_handlers_gethandlerdata(this, selector);
}
inline HandlerCache *HandlerCache::New(upb_handlers_callback *callback,
const void *closure) {
return upb_handlercache_new(callback, closure);
}
inline void HandlerCache::Free(HandlerCache* cache) {
return upb_handlercache_free(cache);
}
const Handlers* HandlerCache::Get(const MessageDef* md) {
return upb_handlercache_get(this, md);
}
inline BytesHandler::BytesHandler() {
upb_byteshandler_init(this);
inline void Handler<T>::AddCleanup(upb_handlers* h) const {
UPB_ASSERT(!registered_);
registered_ = true;
if (cleanup_func_) {
bool ok = upb_handlers_addcleanup(h, cleanup_data_, cleanup_func_);
UPB_ASSERT(ok);
}
}
inline BytesHandler::~BytesHandler() {}
} /* namespace upb */
#endif /* __cplusplus */

@ -9,6 +9,15 @@
#include "upb/sink.h"
struct upb_handlers {
upb_handlercache *cache;
const upb_msgdef *msg;
const upb_handlers **sub;
const void *top_closure_type;
upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
};
static void *upb_calloc(upb_arena *arena, size_t size) {
void *mem = upb_malloc(upb_arena_alloc(arena), size);
if (mem) {
@ -50,13 +59,13 @@ static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
static const void **returntype(upb_handlers *h, const upb_fielddef *f,
upb_handlertype_t type) {
return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type_;
return &h->table[handlers_getsel(h, f, type)].attr.return_closure_type;
}
static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
upb_handlertype_t type, upb_func *func,
upb_handlerattr *attr) {
upb_handlerattr set_attr = UPB_HANDLERATTR_INITIALIZER;
const upb_handlerattr *attr) {
upb_handlerattr set_attr = UPB_HANDLERATTR_INIT;
const void *closure_type;
const void **context_closure_type;
@ -68,7 +77,7 @@ static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
/* Check that the given closure type matches the closure type that has been
* established for this context (if any). */
closure_type = upb_handlerattr_closuretype(&set_attr);
closure_type = set_attr.closure_type;
if (type == UPB_HANDLER_STRING) {
context_closure_type = returntype(h, f, UPB_HANDLER_STARTSTR);
@ -91,15 +100,15 @@ static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
/* If this is a STARTSEQ or STARTSTR handler, check that the returned pointer
* matches any pre-existing expectations about what type is expected. */
if (type == UPB_HANDLER_STARTSEQ || type == UPB_HANDLER_STARTSTR) {
const void *return_type = upb_handlerattr_returnclosuretype(&set_attr);
const void *table_return_type =
upb_handlerattr_returnclosuretype(&h->table[sel].attr);
const void *return_type = set_attr.return_closure_type;
const void *table_return_type = h->table[sel].attr.return_closure_type;
if (return_type && table_return_type && return_type != table_return_type) {
UPB_ASSERT(false);
}
if (table_return_type && !return_type)
upb_handlerattr_setreturnclosuretype(&set_attr, table_return_type);
if (table_return_type && !return_type) {
set_attr.return_closure_type = table_return_type;
}
}
h->table[sel].func = (upb_func*)func;
@ -125,18 +134,18 @@ const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
type != UPB_HANDLER_STARTSEQ &&
type != UPB_HANDLER_ENDSEQ &&
h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSEQ)].func) {
ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
ret = h->table[sel].attr.return_closure_type;
}
if (type == UPB_HANDLER_STRING &&
h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSTR)].func) {
ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
ret = h->table[sel].attr.return_closure_type;
}
/* The effective type of the submessage; not used yet.
* if (type == SUBMESSAGE &&
* h->table[sel = handlers_getsel(h, f, UPB_HANDLER_STARTSUBMSG)].func) {
* ret = upb_handlerattr_returnclosuretype(&h->table[sel].attr);
* ret = h->table[sel].attr.return_closure_type;
* } */
return ret;
@ -156,7 +165,7 @@ bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
if (h->table[sel].func) return true;
closure_type = effective_closure_type(h, f, type);
attr = &h->table[sel].attr;
return_closure_type = upb_handlerattr_returnclosuretype(attr);
return_closure_type = attr->return_closure_type;
if (closure_type && return_closure_type &&
closure_type != return_closure_type) {
UPB_ASSERT(false);
@ -164,12 +173,14 @@ bool checkstart(upb_handlers *h, const upb_fielddef *f, upb_handlertype_t type,
return true;
}
static upb_handlers *upb_handlers_new(const upb_msgdef *md, upb_handlercache *cache) {
static upb_handlers *upb_handlers_new(const upb_msgdef *md,
upb_handlercache *cache,
upb_arena *arena) {
int extra;
upb_handlers *h;
extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
h = upb_calloc(&cache->arena, sizeof(*h) + extra);
h = upb_calloc(arena, sizeof(*h) + extra);
if (!h) return NULL;
h->cache = cache;
@ -177,7 +188,7 @@ static upb_handlers *upb_handlers_new(const upb_msgdef *md, upb_handlercache *ca
if (upb_msgdef_submsgfieldcount(md) > 0) {
size_t bytes = upb_msgdef_submsgfieldcount(md) * sizeof(*h->sub);
h->sub = upb_calloc(&cache->arena, bytes);
h->sub = upb_calloc(arena, bytes);
if (!h->sub) return NULL;
} else {
h->sub = 0;
@ -187,14 +198,14 @@ static upb_handlers *upb_handlers_new(const upb_msgdef *md, upb_handlercache *ca
return h;
}
/* Public interface ***********************************************************/
#define SETTER(name, handlerctype, handlertype) \
bool upb_handlers_set ## name(upb_handlers *h, const upb_fielddef *f, \
handlerctype func, upb_handlerattr *attr) { \
bool upb_handlers_set##name(upb_handlers *h, const upb_fielddef *f, \
handlerctype func, \
const upb_handlerattr *attr) { \
int32_t sel = trygetsel(h, f, handlertype); \
return doset(h, sel, f, handlertype, (upb_func*)func, attr); \
return doset(h, sel, f, handlertype, (upb_func *)func, attr); \
}
SETTER(int32, upb_int32_handlerfunc*, UPB_HANDLER_INT32)
@ -215,19 +226,19 @@ SETTER(endseq, upb_endfield_handlerfunc*, UPB_HANDLER_ENDSEQ)
#undef SETTER
bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
upb_handlerattr *attr) {
const upb_handlerattr *attr) {
return doset(h, UPB_UNKNOWN_SELECTOR, NULL, UPB_HANDLER_INT32,
(upb_func *)func, attr);
}
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
upb_handlerattr *attr) {
const upb_handlerattr *attr) {
return doset(h, UPB_STARTMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
(upb_func *)func, attr);
}
bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
upb_handlerattr *attr) {
const upb_handlerattr *attr) {
return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
(upb_func *)func, attr);
}
@ -250,9 +261,18 @@ const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
return SUBH_F(h, f);
}
upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
const void **handler_data) {
upb_func *ret = (upb_func *)h->table[s].func;
if (ret && handler_data) {
*handler_data = h->table[s].attr.handler_data;
}
return ret;
}
bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t sel,
upb_handlerattr *attr) {
if (!upb_handlers_gethandler(h, sel))
if (!upb_handlers_gethandler(h, sel, NULL))
return false;
*attr = h->table[sel].attr;
return true;
@ -266,16 +286,6 @@ const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h) { return h->msg; }
bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
bool ok;
if (upb_inttable_lookupptr(&h->cache->cleanup_, p, NULL)) {
return false;
}
ok = upb_inttable_insertptr(&h->cache->cleanup_, p, upb_value_fptr(func));
UPB_ASSERT(ok);
return true;
}
upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
switch (upb_fielddef_type(f)) {
case UPB_TYPE_INT32:
@ -375,6 +385,14 @@ uint32_t upb_handlers_selectorcount(const upb_fielddef *f) {
/* upb_handlercache ***********************************************************/
struct upb_handlercache {
upb_arena arena;
upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
upb_inttable cleanup_;
upb_handlers_callback *callback;
const void *closure;
};
const upb_handlers *upb_handlercache_get(upb_handlercache *c,
const upb_msgdef *md) {
upb_msg_field_iter i;
@ -385,7 +403,7 @@ const upb_handlers *upb_handlercache_get(upb_handlercache *c,
return upb_value_getptr(v);
}
h = upb_handlers_new(md, c);
h = upb_handlers_new(md, c, &c->arena);
v = upb_value_ptr(h);
if (!h) return NULL;
@ -452,90 +470,39 @@ void upb_handlercache_free(upb_handlercache *cache) {
upb_gfree(cache);
}
/* upb_handlerattr ************************************************************/
void upb_handlerattr_init(upb_handlerattr *attr) {
upb_handlerattr from = UPB_HANDLERATTR_INITIALIZER;
memcpy(attr, &from, sizeof(*attr));
}
void upb_handlerattr_uninit(upb_handlerattr *attr) {
UPB_UNUSED(attr);
}
bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd) {
attr->handler_data_ = hd;
return true;
}
bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type) {
attr->closure_type_ = type;
return true;
}
const void *upb_handlerattr_closuretype(const upb_handlerattr *attr) {
return attr->closure_type_;
}
bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
const void *type) {
attr->return_closure_type_ = type;
return true;
}
const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr) {
return attr->return_closure_type_;
}
bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok) {
attr->alwaysok_ = alwaysok;
bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
bool ok;
if (upb_inttable_lookupptr(&h->cache->cleanup_, p, NULL)) {
return false;
}
ok = upb_inttable_insertptr(&h->cache->cleanup_, p, upb_value_fptr(func));
UPB_ASSERT(ok);
return true;
}
bool upb_handlerattr_alwaysok(const upb_handlerattr *attr) {
return attr->alwaysok_;
}
/* upb_bufhandle **************************************************************/
size_t upb_bufhandle_objofs(const upb_bufhandle *h) {
return h->objofs_;
}
/* upb_byteshandler ***********************************************************/
void upb_byteshandler_init(upb_byteshandler* h) {
memset(h, 0, sizeof(*h));
}
/* For when we support handlerfree callbacks. */
void upb_byteshandler_uninit(upb_byteshandler* h) {
UPB_UNUSED(h);
}
bool upb_byteshandler_setstartstr(upb_byteshandler *h,
upb_startstr_handlerfunc *func, void *d) {
h->table[UPB_STARTSTR_SELECTOR].func = (upb_func*)func;
h->table[UPB_STARTSTR_SELECTOR].attr.handler_data_ = d;
h->table[UPB_STARTSTR_SELECTOR].attr.handler_data = d;
return true;
}
bool upb_byteshandler_setstring(upb_byteshandler *h,
upb_string_handlerfunc *func, void *d) {
h->table[UPB_STRING_SELECTOR].func = (upb_func*)func;
h->table[UPB_STRING_SELECTOR].attr.handler_data_ = d;
h->table[UPB_STRING_SELECTOR].attr.handler_data = d;
return true;
}
bool upb_byteshandler_setendstr(upb_byteshandler *h,
upb_endfield_handlerfunc *func, void *d) {
h->table[UPB_ENDSTR_SELECTOR].func = (upb_func*)func;
h->table[UPB_ENDSTR_SELECTOR].attr.handler_data_ = d;
h->table[UPB_ENDSTR_SELECTOR].attr.handler_data = d;
return true;
}
/** Handlers for upb_msg ******************************************************/
typedef struct {
@ -564,7 +531,7 @@ MSG_WRITER(bool, bool)
bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
size_t offset, int32_t hasbit) {
upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr attr = UPB_HANDLERATTR_INIT;
bool ok;
upb_msg_handlerdata *d = upb_gmalloc(sizeof(*d));
@ -572,8 +539,8 @@ bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
d->offset = offset;
d->hasbit = hasbit;
upb_handlerattr_sethandlerdata(&attr, d);
upb_handlerattr_setalwaysok(&attr, true);
attr.handler_data = d;
attr.alwaysok = true;
upb_handlers_addcleanup(h, d, upb_gfree);
#define TYPE(u, l) \
@ -595,7 +562,6 @@ bool upb_msg_setscalarhandler(upb_handlers *h, const upb_fielddef *f,
}
#undef TYPE
upb_handlerattr_uninit(&attr);
return ok;
}
@ -605,7 +571,8 @@ bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
size_t *offset,
int32_t *hasbit) {
const upb_msg_handlerdata *d;
upb_func *f = upb_handlers_gethandler(h, s);
const void *p;
upb_func *f = upb_handlers_gethandler(h, s, &p);
if ((upb_int64_handlerfunc*)f == upb_msg_setint64) {
*type = UPB_TYPE_INT64;
@ -625,7 +592,7 @@ bool upb_msg_getscalarhandlerdata(const upb_handlers *h,
return false;
}
d = upb_handlers_gethandlerdata(h, s);
d = p;
*offset = d->offset;
*hasbit = d->hasbit;
return true;

@ -24,21 +24,13 @@
#ifdef __cplusplus
namespace upb {
class BufferHandle;
class BytesHandler;
class HandlerAttributes;
class Handlers;
class HandlersPtr;
class HandlerCache;
template <class T> class Handler;
template <class T> struct CanonicalType;
} /* namespace upb */
#endif
UPB_DECLARE_TYPE(upb::BufferHandle, upb_bufhandle)
UPB_DECLARE_TYPE(upb::BytesHandler, upb_byteshandler)
UPB_DECLARE_TYPE(upb::HandlerAttributes, upb_handlerattr)
UPB_DECLARE_TYPE(upb::Handlers, upb_handlers)
UPB_DECLARE_TYPE(upb::HandlerCache, upb_handlercache)
/* The maximum depth that the handler graph can have. This is a resource limit
* for the C stack since we sometimes need to recursively traverse the graph.
@ -80,28 +72,6 @@ extern char _upb_noclosure;
* (for example: the STARTSUBMSG handler for field "field15"). */
typedef int32_t upb_selector_t;
UPB_BEGIN_EXTERN_C
/* Forward-declares for C inline accessors. We need to declare these here
* so we can "friend" them in the class declarations in C++. */
UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h,
upb_selector_t s);
UPB_INLINE const void *upb_handlerattr_handlerdata(const upb_handlerattr *attr);
UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h,
upb_selector_t s);
UPB_INLINE void upb_bufhandle_init(upb_bufhandle *h);
UPB_INLINE void upb_bufhandle_setobj(upb_bufhandle *h, const void *obj,
const void *type);
UPB_INLINE void upb_bufhandle_setbuf(upb_bufhandle *h, const char *buf,
size_t ofs);
UPB_INLINE const void *upb_bufhandle_obj(const upb_bufhandle *h);
UPB_INLINE const void *upb_bufhandle_objtype(const upb_bufhandle *h);
UPB_INLINE const char *upb_bufhandle_buf(const upb_bufhandle *h);
UPB_END_EXTERN_C
/* Static selectors for upb::Handlers. */
#define UPB_STARTMSG_SELECTOR 0
#define UPB_ENDMSG_SELECTOR 1
@ -113,126 +83,234 @@ UPB_END_EXTERN_C
#define UPB_STRING_SELECTOR 1
#define UPB_ENDSTR_SELECTOR 2
typedef void upb_handlerfree(void *d);
#ifdef __cplusplus
/* A set of attributes that accompanies a handler's function pointer. */
class upb::HandlerAttributes {
public:
HandlerAttributes();
~HandlerAttributes();
/* Sets the handler data that will be passed as the second parameter of the
* handler. To free this pointer when the handlers are freed, call
* Handlers::AddCleanup(). */
bool SetHandlerData(const void *handler_data);
const void* handler_data() const;
/* Use this to specify the type of the closure. This will be checked against
* all other closure types for handler that use the same closure.
* Registration will fail if this does not match all other non-NULL closure
* types. */
bool SetClosureType(const void *closure_type);
const void* closure_type() const;
/* Use this to specify the type of the returned closure. Only used for
* Start*{String,SubMessage,Sequence} handlers. This must match the closure
* type of any handlers that use it (for example, the StringBuf handler must
* match the closure returned from StartString). */
bool SetReturnClosureType(const void *return_closure_type);
const void* return_closure_type() const;
/* Set to indicate that the handler always returns "ok" (either "true" or a
* non-NULL closure). This is a hint that can allow code generators to
* generate more efficient code. */
bool SetAlwaysOk(bool always_ok);
bool always_ok() const;
private:
friend UPB_INLINE const void * ::upb_handlerattr_handlerdata(
const upb_handlerattr *attr);
#else
struct upb_handlerattr {
template<class T> const void *UniquePtrForType() {
static const char ch = 0;
return &ch;
}
#endif
const void *handler_data_;
const void *closure_type_;
const void *return_closure_type_;
bool alwaysok_;
};
#define UPB_HANDLERATTR_INITIALIZER {NULL, NULL, NULL, false}
/* upb_handlers ************************************************************/
/* Handler attributes, to be registered with the handler itself. */
typedef struct {
upb_func *func;
const void *handler_data;
const void *closure_type;
const void *return_closure_type;
bool alwaysok;
} upb_handlerattr;
/* It is wasteful to include the entire attributes here:
*
* * Some of the information is redundant (like storing the closure type
* separately for each handler that must match).
* * Some of the info is only needed prior to freeze() (like closure types).
* * alignment padding wastes a lot of space for alwaysok_.
*
* If/when the size and locality of handlers is an issue, we can optimize this
* not to store the entire attr like this. We do not expose the table's
* layout to allow this optimization in the future. */
upb_handlerattr attr;
} upb_handlers_tabent;
#ifdef __cplusplus
/* Extra information about a buffer that is passed to a StringBuf handler.
* TODO(haberman): allow the handle to be pinned so that it will outlive
* the handler invocation. */
class upb::BufferHandle {
public:
BufferHandle();
~BufferHandle();
#define UPB_HANDLERATTR_INIT {NULL, NULL, NULL, false}
/* Bufhandle, data passed along with a buffer to indicate its provenance. */
typedef struct {
/* The beginning of the buffer. This may be different than the pointer
* passed to a StringBuf handler because the handler may receive data
* that is from the middle or end of a larger buffer. */
const char* buffer() const;
const char *buf;
/* The offset within the attached object where this buffer begins. Only
* meaningful if there is an attached object. */
size_t object_offset() const;
size_t objofs;
/* Note that object_offset is the offset of "buf" within the attached
* object. */
void SetBuffer(const char* buf, size_t object_offset);
/* The attached object (if any) and a pointer representing its type. */
const void *obj;
const void *objtype;
/* The BufferHandle can have an "attached object", which can be used to
* tunnel through a pointer to the buffer's underlying representation. */
#ifdef __cplusplus
template <class T>
void SetAttachedObject(const T* obj);
void SetAttachedObject(const T* _obj) {
obj = _obj;
objtype = UniquePtrForType<T>();
}
/* Returns NULL if the attached object is not of this type. */
template <class T>
const T* GetAttachedObject() const;
private:
friend UPB_INLINE void ::upb_bufhandle_init(upb_bufhandle *h);
friend UPB_INLINE void ::upb_bufhandle_setobj(upb_bufhandle *h,
const void *obj,
const void *type);
friend UPB_INLINE void ::upb_bufhandle_setbuf(upb_bufhandle *h,
const char *buf, size_t ofs);
friend UPB_INLINE const void* ::upb_bufhandle_obj(const upb_bufhandle *h);
friend UPB_INLINE const void* ::upb_bufhandle_objtype(
const upb_bufhandle *h);
friend UPB_INLINE const char* ::upb_bufhandle_buf(const upb_bufhandle *h);
#else
struct upb_bufhandle {
const T *GetAttachedObject() const {
return objtype == UniquePtrForType<T>() ? static_cast<const T *>(obj)
: NULL;
}
#endif
const char *buf_;
const void *obj_;
const void *objtype_;
size_t objofs_;
};
} upb_bufhandle;
#define UPB_BUFHANDLE_INIT {NULL, 0, NULL, NULL}
/* Handler function typedefs. */
typedef void upb_handlerfree(void *d);
typedef bool upb_unknown_handlerfunc(void *c, const void *hd, const char *buf,
size_t n);
typedef bool upb_startmsg_handlerfunc(void *c, const void*);
typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status);
typedef void* upb_startfield_handlerfunc(void *c, const void *hd);
typedef bool upb_endfield_handlerfunc(void *c, const void *hd);
typedef bool upb_int32_handlerfunc(void *c, const void *hd, int32_t val);
typedef bool upb_int64_handlerfunc(void *c, const void *hd, int64_t val);
typedef bool upb_uint32_handlerfunc(void *c, const void *hd, uint32_t val);
typedef bool upb_uint64_handlerfunc(void *c, const void *hd, uint64_t val);
typedef bool upb_float_handlerfunc(void *c, const void *hd, float val);
typedef bool upb_double_handlerfunc(void *c, const void *hd, double val);
typedef bool upb_bool_handlerfunc(void *c, const void *hd, bool val);
typedef void *upb_startstr_handlerfunc(void *c, const void *hd,
size_t size_hint);
typedef size_t upb_string_handlerfunc(void *c, const void *hd, const char *buf,
size_t n, const upb_bufhandle* handle);
struct upb_handlers;
typedef struct upb_handlers upb_handlers;
UPB_BEGIN_EXTERN_C
/* Mutating accessors. */
const upb_status *upb_handlers_status(upb_handlers *h);
void upb_handlers_clearerr(upb_handlers *h);
const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h);
bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree);
bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setint32(upb_handlers *h, const upb_fielddef *f,
upb_int32_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setint64(upb_handlers *h, const upb_fielddef *f,
upb_int64_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setuint32(upb_handlers *h, const upb_fielddef *f,
upb_uint32_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setuint64(upb_handlers *h, const upb_fielddef *f,
upb_uint64_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setfloat(upb_handlers *h, const upb_fielddef *f,
upb_float_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setdouble(upb_handlers *h, const upb_fielddef *f,
upb_double_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setbool(upb_handlers *h, const upb_fielddef *f,
upb_bool_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setstartstr(upb_handlers *h, const upb_fielddef *f,
upb_startstr_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setstring(upb_handlers *h, const upb_fielddef *f,
upb_string_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setendstr(upb_handlers *h, const upb_fielddef *f,
upb_endfield_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setstartseq(upb_handlers *h, const upb_fielddef *f,
upb_startfield_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setstartsubmsg(upb_handlers *h, const upb_fielddef *f,
upb_startfield_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setendsubmsg(upb_handlers *h, const upb_fielddef *f,
upb_endfield_handlerfunc *func,
const upb_handlerattr *attr);
bool upb_handlers_setendseq(upb_handlers *h, const upb_fielddef *f,
upb_endfield_handlerfunc *func,
const upb_handlerattr *attr);
/* Read-only accessors. */
const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
const upb_fielddef *f);
const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
upb_selector_t sel);
upb_func *upb_handlers_gethandler(const upb_handlers *h, upb_selector_t s,
const void **handler_data);
bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t s,
upb_handlerattr *attr);
/* "Static" methods */
upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f);
bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
upb_selector_t *s);
UPB_INLINE upb_selector_t upb_handlers_getendselector(upb_selector_t start) {
return start + 1;
}
/* Internal-only. */
uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f);
uint32_t upb_handlers_selectorcount(const upb_fielddef *f);
UPB_END_EXTERN_C
#ifdef __cplusplus
namespace upb {
typedef upb_handlers Handlers;
}
/* Convenience macros for creating a Handler object that is wrapped with a
* type-safe wrapper function that converts the "void*" parameters/returns
* of the underlying C API into nice C++ function.
*
* Sample usage:
* void OnValue1(MyClosure* c, const MyHandlerData* d, int32_t val) {
* // do stuff ...
* }
*
* // Handler that doesn't need any data bound to it.
* void OnValue2(MyClosure* c, int32_t val) {
* // do stuff ...
* }
*
* // Handler that returns bool so it can return failure if necessary.
* bool OnValue3(MyClosure* c, int32_t val) {
* // do stuff ...
* return ok;
* }
*
* // Member function handler.
* class MyClosure {
* public:
* void OnValue(int32_t val) {
* // do stuff ...
* }
* };
*
* // Takes ownership of the MyHandlerData.
* handlers->SetInt32Handler(f1, UpbBind(OnValue1, new MyHandlerData(...)));
* handlers->SetInt32Handler(f2, UpbMakeHandler(OnValue2));
* handlers->SetInt32Handler(f1, UpbMakeHandler(OnValue3));
* handlers->SetInt32Handler(f2, UpbMakeHandler(&MyClosure::OnValue));
*/
/* In C++11, the "template" disambiguator can appear even outside templates,
* so all calls can safely use this pair of macros. */
#define UpbMakeHandler(f) upb::MatchFunc(f).template GetFunc<f>()
/* We have to be careful to only evaluate "d" once. */
#define UpbBind(f, d) upb::MatchFunc(f).template GetFunc<f>((d))
/* Handler: a struct that contains the (handler, data, deleter) tuple that is
* used to register all handlers. Users can Make() these directly but it's
* more convenient to use the UpbMakeHandler/UpbBind macros above. */
template <class T> class upb::Handler {
public:
/* The underlying, handler function signature that upb uses internally. */
typedef T FuncPtr;
/* Intentionally implicit. */
template <class F> Handler(F func);
~Handler() { UPB_ASSERT(registered_); }
void AddCleanup(upb_handlers* h) const;
FuncPtr handler() const { return handler_; }
const upb_handlerattr& attr() const { return attr_; }
private:
UPB_DISALLOW_COPY_AND_ASSIGN(Handler)
FuncPtr handler_;
mutable upb_handlerattr attr_;
mutable bool registered_;
void *cleanup_data_;
upb_handlerfree *cleanup_func_;
};
/* A upb::Handlers object represents the set of handlers associated with a
* message in the graph of messages. You can think of it as a big virtual
* table with functions corresponding to all the events that can fire while
@ -244,18 +322,23 @@ struct upb_bufhandle {
*
* The easiest way to create the *Handler objects needed by the Set* methods is
* with the UpbBind() and UpbMakeHandler() macros; see below. */
class upb::Handlers {
class upb::HandlersPtr {
public:
HandlersPtr(upb_handlers* ptr) : ptr_(ptr) {}
upb_handlers* ptr() const { return ptr_; }
typedef upb_selector_t Selector;
typedef upb_handlertype_t Type;
typedef Handler<void *(*)(void *, const void *)> StartFieldHandler;
typedef Handler<bool (*)(void *, const void *)> EndFieldHandler;
typedef Handler<bool (*)(void *, const void *)> StartMessageHandler;
typedef Handler<bool (*)(void *, const void *, Status*)> EndMessageHandler;
typedef Handler<bool (*)(void *, const void *, Status *)> EndMessageHandler;
typedef Handler<void *(*)(void *, const void *, size_t)> StartStringHandler;
typedef Handler<size_t (*)(void *, const void *, const char *, size_t,
const BufferHandle *)> StringHandler;
const upb_bufhandle *)>
StringHandler;
template <class T> struct ValueHandler {
typedef Handler<bool(*)(void *, const void *, T)> H;
@ -275,21 +358,17 @@ class upb::Handlers {
typedef void HandlersCallback(const void *closure, upb_handlers *h);
/* All handler registration functions return bool to indicate success or
* failure; details about failures are stored in this status object. If a
* failure does occur, it must be cleared before the Handlers are frozen,
* otherwise the freeze() operation will fail. The functions may *only* be
* used while the Handlers are mutable. */
const Status* status();
void ClearError();
/* Returns the msgdef associated with this handlers object. */
const MessageDef* message_def() const;
MessageDefPtr message_def() const {
return MessageDefPtr(upb_handlers_msgdef(ptr()));
}
/* Adds the given pointer and function to the list of cleanup functions that
* will be run when these handlers are freed. If this pointer has previously
* been registered, the function returns false and does nothing. */
bool AddCleanup(void *ptr, upb_handlerfree *cleanup);
bool AddCleanup(void *ptr, upb_handlerfree *cleanup) {
return upb_handlers_addcleanup(ptr_, ptr, cleanup);
}
/* Sets the startmsg handler for the message, which is defined as follows:
*
@ -299,7 +378,10 @@ class upb::Handlers {
* return true;
* }
*/
bool SetStartMessageHandler(const StartMessageHandler& handler);
bool SetStartMessageHandler(const StartMessageHandler &h) {
h.AddCleanup(ptr());
return upb_handlers_setstartmsg(ptr(), h.handler(), &h.attr());
}
/* Sets the endmsg handler for the message, which is defined as follows:
*
@ -309,7 +391,10 @@ class upb::Handlers {
* // can also be modified in-place to update the final status.
* }
*/
bool SetEndMessageHandler(const EndMessageHandler& handler);
bool SetEndMessageHandler(const EndMessageHandler& h) {
h.AddCleanup(ptr());
return upb_handlers_setendmsg(ptr(), h.handler(), &h.attr());
}
/* Sets the value handler for the given field, which is defined as follows
* (this is for an int32 field; other field types will pass their native
@ -331,13 +416,40 @@ class upb::Handlers {
* Returns false if the handler failed to register; in this case the cleanup
* handler (if any) will be called immediately.
*/
bool SetInt32Handler (const FieldDef* f, const Int32Handler& h);
bool SetInt64Handler (const FieldDef* f, const Int64Handler& h);
bool SetUInt32Handler(const FieldDef* f, const UInt32Handler& h);
bool SetUInt64Handler(const FieldDef* f, const UInt64Handler& h);
bool SetFloatHandler (const FieldDef* f, const FloatHandler& h);
bool SetDoubleHandler(const FieldDef* f, const DoubleHandler& h);
bool SetBoolHandler (const FieldDef* f, const BoolHandler& h);
bool SetInt32Handler(FieldDefPtr f, const Int32Handler &h) {
h.AddCleanup(ptr());
return upb_handlers_setint32(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetInt64Handler (FieldDefPtr f, const Int64Handler& h) {
h.AddCleanup(ptr());
return upb_handlers_setint64(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetUInt32Handler(FieldDefPtr f, const UInt32Handler& h) {
h.AddCleanup(ptr());
return upb_handlers_setuint32(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetUInt64Handler(FieldDefPtr f, const UInt64Handler& h) {
h.AddCleanup(ptr());
return upb_handlers_setuint64(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetFloatHandler (FieldDefPtr f, const FloatHandler& h) {
h.AddCleanup(ptr());
return upb_handlers_setfloat(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetDoubleHandler(FieldDefPtr f, const DoubleHandler& h) {
h.AddCleanup(ptr());
return upb_handlers_setdouble(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetBoolHandler(FieldDefPtr f, const BoolHandler &h) {
h.AddCleanup(ptr());
return upb_handlers_setbool(ptr(), f.ptr(), h.handler(), &h.attr());
}
/* Like the previous, but templated on the type on the value (ie. int32).
* This is mostly useful to call from other templates. To call this you must
@ -345,8 +457,8 @@ class upb::Handlers {
* h->SetValueHandler<T>(f, UpbBind(MyHandler<T>, MyData)); */
template <class T>
bool SetValueHandler(
const FieldDef *f,
const typename ValueHandler<typename CanonicalType<T>::Type>::H& handler);
FieldDefPtr f,
const typename ValueHandler<typename CanonicalType<T>::Type>::H &handler);
/* Sets handlers for a string field, which are defined as follows:
*
@ -384,9 +496,20 @@ class upb::Handlers {
* return true;
* }
*/
bool SetStartStringHandler(const FieldDef* f, const StartStringHandler& h);
bool SetStringHandler(const FieldDef* f, const StringHandler& h);
bool SetEndStringHandler(const FieldDef* f, const EndFieldHandler& h);
bool SetStartStringHandler(FieldDefPtr f, const StartStringHandler &h) {
h.AddCleanup(ptr());
return upb_handlers_setstartstr(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetStringHandler(FieldDefPtr f, const StringHandler& h) {
h.AddCleanup(ptr());
return upb_handlers_setstring(ptr(), f.ptr(), h.handler(), &h.attr());
}
bool SetEndStringHandler(FieldDefPtr f, const EndFieldHandler& h) {
h.AddCleanup(ptr());
return upb_handlers_setendstr(ptr(), f.ptr(), h.handler(), &h.attr());
}
/* Sets the startseq handler, which is defined as follows:
*
@ -402,7 +525,10 @@ class upb::Handlers {
* Returns "false" if "f" does not belong to this message or is not a
* repeated field.
*/
bool SetStartSequenceHandler(const FieldDef* f, const StartFieldHandler& h);
bool SetStartSequenceHandler(FieldDefPtr f, const StartFieldHandler &h) {
h.AddCleanup(ptr());
return upb_handlers_setstartseq(ptr(), f.ptr(), h.handler(), &h.attr());
}
/* Sets the startsubmsg handler for the given field, which is defined as
* follows:
@ -419,7 +545,10 @@ class upb::Handlers {
* Returns "false" if "f" does not belong to this message or is not a
* submessage/group field.
*/
bool SetStartSubMessageHandler(const FieldDef* f, const StartFieldHandler& h);
bool SetStartSubMessageHandler(FieldDefPtr f, const StartFieldHandler& h) {
h.AddCleanup(ptr());
return upb_handlers_setstartsubmsg(ptr(), f.ptr(), h.handler(), &h.attr());
}
/* Sets the endsubmsg handler for the given field, which is defined as
* follows:
@ -432,7 +561,10 @@ class upb::Handlers {
* Returns "false" if "f" does not belong to this message or is not a
* submessage/group field.
*/
bool SetEndSubMessageHandler(const FieldDef *f, const EndFieldHandler &h);
bool SetEndSubMessageHandler(FieldDefPtr f, const EndFieldHandler &h) {
h.AddCleanup(ptr());
return upb_handlers_setendsubmsg(ptr(), f.ptr(), h.handler(), &h.attr());
}
/* Starts the endsubseq handler for the given field, which is defined as
* follows:
@ -445,328 +577,93 @@ class upb::Handlers {
* Returns "false" if "f" does not belong to this message or is not a
* repeated field.
*/
bool SetEndSequenceHandler(const FieldDef* f, const EndFieldHandler& h);
/* Gets the object that specifies handlers for the given field, which
* must be a submessage or group. Returns NULL if no handlers are set. */
const Handlers* GetSubHandlers(const FieldDef* f) const;
/* Equivalent to GetSubHandlers, but takes the STARTSUBMSG selector for the
* field. */
const Handlers* GetSubHandlers(Selector startsubmsg) const;
/* A selector refers to a specific field handler in the Handlers object
* (for example: the STARTSUBMSG handler for field "field15").
* On success, returns true and stores the selector in "s".
* If the FieldDef or Type are invalid, returns false.
* The returned selector is ONLY valid for Handlers whose MessageDef
* contains this FieldDef. */
static bool GetSelector(const FieldDef* f, Type type, Selector* s);
/* Given a START selector of any kind, returns the corresponding END selector. */
static Selector GetEndSelector(Selector start_selector);
/* Returns the function pointer for this handler. It is the client's
* responsibility to cast to the correct function type before calling it. */
GenericFunction* GetHandler(Selector selector);
/* Sets the given attributes to the attributes for this selector. */
bool GetAttributes(Selector selector, HandlerAttributes* attr);
/* Returns the handler data that was registered with this handler. */
const void* GetHandlerData(Selector selector);
/* Could add any of the following functions as-needed, with some minor
* implementation changes:
*
* const FieldDef* GetFieldDef(Selector selector);
* static bool IsSequence(Selector selector); */
bool SetEndSequenceHandler(FieldDefPtr f, const EndFieldHandler &h) {
h.AddCleanup(ptr());
return upb_handlers_setendseq(ptr(), f.ptr(), h.handler(), &h.attr());
}
private:
UPB_DISALLOW_POD_OPS(Handlers, upb::Handlers)
friend UPB_INLINE GenericFunction *::upb_handlers_gethandler(
const upb_handlers *h, upb_selector_t s);
friend UPB_INLINE const void *::upb_handlers_gethandlerdata(
const upb_handlers *h, upb_selector_t s);
#else
struct upb_handlers {
#endif
upb_handlercache *cache;
const upb_msgdef *msg;
const upb_handlers **sub;
const void *top_closure_type;
upb_handlers_tabent table[1]; /* Dynamically-sized field handler array. */
upb_handlers* ptr_;
};
#ifdef __cplusplus
namespace upb {
/* Convenience macros for creating a Handler object that is wrapped with a
* type-safe wrapper function that converts the "void*" parameters/returns
* of the underlying C API into nice C++ function.
*
* Sample usage:
* void OnValue1(MyClosure* c, const MyHandlerData* d, int32_t val) {
* // do stuff ...
* }
*
* // Handler that doesn't need any data bound to it.
* void OnValue2(MyClosure* c, int32_t val) {
* // do stuff ...
* }
*
* // Handler that returns bool so it can return failure if necessary.
* bool OnValue3(MyClosure* c, int32_t val) {
* // do stuff ...
* return ok;
* }
*
* // Member function handler.
* class MyClosure {
* public:
* void OnValue(int32_t val) {
* // do stuff ...
* }
* };
*
* // Takes ownership of the MyHandlerData.
* handlers->SetInt32Handler(f1, UpbBind(OnValue1, new MyHandlerData(...)));
* handlers->SetInt32Handler(f2, UpbMakeHandler(OnValue2));
* handlers->SetInt32Handler(f1, UpbMakeHandler(OnValue3));
* handlers->SetInt32Handler(f2, UpbMakeHandler(&MyClosure::OnValue));
*/
#ifdef UPB_CXX11
/* In C++11, the "template" disambiguator can appear even outside templates,
* so all calls can safely use this pair of macros. */
#define UpbMakeHandler(f) upb::MatchFunc(f).template GetFunc<f>()
/* We have to be careful to only evaluate "d" once. */
#define UpbBind(f, d) upb::MatchFunc(f).template GetFunc<f>((d))
#endif /* __cplusplus */
#else
/* upb_handlercache ***********************************************************/
/* Prior to C++11, the "template" disambiguator may only appear inside a
* template, so the regular macro must not use "template" */
UPB_BEGIN_EXTERN_C
#define UpbMakeHandler(f) upb::MatchFunc(f).GetFunc<f>()
struct upb_handlercache;
typedef struct upb_handlercache upb_handlercache;
#define UpbBind(f, d) upb::MatchFunc(f).GetFunc<f>((d))
typedef void upb_handlers_callback(const void *closure, upb_handlers *h);
#endif /* UPB_CXX11 */
upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
const void *closure);
void upb_handlercache_free(upb_handlercache *cache);
const upb_handlers *upb_handlercache_get(upb_handlercache *cache,
const upb_msgdef *md);
/* This macro must be used in C++98 for calls from inside a template. But we
* define this variant in all cases; code that wants to be compatible with both
* C++98 and C++11 should always use this macro when calling from a template. */
#define UpbMakeHandlerT(f) upb::MatchFunc(f).template GetFunc<f>()
UPB_END_EXTERN_C
/* We have to be careful to only evaluate "d" once. */
#define UpbBindT(f, d) upb::MatchFunc(f).template GetFunc<f>((d))
#ifdef __cplusplus
/* Handler: a struct that contains the (handler, data, deleter) tuple that is
* used to register all handlers. Users can Make() these directly but it's
* more convenient to use the UpbMakeHandler/UpbBind macros above. */
template <class T> class Handler {
class upb::HandlerCache {
public:
/* The underlying, handler function signature that upb uses internally. */
typedef T FuncPtr;
HandlerCache(upb_handlers_callback *callback, const void *closure)
: ptr_(upb_handlercache_new(callback, closure), upb_handlercache_free) {}
HandlerCache(HandlerCache&&) = default;
HandlerCache& operator=(HandlerCache&&) = default;
HandlerCache(upb_handlercache* c) : ptr_(c, upb_handlercache_free) {}
/* Intentionally implicit. */
template <class F> Handler(F func);
~Handler();
upb_handlercache* ptr() { return ptr_.get(); }
private:
void AddCleanup(Handlers* h) const {
if (cleanup_func_) {
bool ok = h->AddCleanup(cleanup_data_, cleanup_func_);
UPB_ASSERT(ok);
}
const upb_handlers *Get(MessageDefPtr md) {
return upb_handlercache_get(ptr_.get(), md.ptr());
}
UPB_DISALLOW_COPY_AND_ASSIGN(Handler)
friend class Handlers;
FuncPtr handler_;
mutable HandlerAttributes attr_;
mutable bool registered_;
void *cleanup_data_;
upb_handlerfree *cleanup_func_;
private:
std::unique_ptr<upb_handlercache, decltype(&upb_handlercache_free)> ptr_;
};
} /* namespace upb */
#endif /* __cplusplus */
UPB_BEGIN_EXTERN_C
/* Native C API. */
/* Handler function typedefs. */
typedef bool upb_unknown_handlerfunc(void *c, const void *hd, const char *buf,
size_t n);
typedef bool upb_startmsg_handlerfunc(void *c, const void*);
typedef bool upb_endmsg_handlerfunc(void *c, const void *, upb_status *status);
typedef void* upb_startfield_handlerfunc(void *c, const void *hd);
typedef bool upb_endfield_handlerfunc(void *c, const void *hd);
typedef bool upb_int32_handlerfunc(void *c, const void *hd, int32_t val);
typedef bool upb_int64_handlerfunc(void *c, const void *hd, int64_t val);
typedef bool upb_uint32_handlerfunc(void *c, const void *hd, uint32_t val);
typedef bool upb_uint64_handlerfunc(void *c, const void *hd, uint64_t val);
typedef bool upb_float_handlerfunc(void *c, const void *hd, float val);
typedef bool upb_double_handlerfunc(void *c, const void *hd, double val);
typedef bool upb_bool_handlerfunc(void *c, const void *hd, bool val);
typedef void *upb_startstr_handlerfunc(void *c, const void *hd,
size_t size_hint);
typedef size_t upb_string_handlerfunc(void *c, const void *hd, const char *buf,
size_t n, const upb_bufhandle* handle);
/* upb_byteshandler ***********************************************************/
/* upb_bufhandle */
size_t upb_bufhandle_objofs(const upb_bufhandle *h);
/* upb_handlerattr */
void upb_handlerattr_init(upb_handlerattr *attr);
void upb_handlerattr_uninit(upb_handlerattr *attr);
bool upb_handlerattr_sethandlerdata(upb_handlerattr *attr, const void *hd);
bool upb_handlerattr_setclosuretype(upb_handlerattr *attr, const void *type);
const void *upb_handlerattr_closuretype(const upb_handlerattr *attr);
bool upb_handlerattr_setreturnclosuretype(upb_handlerattr *attr,
const void *type);
const void *upb_handlerattr_returnclosuretype(const upb_handlerattr *attr);
bool upb_handlerattr_setalwaysok(upb_handlerattr *attr, bool alwaysok);
bool upb_handlerattr_alwaysok(const upb_handlerattr *attr);
UPB_INLINE const void *upb_handlerattr_handlerdata(
const upb_handlerattr *attr) {
return attr->handler_data_;
}
UPB_BEGIN_EXTERN_C
/* upb_handlers */
const upb_status *upb_handlers_status(upb_handlers *h);
void upb_handlers_clearerr(upb_handlers *h);
const upb_msgdef *upb_handlers_msgdef(const upb_handlers *h);
bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *hfree);
bool upb_handlers_setunknown(upb_handlers *h, upb_unknown_handlerfunc *func,
upb_handlerattr *attr);
typedef struct {
upb_func *func;
bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setint32(upb_handlers *h, const upb_fielddef *f,
upb_int32_handlerfunc *func, upb_handlerattr *attr);
bool upb_handlers_setint64(upb_handlers *h, const upb_fielddef *f,
upb_int64_handlerfunc *func, upb_handlerattr *attr);
bool upb_handlers_setuint32(upb_handlers *h, const upb_fielddef *f,
upb_uint32_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setuint64(upb_handlers *h, const upb_fielddef *f,
upb_uint64_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setfloat(upb_handlers *h, const upb_fielddef *f,
upb_float_handlerfunc *func, upb_handlerattr *attr);
bool upb_handlers_setdouble(upb_handlers *h, const upb_fielddef *f,
upb_double_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setbool(upb_handlers *h, const upb_fielddef *f,
upb_bool_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setstartstr(upb_handlers *h, const upb_fielddef *f,
upb_startstr_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setstring(upb_handlers *h, const upb_fielddef *f,
upb_string_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setendstr(upb_handlers *h, const upb_fielddef *f,
upb_endfield_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setstartseq(upb_handlers *h, const upb_fielddef *f,
upb_startfield_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setstartsubmsg(upb_handlers *h, const upb_fielddef *f,
upb_startfield_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setendsubmsg(upb_handlers *h, const upb_fielddef *f,
upb_endfield_handlerfunc *func,
upb_handlerattr *attr);
bool upb_handlers_setendseq(upb_handlers *h, const upb_fielddef *f,
upb_endfield_handlerfunc *func,
upb_handlerattr *attr);
/* It is wasteful to include the entire attributes here:
*
* * Some of the information is redundant (like storing the closure type
* separately for each handler that must match).
* * Some of the info is only needed prior to freeze() (like closure types).
* * alignment padding wastes a lot of space for alwaysok_.
*
* If/when the size and locality of handlers is an issue, we can optimize this
* not to store the entire attr like this. We do not expose the table's
* layout to allow this optimization in the future. */
upb_handlerattr attr;
} upb_handlers_tabent;
const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
const upb_fielddef *f);
const upb_handlers *upb_handlers_getsubhandlers_sel(const upb_handlers *h,
upb_selector_t sel);
#define UPB_TABENT_INIT {NULL, UPB_HANDLERATTR_INIT}
UPB_INLINE upb_func *upb_handlers_gethandler(const upb_handlers *h,
upb_selector_t s) {
return (upb_func *)h->table[s].func;
}
typedef struct {
upb_handlers_tabent table[3];
} upb_byteshandler;
bool upb_handlers_getattr(const upb_handlers *h, upb_selector_t s,
upb_handlerattr *attr);
#define UPB_BYTESHANDLER_INIT \
{ \
{ UPB_TABENT_INIT, UPB_TABENT_INIT, UPB_TABENT_INIT } \
}
UPB_INLINE const void *upb_handlers_gethandlerdata(const upb_handlers *h,
upb_selector_t s) {
return upb_handlerattr_handlerdata(&h->table[s].attr);
UPB_INLINE void upb_byteshandler_init(upb_byteshandler *handler) {
upb_byteshandler init = UPB_BYTESHANDLER_INIT;
*handler = init;
}
typedef void upb_handlers_callback(const void *closure, upb_handlers *h);
#ifdef __cplusplus
class upb::HandlerCache {
public:
static HandlerCache *New(upb_handlers_callback *callback,
const void *closure);
static void Free(HandlerCache* cache);
const Handlers* Get(const MessageDef* md);
private:
UPB_DISALLOW_POD_OPS(HandlerCache, upb::pb::HandlerCache)
#else
struct upb_handlercache {
#endif
upb_arena arena;
upb_inttable tab; /* maps upb_msgdef* -> upb_handlers*. */
upb_inttable cleanup_;
upb_handlers_callback *callback;
const void *closure;
};
upb_handlercache *upb_handlercache_new(upb_handlers_callback *callback,
const void *closure);
void upb_handlercache_free(upb_handlercache *cache);
const upb_handlers *upb_handlercache_get(upb_handlercache *cache,
const upb_msgdef *md);
#ifdef __cplusplus
/* Handler types for single fields.
* Right now we only have one for TYPE_BYTES but ones for other types
* should follow.
*
* These follow the same handlers protocol for fields of a message. */
class upb::BytesHandler {
public:
BytesHandler();
~BytesHandler();
#else
struct upb_byteshandler {
#endif
upb_handlers_tabent table[3];
};
void upb_byteshandler_init(upb_byteshandler *h);
/* Caller must ensure that "d" outlives the handlers.
* TODO(haberman): should this have a "freeze" operation? It's not necessary
* for memory management, but could be useful to force immutability and provide
* a convenient moment to verify that all registration succeeded. */
/* Caller must ensure that "d" outlives the handlers. */
bool upb_byteshandler_setstartstr(upb_byteshandler *h,
upb_startstr_handlerfunc *func, void *d);
bool upb_byteshandler_setstring(upb_byteshandler *h,
@ -774,21 +671,18 @@ bool upb_byteshandler_setstring(upb_byteshandler *h,
bool upb_byteshandler_setendstr(upb_byteshandler *h,
upb_endfield_handlerfunc *func, void *d);
/* "Static" methods */
upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f);
bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
upb_selector_t *s);
UPB_INLINE upb_selector_t upb_handlers_getendselector(upb_selector_t start) {
return start + 1;
#ifdef __cplusplus
namespace upb {
typedef upb_byteshandler BytesHandler;
}
#endif
/* Internal-only. */
uint32_t upb_handlers_selectorbaseoffset(const upb_fielddef *f);
uint32_t upb_handlers_selectorcount(const upb_fielddef *f);
UPB_END_EXTERN_C
/** Message handlers ******************************************************************/
UPB_BEGIN_EXTERN_C
/* These are the handlers used internally by upb_msgfactory_getmergehandlers().
* They write scalar data to a known offset from the message pointer.
*

@ -601,7 +601,7 @@ static void set_enum_hd(upb_handlers *h,
hd->enumdef = upb_fielddef_enumsubdef(f);
hd->keyname = newstrpc(h, f, preserve_fieldnames);
upb_handlers_addcleanup(h, hd, upb_gfree);
upb_handlerattr_sethandlerdata(attr, hd);
attr->handler_data = hd;
}
/* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
@ -626,7 +626,7 @@ void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
UPB_UNUSED(closure);
@ -690,10 +690,9 @@ void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
break;
case UPB_TYPE_ENUM: {
upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
upb_handlerattr_uninit(&enum_attr);
break;
}
case UPB_TYPE_MESSAGE:
@ -701,8 +700,6 @@ void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
* as appropriate. */
break;
}
upb_handlerattr_uninit(&empty_attr);
}
static bool putseconds(void *closure, const void *handler_data,
@ -948,16 +945,16 @@ void printer_sethandlers_any(const void *closure, upb_handlers *h) {
const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
/* type_url's json name is "@type" */
upb_handlerattr type_name_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr value_name_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
strpc *type_url_json_name = newstrpc_str(h, "@type");
strpc *value_json_name = newstrpc_str(h, "value");
upb_handlerattr_sethandlerdata(&type_name_attr, type_url_json_name);
upb_handlerattr_sethandlerdata(&value_name_attr, value_json_name);
type_name_attr.handler_data = type_url_json_name;
value_name_attr.handler_data = value_json_name;
/* Set up handlers. */
upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
@ -985,7 +982,7 @@ void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
const upb_fielddef* nanos_field =
upb_msgdef_itof(md, UPB_DURATION_NANOS);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
@ -1005,7 +1002,7 @@ void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
const upb_fielddef* nanos_field =
upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
@ -1019,7 +1016,7 @@ void printer_sethandlers_value(const void *closure, upb_handlers *h) {
const upb_msgdef *md = upb_handlers_msgdef(h);
upb_msg_field_iter i;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
@ -1058,7 +1055,7 @@ void printer_sethandlers_value(const void *closure, upb_handlers *h) {
void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
const upb_msgdef *md = upb_handlers_msgdef(h); \
const upb_fielddef* f = upb_msgdef_itof(md, 1); \
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER; \
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
upb_handlers_set##type(h, f, putmethod, &empty_attr); \
@ -1081,7 +1078,7 @@ void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
const upb_msgdef *md = upb_handlers_msgdef(h);
const upb_fielddef* f = upb_msgdef_itof(md, 1);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
upb_handlers_setendseq(h, f, endseq, &empty_attr);
@ -1098,7 +1095,7 @@ void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
const upb_msgdef *md = upb_handlers_msgdef(h);
const upb_fielddef* f = upb_msgdef_itof(md, 1);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
upb_handlers_setendseq(h, f, endmap, &empty_attr);
@ -1114,7 +1111,7 @@ void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
void printer_sethandlers(const void *closure, upb_handlers *h) {
const upb_msgdef *md = upb_handlers_msgdef(h);
bool is_mapentry = upb_msgdef_mapentry(md);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
upb_msg_field_iter i;
const upb_json_printercache *cache = closure;
const bool preserve_fieldnames = cache->preserve_fieldnames;
@ -1181,9 +1178,8 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
const upb_fielddef *f = upb_msg_iter_field(&i);
upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr_sethandlerdata(&name_attr,
newstrpc(h, f, preserve_fieldnames));
upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
if (upb_fielddef_ismap(f)) {
upb_handlers_setstartseq(h, f, startmap, &name_attr);
@ -1205,7 +1201,7 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
/* For now, we always emit symbolic names for enums. We may want an
* option later to control this behavior, but we will wait for a real
* need first. */
upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
if (upb_fielddef_isseq(f)) {
@ -1214,7 +1210,6 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
}
upb_handlerattr_uninit(&enum_attr);
break;
}
case UPB_TYPE_STRING:
@ -1245,11 +1240,8 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
}
break;
}
upb_handlerattr_uninit(&name_attr);
}
upb_handlerattr_uninit(&empty_attr);
#undef TYPE
}

@ -516,7 +516,7 @@ static upb_pbdecodermethod *find_submethod(const compiler *c,
static void putsel(compiler *c, opcode op, upb_selector_t sel,
const upb_handlers *h) {
if (upb_handlers_gethandler(h, sel)) {
if (upb_handlers_gethandler(h, sel, NULL)) {
putop(c, op, sel);
}
}
@ -532,9 +532,9 @@ static bool haslazyhandlers(const upb_handlers *h, const upb_fielddef *f) {
if (!upb_fielddef_lazy(f))
return false;
return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR)) ||
upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING)) ||
upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR));
return upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STARTSTR), NULL) ||
upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_STRING), NULL) ||
upb_handlers_gethandler(h, getsel(f, UPB_HANDLER_ENDSTR), NULL);
}

@ -21,17 +21,13 @@
namespace upb {
namespace pb {
class CodeCache;
class Decoder;
class DecoderMethod;
class DecoderPtr;
class DecoderMethodPtr;
class DecoderMethodOptions;
} /* namespace pb */
} /* namespace upb */
#endif
UPB_DECLARE_TYPE(upb::pb::CodeCache, upb_pbcodecache)
UPB_DECLARE_TYPE(upb::pb::Decoder, upb_pbdecoder)
UPB_DECLARE_TYPE(upb::pb::DecoderMethod, upb_pbdecodermethod)
/* The maximum number of bytes we are required to buffer internally between
* calls to the decoder. The value is 14: a 5 byte unknown tag plus ten-byte
* varint, less one because we are buffering an incomplete value.
@ -39,54 +35,106 @@ UPB_DECLARE_TYPE(upb::pb::DecoderMethod, upb_pbdecodermethod)
* Should only be used by unit tests. */
#define UPB_DECODER_MAX_RESIDUAL_BYTES 14
/* upb_pbdecodermethod ********************************************************/
struct upb_pbdecodermethod;
typedef struct upb_pbdecodermethod upb_pbdecodermethod;
UPB_BEGIN_EXTERN_C
const upb_handlers *upb_pbdecodermethod_desthandlers(
const upb_pbdecodermethod *m);
const upb_byteshandler *upb_pbdecodermethod_inputhandler(
const upb_pbdecodermethod *m);
bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m);
UPB_END_EXTERN_C
#ifdef __cplusplus
/* Represents the code to parse a protobuf according to a destination
* Handlers. */
class upb::pb::DecoderMethod {
class upb::pb::DecoderMethodPtr {
public:
DecoderMethodPtr(const upb_pbdecodermethod* ptr) : ptr_(ptr) {}
const upb_pbdecodermethod* ptr() { return ptr_; }
/* The destination handlers that are statically bound to this method.
* This method is only capable of outputting to a sink that uses these
* handlers. */
const Handlers* dest_handlers() const;
const Handlers *dest_handlers() const {
return upb_pbdecodermethod_desthandlers(ptr_);
}
/* The input handlers for this decoder method. */
const BytesHandler* input_handler() const;
const BytesHandler* input_handler() const {
return upb_pbdecodermethod_inputhandler(ptr_);
}
/* Whether this method is native. */
bool is_native() const;
bool is_native() const {
return upb_pbdecodermethod_isnative(ptr_);
}
private:
UPB_DISALLOW_POD_OPS(DecoderMethod, upb::pb::DecoderMethod)
const upb_pbdecodermethod* ptr_;
};
#endif
/* upb_pbdecoder **************************************************************/
/* Preallocation hint: decoder won't allocate more bytes than this when first
* constructed. This hint may be an overestimate for some build configurations.
* But if the decoder library is upgraded without recompiling the application,
* it may be an underestimate. */
#define UPB_PB_DECODER_SIZE 4416
struct upb_pbdecoder;
typedef struct upb_pbdecoder upb_pbdecoder;
UPB_BEGIN_EXTERN_C
upb_pbdecoder *upb_pbdecoder_create(upb_env *e,
const upb_pbdecodermethod *method,
upb_sink *output);
const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d);
upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d);
uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d);
size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d);
bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max);
void upb_pbdecoder_reset(upb_pbdecoder *d);
UPB_END_EXTERN_C
#ifdef __cplusplus
/* A Decoder receives binary protobuf data on its input sink and pushes the
* decoded data to its output sink. */
class upb::pb::Decoder {
class upb::pb::DecoderPtr {
public:
DecoderPtr(upb_pbdecoder* ptr) : ptr_(ptr) {}
upb_pbdecoder* ptr() { return ptr_; }
/* Constructs a decoder instance for the given method, which must outlive this
* decoder. Any errors during parsing will be set on the given status, which
* must also outlive this decoder.
*
* The sink must match the given method. */
static Decoder* Create(Environment* env, const DecoderMethod* method,
Sink* output);
static DecoderPtr Create(Environment *env, DecoderMethodPtr method,
upb_sink *output) {
return DecoderPtr(upb_pbdecoder_create(env, method.ptr(), output));
}
/* Returns the DecoderMethod this decoder is parsing from. */
const DecoderMethod* method() const;
const DecoderMethodPtr method() const {
return DecoderMethodPtr(upb_pbdecoder_method(ptr_));
}
/* The sink on which this decoder receives input. */
BytesSink* input();
upb_bytessink* input() { return upb_pbdecoder_input(ptr()); }
/* Returns number of bytes successfully parsed.
*
@ -95,7 +143,7 @@ class upb::pb::Decoder {
*
* This value may not be up-to-date when called from inside a parsing
* callback. */
uint64_t BytesParsed() const;
uint64_t BytesParsed() { return upb_pbdecoder_bytesparsed(ptr()); }
/* Gets/sets the parsing nexting limit. If the total number of nested
* submessages and repeated fields hits this limit, parsing will fail. This
@ -104,25 +152,51 @@ class upb::pb::Decoder {
*
* Setting the limit will fail if the parser is currently suspended at a depth
* greater than this, or if memory allocation of the stack fails. */
size_t max_nesting() const;
bool set_max_nesting(size_t max);
size_t max_nesting() { return upb_pbdecoder_maxnesting(ptr()); }
bool set_max_nesting(size_t max) { return upb_pbdecoder_maxnesting(ptr()); }
void Reset();
void Reset() { upb_pbdecoder_reset(ptr()); }
static const size_t kSize = UPB_PB_DECODER_SIZE;
private:
UPB_DISALLOW_POD_OPS(Decoder, upb::pb::Decoder)
upb_pbdecoder *ptr_;
};
#endif /* __cplusplus */
/* upb_pbcodecache ************************************************************/
struct upb_pbcodecache;
typedef struct upb_pbcodecache upb_pbcodecache;
UPB_BEGIN_EXTERN_C
upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest);
void upb_pbcodecache_free(upb_pbcodecache *c);
bool upb_pbcodecache_allowjit(const upb_pbcodecache *c);
void upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow);
void upb_pbcodecache_setlazy(upb_pbcodecache *c, bool lazy);
const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
const upb_msgdef *md);
UPB_END_EXTERN_C
#ifdef __cplusplus
/* A class for caching protobuf processing code, whether bytecode for the
* interpreted decoder or machine code for the JIT.
*
* This class is not thread-safe. */
class upb::pb::CodeCache {
public:
static CodeCache* New(HandlerCache* dest);
static void Free(CodeCache* cache);
CodeCache(upb::HandlerCache *dest)
: ptr_(upb_pbcodecache_new(dest->ptr()), upb_pbcodecache_free) {}
CodeCache(CodeCache&&) = default;
CodeCache& operator=(CodeCache&&) = default;
upb_pbcodecache* ptr() { return ptr_.get(); }
const upb_pbcodecache* ptr() const { return ptr_.get(); }
/* Whether the cache is allowed to generate machine code. Defaults to true.
* There is no real reason to turn it off except for testing or if you are
@ -131,114 +205,27 @@ class upb::pb::CodeCache {
* Note that allow_jit = true does not *guarantee* that the code will be JIT
* compiled. If this platform is not supported or the JIT was not compiled
* in, the code may still be interpreted. */
bool allow_jit() const;
bool allow_jit() const { return upb_pbcodecache_allowjit(ptr()); }
/* This may only be called when the object is first constructed, and prior to
* any code generation. */
void set_allow_jit(bool allow);
void set_allow_jit(bool allow) { upb_pbcodecache_setallowjit(ptr(), allow); }
/* Should the decoder push submessages to lazy handlers for fields that have
* them? The caller should set this iff the lazy handlers expect data that is
* in protobuf binary format and the caller wishes to lazy parse it. */
void set_lazy(bool lazy);
void set_lazy(bool lazy) { upb_pbcodecache_setlazy(ptr(), lazy); }
/* Returns a DecoderMethod that can push data to the given handlers.
* If a suitable method already exists, it will be returned from the cache. */
const DecoderMethod *Get(const MessageDef* md);
const DecoderMethodPtr Get(MessageDefPtr md) {
return DecoderMethodPtr(upb_pbcodecache_get(ptr(), md.ptr()));
}
private:
UPB_DISALLOW_POD_OPS(CodeCache, upb::pb::CodeCache)
std::unique_ptr<upb_pbcodecache, decltype(&upb_pbcodecache_free)> ptr_;
};
#endif
UPB_BEGIN_EXTERN_C
upb_pbdecoder *upb_pbdecoder_create(upb_env *e,
const upb_pbdecodermethod *method,
upb_sink *output);
const upb_pbdecodermethod *upb_pbdecoder_method(const upb_pbdecoder *d);
upb_bytessink *upb_pbdecoder_input(upb_pbdecoder *d);
uint64_t upb_pbdecoder_bytesparsed(const upb_pbdecoder *d);
size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d);
bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max);
void upb_pbdecoder_reset(upb_pbdecoder *d);
const upb_handlers *upb_pbdecodermethod_desthandlers(
const upb_pbdecodermethod *m);
const upb_byteshandler *upb_pbdecodermethod_inputhandler(
const upb_pbdecodermethod *m);
bool upb_pbdecodermethod_isnative(const upb_pbdecodermethod *m);
upb_pbcodecache *upb_pbcodecache_new(upb_handlercache *dest);
void upb_pbcodecache_free(upb_pbcodecache *c);
bool upb_pbcodecache_allowjit(const upb_pbcodecache *c);
void upb_pbcodecache_setallowjit(upb_pbcodecache *c, bool allow);
void upb_pbcodecache_setlazy(upb_pbcodecache *c, bool lazy);
const upb_pbdecodermethod *upb_pbcodecache_get(upb_pbcodecache *c,
const upb_msgdef *md);
UPB_END_EXTERN_C
#ifdef __cplusplus
namespace upb {
namespace pb {
/* static */
inline Decoder* Decoder::Create(Environment* env, const DecoderMethod* m,
Sink* sink) {
return upb_pbdecoder_create(env, m, sink);
}
inline const DecoderMethod* Decoder::method() const {
return upb_pbdecoder_method(this);
}
inline BytesSink* Decoder::input() {
return upb_pbdecoder_input(this);
}
inline uint64_t Decoder::BytesParsed() const {
return upb_pbdecoder_bytesparsed(this);
}
inline size_t Decoder::max_nesting() const {
return upb_pbdecoder_maxnesting(this);
}
inline bool Decoder::set_max_nesting(size_t max) {
return upb_pbdecoder_setmaxnesting(this, max);
}
inline void Decoder::Reset() { upb_pbdecoder_reset(this); }
inline const Handlers* DecoderMethod::dest_handlers() const {
return upb_pbdecodermethod_desthandlers(this);
}
inline const BytesHandler* DecoderMethod::input_handler() const {
return upb_pbdecodermethod_inputhandler(this);
}
inline bool DecoderMethod::is_native() const {
return upb_pbdecodermethod_isnative(this);
}
inline CodeCache* CodeCache::New(HandlerCache* dest) {
return upb_pbcodecache_new(dest);
}
inline void CodeCache::Free(CodeCache* cache) {
upb_pbcodecache_free(cache);
}
inline bool CodeCache::allow_jit() const {
return upb_pbcodecache_allowjit(this);
}
inline void CodeCache::set_allow_jit(bool allow) {
upb_pbcodecache_setallowjit(this, allow);
}
inline const DecoderMethod *CodeCache::Get(const MessageDef *md) {
return upb_pbcodecache_get(this, md);
}
} /* namespace pb */
} /* namespace upb */
#endif /* __cplusplus */
#endif /* UPB_DECODER_H_ */

@ -304,8 +304,7 @@ static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
tag_t *tag = upb_gmalloc(sizeof(tag_t));
tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
upb_handlerattr_init(attr);
upb_handlerattr_sethandlerdata(attr, tag);
attr->handler_data = tag;
upb_handlers_addcleanup(h, tag, upb_gfree);
}
@ -451,7 +450,7 @@ static void newhandlers_callback(const void *closure, upb_handlers *h) {
const upb_fielddef *f = upb_msg_iter_field(&i);
bool packed = upb_fielddef_isseq(f) && upb_fielddef_isprimitive(f) &&
upb_fielddef_packed(f);
upb_handlerattr attr;
upb_handlerattr attr = UPB_HANDLERATTR_INIT;
upb_wiretype_t wt =
packed ? UPB_WIRE_TYPE_DELIMITED
: upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
@ -500,20 +499,17 @@ static void newhandlers_callback(const void *closure, upb_handlers *h) {
break;
case UPB_DESCRIPTOR_TYPE_GROUP: {
/* Endgroup takes a different tag (wire_type = END_GROUP). */
upb_handlerattr attr2;
upb_handlerattr attr2 = UPB_HANDLERATTR_INIT;
new_tag(h, f, UPB_WIRE_TYPE_END_GROUP, &attr2);
upb_handlers_setstartsubmsg(h, f, encode_startgroup, &attr);
upb_handlers_setendsubmsg(h, f, encode_endgroup, &attr2);
upb_handlerattr_uninit(&attr2);
break;
}
}
#undef T
upb_handlerattr_uninit(&attr);
}
}

@ -17,16 +17,14 @@
#ifdef __cplusplus
namespace upb {
namespace pb {
class Encoder;
class EncoderPtr;
} /* namespace pb */
} /* namespace upb */
#endif
UPB_DECLARE_TYPE(upb::pb::Encoder, upb_pb_encoder)
#define UPB_PBENCODER_MAX_NESTING 100
/* upb::pb::Encoder ***********************************************************/
/* upb_pb_encoder *************************************************************/
/* Preallocation hint: decoder won't allocate more bytes than this when first
* constructed. This hint may be an overestimate for some build configurations.
@ -34,28 +32,8 @@ UPB_DECLARE_TYPE(upb::pb::Encoder, upb_pb_encoder)
* it may be an underestimate. */
#define UPB_PB_ENCODER_SIZE 768
#ifdef __cplusplus
class upb::pb::Encoder {
public:
/* Creates a new encoder in the given environment. The Handlers must have
* come from NewHandlers() below. */
static Encoder* Create(Environment* env, const Handlers* handlers,
BytesSink* output);
/* The input to the encoder. */
Sink* input();
/* Creates a new set of handlers for this MessageDef. */
static upb_handlercache* NewCache();
static const size_t kSize = UPB_PB_ENCODER_SIZE;
private:
UPB_DISALLOW_POD_OPS(Encoder, upb::pb::Encoder)
};
#endif
struct upb_pb_encoder;
typedef struct upb_pb_encoder upb_pb_encoder;
UPB_BEGIN_EXTERN_C
@ -69,21 +47,33 @@ UPB_END_EXTERN_C
#ifdef __cplusplus
namespace upb {
namespace pb {
inline Encoder* Encoder::Create(Environment* env, const Handlers* handlers,
class upb::pb::EncoderPtr {
public:
EncoderPtr(upb_pb_encoder* ptr) : ptr_(ptr) {}
upb_pb_encoder* ptr() { return ptr_; }
/* Creates a new encoder in the given environment. The Handlers must have
* come from NewHandlers() below. */
static EncoderPtr Create(Environment* env, const Handlers* handlers,
BytesSink* output) {
return upb_pb_encoder_create(env, handlers, output);
}
inline Sink* Encoder::input() {
return upb_pb_encoder_input(this);
}
inline upb_handlercache* Encoder::NewCache() {
return upb_pb_encoder_newcache();
}
} /* namespace pb */
} /* namespace upb */
return EncoderPtr(upb_pb_encoder_create(env, handlers, output->ptr()));
}
#endif
/* The input to the encoder. */
upb_sink* input() { return upb_pb_encoder_input(ptr()); }
/* Creates a new set of handlers for this MessageDef. */
static HandlerCache NewCache() {
return HandlerCache(upb_pb_encoder_newcache());
}
static const size_t kSize = UPB_PB_ENCODER_SIZE;
private:
upb_pb_encoder* ptr_;
};
#endif /* __cplusplus */
#endif /* UPB_ENCODER_H_ */

@ -260,8 +260,8 @@ static void onmreg(const void *c, upb_handlers *h) {
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
upb_fielddef *f = upb_msg_iter_field(&i);
upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
upb_handlerattr_sethandlerdata(&attr, f);
upb_handlerattr attr = UPB_HANDLERATTR_INIT;
attr.handler_data = f;
switch (upb_fielddef_type(f)) {
case UPB_TYPE_INT32:
upb_handlers_setint32(h, f, textprinter_putint32, &attr);
@ -295,7 +295,7 @@ static void onmreg(const void *c, upb_handlers *h) {
upb_fielddef_descriptortype(f) == UPB_DESCRIPTOR_TYPE_GROUP
? shortname(upb_msgdef_fullname(upb_fielddef_msgsubdef(f)))
: upb_fielddef_name(f);
upb_handlerattr_sethandlerdata(&attr, name);
attr.handler_data = name;
upb_handlers_setstartsubmsg(h, f, textprinter_startsubmsg, &attr);
upb_handlers_setendsubmsg(h, f, textprinter_endsubmsg, &attr);
break;

@ -4,9 +4,8 @@
bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
void *subc;
bool ret;
upb_bufhandle handle;
upb_bufhandle_init(&handle);
upb_bufhandle_setbuf(&handle, buf, 0);
upb_bufhandle handle = UPB_BUFHANDLE_INIT;
handle.buf = buf;
ret = upb_bytessink_start(sink, len, &subc);
if (ret && len != 0) {
ret = (upb_bytessink_putbuf(sink, subc, buf, len, &handle) >= len);
@ -14,7 +13,6 @@ bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink) {
if (ret) {
ret = upb_bytessink_end(sink);
}
upb_bufhandle_uninit(&handle);
return ret;
}

@ -22,17 +22,177 @@
#ifdef __cplusplus
namespace upb {
class BufferSink;
class BufferSource;
class BytesSink;
class Sink;
}
#endif
UPB_DECLARE_TYPE(upb::BufferSink, upb_bufsink)
UPB_DECLARE_TYPE(upb::BufferSource, upb_bufsrc)
UPB_DECLARE_TYPE(upb::BytesSink, upb_bytessink)
UPB_DECLARE_TYPE(upb::Sink, upb_sink)
/* upb_sink *******************************************************************/
UPB_BEGIN_EXTERN_C
typedef struct {
const upb_handlers *handlers;
void *closure;
} upb_sink;
#define PUTVAL(type, ctype) \
UPB_INLINE bool upb_sink_put##type(upb_sink *s, upb_selector_t sel, \
ctype val) { \
typedef upb_##type##_handlerfunc functype; \
functype *func; \
const void *hd; \
if (!s->handlers) return true; \
func = (functype *)upb_handlers_gethandler(s->handlers, sel, &hd); \
if (!func) return true; \
return func(s->closure, hd, val); \
}
PUTVAL(int32, int32_t)
PUTVAL(int64, int64_t)
PUTVAL(uint32, uint32_t)
PUTVAL(uint64, uint64_t)
PUTVAL(float, float)
PUTVAL(double, double)
PUTVAL(bool, bool)
#undef PUTVAL
UPB_INLINE void upb_sink_reset(upb_sink *s, const upb_handlers *h, void *c) {
s->handlers = h;
s->closure = c;
}
UPB_INLINE size_t upb_sink_putstring(upb_sink *s, upb_selector_t sel,
const char *buf, size_t n,
const upb_bufhandle *handle) {
typedef upb_string_handlerfunc func;
func *handler;
const void *hd;
if (!s->handlers) return n;
handler = (func *)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!handler) return n;
return handler(s->closure, hd, buf, n, handle);
}
UPB_INLINE bool upb_sink_putunknown(upb_sink *s, const char *buf, size_t n) {
typedef upb_unknown_handlerfunc func;
func *handler;
const void *hd;
if (!s->handlers) return true;
handler =
(func *)upb_handlers_gethandler(s->handlers, UPB_UNKNOWN_SELECTOR, &hd);
if (!handler) return n;
return handler(s->closure, hd, buf, n);
}
UPB_INLINE bool upb_sink_startmsg(upb_sink *s) {
typedef upb_startmsg_handlerfunc func;
func *startmsg;
const void *hd;
if (!s->handlers) return true;
startmsg =
(func *)upb_handlers_gethandler(s->handlers, UPB_STARTMSG_SELECTOR, &hd);
if (!startmsg) return true;
return startmsg(s->closure, hd);
}
UPB_INLINE bool upb_sink_endmsg(upb_sink *s, upb_status *status) {
typedef upb_endmsg_handlerfunc func;
func *endmsg;
const void *hd;
if (!s->handlers) return true;
endmsg =
(func *)upb_handlers_gethandler(s->handlers, UPB_ENDMSG_SELECTOR, &hd);
if (!endmsg) return true;
return endmsg(s->closure, hd, status);
}
UPB_INLINE bool upb_sink_startseq(upb_sink *s, upb_selector_t sel,
upb_sink *sub) {
typedef upb_startfield_handlerfunc func;
func *startseq;
const void *hd;
sub->closure = s->closure;
sub->handlers = s->handlers;
if (!s->handlers) return true;
startseq = (func*)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!startseq) return true;
sub->closure = startseq(s->closure, hd);
return sub->closure ? true : false;
}
UPB_INLINE bool upb_sink_endseq(upb_sink *s, upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endseq;
const void *hd;
if (!s->handlers) return true;
endseq = (func*)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!endseq) return true;
return endseq(s->closure, hd);
}
UPB_INLINE bool upb_sink_startstr(upb_sink *s, upb_selector_t sel,
size_t size_hint, upb_sink *sub) {
typedef upb_startstr_handlerfunc func;
func *startstr;
const void *hd;
sub->closure = s->closure;
sub->handlers = s->handlers;
if (!s->handlers) return true;
startstr = (func*)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!startstr) return true;
sub->closure = startstr(s->closure, hd, size_hint);
return sub->closure ? true : false;
}
UPB_INLINE bool upb_sink_endstr(upb_sink *s, upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endstr;
const void *hd;
if (!s->handlers) return true;
endstr = (func*)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!endstr) return true;
return endstr(s->closure, hd);
}
UPB_INLINE bool upb_sink_startsubmsg(upb_sink *s, upb_selector_t sel,
upb_sink *sub) {
typedef upb_startfield_handlerfunc func;
func *startsubmsg;
const void *hd;
sub->closure = s->closure;
if (!s->handlers) {
sub->handlers = NULL;
return true;
}
sub->handlers = upb_handlers_getsubhandlers_sel(s->handlers, sel);
startsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!startsubmsg) return true;
sub->closure = startsubmsg(s->closure, hd);
return sub->closure ? true : false;
}
UPB_INLINE bool upb_sink_endsubmsg(upb_sink *s, upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endsubmsg;
const void *hd;
if (!s->handlers) return true;
endsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel, &hd);
if (!endsubmsg) return s->closure;
return endsubmsg(s->closure, hd);
}
UPB_END_EXTERN_C
#ifdef __cplusplus
@ -81,16 +241,24 @@ class upb::Sink {
*
* TODO: once the Handlers know the expected closure type, verify that T
* matches it. */
template <class T> Sink(const Handlers* handlers, T* closure);
template <class T> Sink(const upb_handlers* handlers, T* closure) {
Reset(handlers, closure);
}
upb_sink* ptr() { return &sink_; }
/* Resets the value of the sink. */
template <class T> void Reset(const Handlers* handlers, T* closure);
template <class T> void Reset(const upb_handlers* handlers, T* closure) {
upb_sink_reset(&sink_, handlers, closure);
}
/* Returns the top-level object that is bound to this sink.
*
* TODO: once the Handlers know the expected closure type, verify that T
* matches it. */
template <class T> T* GetObject() const;
template <class T> T* GetObject() const {
return static_cast<T*>(sink_.closure);
}
/* Functions for pushing data into the sink.
*
@ -108,37 +276,57 @@ class upb::Sink {
* // ...
* sink->EndMessage(&status);
* sink->EndSubMessage(endsubmsg_selector); */
bool StartMessage();
bool EndMessage(Status* status);
bool StartMessage() { return upb_sink_startmsg(&sink_); }
bool EndMessage(Status* status) { return upb_sink_endmsg(&sink_, status); }
/* Putting of individual values. These work for both repeated and
* non-repeated fields, but for repeated fields you must wrap them in
* calls to StartSequence()/EndSequence(). */
bool PutInt32(Handlers::Selector s, int32_t val);
bool PutInt64(Handlers::Selector s, int64_t val);
bool PutUInt32(Handlers::Selector s, uint32_t val);
bool PutUInt64(Handlers::Selector s, uint64_t val);
bool PutFloat(Handlers::Selector s, float val);
bool PutDouble(Handlers::Selector s, double val);
bool PutBool(Handlers::Selector s, bool val);
bool PutInt32(HandlersPtr::Selector s, int32_t val) {
return upb_sink_putint32(&sink_, s, val);
}
bool PutInt64(HandlersPtr::Selector s, int64_t val) {
return upb_sink_putint64(&sink_, s, val);
}
bool PutUInt32(HandlersPtr::Selector s, uint32_t val) {
return upb_sink_putuint32(&sink_, s, val);
}
bool PutUInt64(HandlersPtr::Selector s, uint64_t val) {
return upb_sink_putuint64(&sink_, s, val);
}
bool PutFloat(HandlersPtr::Selector s, float val) {
return upb_sink_putfloat(&sink_, s, val);
}
bool PutDouble(HandlersPtr::Selector s, double val) {
return upb_sink_putdouble(&sink_, s, val);
}
bool PutBool(HandlersPtr::Selector s, bool val) {
return upb_sink_putbool(&sink_, s, val);
}
/* Putting of string/bytes values. Each string can consist of zero or more
* non-contiguous buffers of data.
*
* For StartString(), the function will write a sink for the string to "sub."
* The sub-sink must be used for any/all PutStringBuffer() calls. */
bool StartString(Handlers::Selector s, size_t size_hint, Sink* sub);
size_t PutStringBuffer(Handlers::Selector s, const char *buf, size_t len,
const BufferHandle *handle);
bool EndString(Handlers::Selector s);
bool StartString(HandlersPtr::Selector s, size_t size_hint, Sink* sub);
size_t PutStringBuffer(HandlersPtr::Selector s, const char *buf, size_t len,
const upb_bufhandle *handle);
bool EndString(HandlersPtr::Selector s);
/* For submessage fields.
*
* For StartSubMessage(), the function will write a sink for the string to
* "sub." The sub-sink must be used for any/all handlers called within the
* submessage. */
bool StartSubMessage(Handlers::Selector s, Sink* sub);
bool EndSubMessage(Handlers::Selector s);
bool StartSubMessage(HandlersPtr::Selector s, Sink* sub);
bool EndSubMessage(HandlersPtr::Selector s);
/* For repeated fields of any type, the sequence of values must be wrapped in
* these calls.
@ -146,84 +334,26 @@ class upb::Sink {
* For StartSequence(), the function will write a sink for the string to
* "sub." The sub-sink must be used for any/all handlers called within the
* sequence. */
bool StartSequence(Handlers::Selector s, Sink* sub);
bool EndSequence(Handlers::Selector s);
bool StartSequence(HandlersPtr::Selector s, Sink* sub);
bool EndSequence(HandlersPtr::Selector s);
/* Copy and assign specifically allowed.
* We don't even bother making these members private because so many
* functions need them and this is mainly just a dumb data container anyway.
*/
#else
struct upb_sink {
#endif
const upb_handlers *handlers;
void *closure;
};
#ifdef __cplusplus
class upb::BytesSink {
public:
BytesSink() {}
private:
upb_sink sink_;
};
/* Constructs a new sink for the given frozen handlers and closure.
*
* TODO(haberman): once the Handlers know the expected closure type, verify
* that T matches it. */
template <class T> BytesSink(const BytesHandler* handler, T* closure);
#endif /* __cplusplus */
/* Resets the value of the sink. */
template <class T> void Reset(const BytesHandler* handler, T* closure);
/* upb_bytessink **************************************************************/
bool Start(size_t size_hint, void **subc);
size_t PutBuffer(void *subc, const char *buf, size_t len,
const BufferHandle *handle);
bool End();
#else
struct upb_bytessink {
#endif
typedef struct {
const upb_byteshandler *handler;
void *closure;
};
#ifdef __cplusplus
/* A class for pushing a flat buffer of data to a BytesSink.
* You can construct an instance of this to get a resumable source,
* or just call the static PutBuffer() to do a non-resumable push all in one
* go. */
class upb::BufferSource {
public:
BufferSource();
BufferSource(const char* buf, size_t len, BytesSink* sink);
/* Returns true if the entire buffer was pushed successfully. Otherwise the
* next call to PutNext() will resume where the previous one left off.
* TODO(haberman): implement this. */
bool PutNext();
/* A static version; with this version is it not possible to resume in the
* case of failure or a partially-consumed buffer. */
static bool PutBuffer(const char* buf, size_t len, BytesSink* sink);
template <class T> static bool PutBuffer(const T& str, BytesSink* sink) {
return PutBuffer(str.c_str(), str.size(), sink);
}
#else
struct upb_bufsrc {
char dummy;
#endif
};
UPB_BEGIN_EXTERN_C
/* A class for accumulating output string data in a flat buffer. */
upb_bufsink *upb_bufsink_new(upb_env *env);
void upb_bufsink_free(upb_bufsink *sink);
upb_bytessink *upb_bufsink_sink(upb_bufsink *sink);
const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len);
/* Inline definitions. */
} upb_bytessink ;
UPB_INLINE void upb_bytessink_reset(upb_bytessink *s, const upb_byteshandler *h,
void *closure) {
@ -240,8 +370,8 @@ UPB_INLINE bool upb_bytessink_start(upb_bytessink *s, size_t size_hint,
start = (func *)s->handler->table[UPB_STARTSTR_SELECTOR].func;
if (!start) return true;
*subc = start(s->closure, upb_handlerattr_handlerdata(
&s->handler->table[UPB_STARTSTR_SELECTOR].attr),
*subc = start(s->closure,
s->handler->table[UPB_STARTSTR_SELECTOR].attr.handler_data,
size_hint);
return *subc != NULL;
}
@ -255,8 +385,7 @@ UPB_INLINE size_t upb_bytessink_putbuf(upb_bytessink *s, void *subc,
putbuf = (func *)s->handler->table[UPB_STRING_SELECTOR].func;
if (!putbuf) return true;
return putbuf(subc, upb_handlerattr_handlerdata(
&s->handler->table[UPB_STRING_SELECTOR].attr),
return putbuf(subc, s->handler->table[UPB_STRING_SELECTOR].attr.handler_data,
buf, size, handle);
}
@ -268,266 +397,80 @@ UPB_INLINE bool upb_bytessink_end(upb_bytessink *s) {
if (!end) return true;
return end(s->closure,
upb_handlerattr_handlerdata(
&s->handler->table[UPB_ENDSTR_SELECTOR].attr));
}
bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink);
#define PUTVAL(type, ctype) \
UPB_INLINE bool upb_sink_put##type(upb_sink *s, upb_selector_t sel, \
ctype val) { \
typedef upb_##type##_handlerfunc functype; \
functype *func; \
const void *hd; \
if (!s->handlers) return true; \
func = (functype *)upb_handlers_gethandler(s->handlers, sel); \
if (!func) return true; \
hd = upb_handlers_gethandlerdata(s->handlers, sel); \
return func(s->closure, hd, val); \
}
PUTVAL(int32, int32_t)
PUTVAL(int64, int64_t)
PUTVAL(uint32, uint32_t)
PUTVAL(uint64, uint64_t)
PUTVAL(float, float)
PUTVAL(double, double)
PUTVAL(bool, bool)
#undef PUTVAL
UPB_INLINE void upb_sink_reset(upb_sink *s, const upb_handlers *h, void *c) {
s->handlers = h;
s->closure = c;
}
UPB_INLINE size_t upb_sink_putstring(upb_sink *s, upb_selector_t sel,
const char *buf, size_t n,
const upb_bufhandle *handle) {
typedef upb_string_handlerfunc func;
func *handler;
const void *hd;
if (!s->handlers) return n;
handler = (func *)upb_handlers_gethandler(s->handlers, sel);
if (!handler) return n;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
return handler(s->closure, hd, buf, n, handle);
}
UPB_INLINE bool upb_sink_putunknown(upb_sink *s, const char *buf, size_t n) {
typedef upb_unknown_handlerfunc func;
func *handler;
const void *hd;
if (!s->handlers) return true;
handler = (func *)upb_handlers_gethandler(s->handlers, UPB_UNKNOWN_SELECTOR);
if (!handler) return n;
hd = upb_handlers_gethandlerdata(s->handlers, UPB_UNKNOWN_SELECTOR);
return handler(s->closure, hd, buf, n);
}
UPB_INLINE bool upb_sink_startmsg(upb_sink *s) {
typedef upb_startmsg_handlerfunc func;
func *startmsg;
const void *hd;
if (!s->handlers) return true;
startmsg = (func*)upb_handlers_gethandler(s->handlers, UPB_STARTMSG_SELECTOR);
if (!startmsg) return true;
hd = upb_handlers_gethandlerdata(s->handlers, UPB_STARTMSG_SELECTOR);
return startmsg(s->closure, hd);
s->handler->table[UPB_ENDSTR_SELECTOR].attr.handler_data);
}
UPB_INLINE bool upb_sink_endmsg(upb_sink *s, upb_status *status) {
typedef upb_endmsg_handlerfunc func;
func *endmsg;
const void *hd;
if (!s->handlers) return true;
endmsg = (func *)upb_handlers_gethandler(s->handlers, UPB_ENDMSG_SELECTOR);
if (!endmsg) return true;
hd = upb_handlers_gethandlerdata(s->handlers, UPB_ENDMSG_SELECTOR);
return endmsg(s->closure, hd, status);
}
#ifdef __cplusplus
UPB_INLINE bool upb_sink_startseq(upb_sink *s, upb_selector_t sel,
upb_sink *sub) {
typedef upb_startfield_handlerfunc func;
func *startseq;
const void *hd;
sub->closure = s->closure;
sub->handlers = s->handlers;
if (!s->handlers) return true;
startseq = (func*)upb_handlers_gethandler(s->handlers, sel);
class upb::BytesSink {
public:
BytesSink() {}
if (!startseq) return true;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
sub->closure = startseq(s->closure, hd);
return sub->closure ? true : false;
}
upb_bytessink* ptr() { return &sink_; }
UPB_INLINE bool upb_sink_endseq(upb_sink *s, upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endseq;
const void *hd;
if (!s->handlers) return true;
endseq = (func*)upb_handlers_gethandler(s->handlers, sel);
/* Constructs a new sink for the given frozen handlers and closure.
*
* TODO(haberman): once the Handlers know the expected closure type, verify
* that T matches it. */
template <class T> BytesSink(const upb_byteshandler* handler, T* closure) {
upb_bytessink_reset(&sink_, handler, closure);
}
if (!endseq) return true;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
return endseq(s->closure, hd);
}
/* Resets the value of the sink. */
template <class T> void Reset(const upb_byteshandler* handler, T* closure) {
upb_bytessink_reset(&sink_, handler, closure);
}
UPB_INLINE bool upb_sink_startstr(upb_sink *s, upb_selector_t sel,
size_t size_hint, upb_sink *sub) {
typedef upb_startstr_handlerfunc func;
func *startstr;
const void *hd;
sub->closure = s->closure;
sub->handlers = s->handlers;
if (!s->handlers) return true;
startstr = (func*)upb_handlers_gethandler(s->handlers, sel);
bool Start(size_t size_hint, void **subc) {
return upb_bytessink_start(&sink_, size_hint, subc);
}
if (!startstr) return true;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
sub->closure = startstr(s->closure, hd, size_hint);
return sub->closure ? true : false;
}
size_t PutBuffer(void *subc, const char *buf, size_t len,
const upb_bufhandle *handle) {
return upb_bytessink_putbuf(&sink_, subc, buf, len, handle);
}
UPB_INLINE bool upb_sink_endstr(upb_sink *s, upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endstr;
const void *hd;
if (!s->handlers) return true;
endstr = (func*)upb_handlers_gethandler(s->handlers, sel);
bool End() {
return upb_bytessink_end(&sink_);
}
if (!endstr) return true;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
return endstr(s->closure, hd);
}
private:
upb_bytessink sink_;
};
UPB_INLINE bool upb_sink_startsubmsg(upb_sink *s, upb_selector_t sel,
upb_sink *sub) {
typedef upb_startfield_handlerfunc func;
func *startsubmsg;
const void *hd;
sub->closure = s->closure;
if (!s->handlers) {
sub->handlers = NULL;
return true;
}
sub->handlers = upb_handlers_getsubhandlers_sel(s->handlers, sel);
startsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel);
#endif /* __cplusplus */
if (!startsubmsg) return true;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
sub->closure = startsubmsg(s->closure, hd);
return sub->closure ? true : false;
}
/* upb_bufsrc *****************************************************************/
UPB_INLINE bool upb_sink_endsubmsg(upb_sink *s, upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endsubmsg;
const void *hd;
if (!s->handlers) return true;
endsubmsg = (func*)upb_handlers_gethandler(s->handlers, sel);
UPB_BEGIN_EXTERN_C
if (!endsubmsg) return s->closure;
hd = upb_handlers_gethandlerdata(s->handlers, sel);
return endsubmsg(s->closure, hd);
}
bool upb_bufsrc_putbuf(const char *buf, size_t len, upb_bytessink *sink);
UPB_END_EXTERN_C
#ifdef __cplusplus
namespace upb {
template <class T> Sink::Sink(const Handlers* handlers, T* closure) {
upb_sink_reset(this, handlers, closure);
}
template <class T>
inline void Sink::Reset(const Handlers* handlers, T* closure) {
upb_sink_reset(this, handlers, closure);
}
inline bool Sink::StartMessage() {
return upb_sink_startmsg(this);
}
inline bool Sink::EndMessage(Status* status) {
return upb_sink_endmsg(this, status);
}
inline bool Sink::PutInt32(Handlers::Selector sel, int32_t val) {
return upb_sink_putint32(this, sel, val);
}
inline bool Sink::PutInt64(Handlers::Selector sel, int64_t val) {
return upb_sink_putint64(this, sel, val);
}
inline bool Sink::PutUInt32(Handlers::Selector sel, uint32_t val) {
return upb_sink_putuint32(this, sel, val);
}
inline bool Sink::PutUInt64(Handlers::Selector sel, uint64_t val) {
return upb_sink_putuint64(this, sel, val);
template <class T> bool PutBuffer(const T& str, upb_bytessink* sink) {
return upb_bufsrc_putbuf(str.c_str(), str.size(), sink);
}
inline bool Sink::PutFloat(Handlers::Selector sel, float val) {
return upb_sink_putfloat(this, sel, val);
}
inline bool Sink::PutDouble(Handlers::Selector sel, double val) {
return upb_sink_putdouble(this, sel, val);
}
inline bool Sink::PutBool(Handlers::Selector sel, bool val) {
return upb_sink_putbool(this, sel, val);
}
inline bool Sink::StartString(Handlers::Selector sel, size_t size_hint,
Sink *sub) {
return upb_sink_startstr(this, sel, size_hint, sub);
}
inline size_t Sink::PutStringBuffer(Handlers::Selector sel, const char *buf,
size_t len, const BufferHandle* handle) {
return upb_sink_putstring(this, sel, buf, len, handle);
}
inline bool Sink::EndString(Handlers::Selector sel) {
return upb_sink_endstr(this, sel);
}
inline bool Sink::StartSubMessage(Handlers::Selector sel, Sink* sub) {
return upb_sink_startsubmsg(this, sel, sub);
}
inline bool Sink::EndSubMessage(Handlers::Selector sel) {
return upb_sink_endsubmsg(this, sel);
}
inline bool Sink::StartSequence(Handlers::Selector sel, Sink* sub) {
return upb_sink_startseq(this, sel, sub);
}
inline bool Sink::EndSequence(Handlers::Selector sel) {
return upb_sink_endseq(this, sel);
}
template <class T>
BytesSink::BytesSink(const BytesHandler* handler, T* closure) {
Reset(handler, closure);
}
#endif /* __cplusplus */
template <class T>
void BytesSink::Reset(const BytesHandler *handler, T *closure) {
upb_bytessink_reset(this, handler, closure);
}
inline bool BytesSink::Start(size_t size_hint, void **subc) {
return upb_bytessink_start(this, size_hint, subc);
}
inline size_t BytesSink::PutBuffer(void *subc, const char *buf, size_t len,
const BufferHandle *handle) {
return upb_bytessink_putbuf(this, subc, buf, len, handle);
}
inline bool BytesSink::End() {
return upb_bytessink_end(this);
}
/* upb_bufsink ****************************************************************/
inline bool BufferSource::PutBuffer(const char *buf, size_t len,
BytesSink *sink) {
return upb_bufsrc_putbuf(buf, len, sink);
}
/* A class for accumulating output string data in a flat buffer. */
struct upb_bufsink;
typedef struct upb_bufsink upb_bufsink;
} /* namespace upb */
#endif
UPB_BEGIN_EXTERN_C
upb_bufsink *upb_bufsink_init(upb_env *env);
void upb_bufsink_free(upb_bufsink *sink);
upb_bytessink *upb_bufsink_sink(upb_bufsink *sink);
const char *upb_bufsink_getdata(const upb_bufsink *sink, size_t *len);
UPB_END_EXTERN_C
#endif

@ -74,7 +74,6 @@ template <int N> class InlinedEnvironment;
#error Need implementations of [v]snprintf and va_copy
#endif
#if ((defined(__cplusplus) && __cplusplus >= 201103L) || \
defined(__GXX_EXPERIMENTAL_CXX0X__)) && !defined(UPB_NO_CXX11)
#define UPB_CXX11
@ -110,28 +109,6 @@ template <int N> class InlinedEnvironment;
#define UPB_FINAL
#endif
/* UPB_DECLARE_TYPE()
* UPB_DECLARE_DERIVED_TYPE()
* UPB_DECLARE_DERIVED_TYPE2()
*
* Macros for declaring C and C++ types both, including inheritance.
* The inheritance doesn't use real C++ inheritance, to stay compatible with C.
*
* These macros also provide upcasts:
* - in C: types-specific functions (ie. upb_foo_upcast(foo))
* - in C++: upb::upcast(foo) along with implicit conversions
*
* Downcasts are not provided, but upb/def.h defines downcasts for upb::Def. */
#define UPB_C_UPCASTS(ty, base) \
UPB_INLINE base *ty ## _upcast_mutable(ty *p) { return (base*)p; } \
UPB_INLINE const base *ty ## _upcast(const ty *p) { return (const base*)p; }
#define UPB_C_UPCASTS2(ty, base, base2) \
UPB_C_UPCASTS(ty, base) \
UPB_INLINE base2 *ty ## _upcast2_mutable(ty *p) { return (base2*)p; } \
UPB_INLINE const base2 *ty ## _upcast2(const ty *p) { return (const base2*)p; }
#ifdef __cplusplus
#define UPB_BEGIN_EXTERN_C extern "C" {
@ -139,45 +116,6 @@ template <int N> class InlinedEnvironment;
#define UPB_PRIVATE_FOR_CPP private:
#define UPB_DECLARE_TYPE(cppname, cname) typedef cppname cname;
#define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \
UPB_DECLARE_TYPE(cppname, cname) \
UPB_C_UPCASTS(cname, cbase) \
namespace upb { \
template <> \
class Pointer<cppname> : public PointerBase<cppname, cppbase> { \
public: \
explicit Pointer(cppname* ptr) \
: PointerBase<cppname, cppbase>(ptr) {} \
}; \
template <> \
class Pointer<const cppname> \
: public PointerBase<const cppname, const cppbase> { \
public: \
explicit Pointer(const cppname* ptr) \
: PointerBase<const cppname, const cppbase>(ptr) {} \
}; \
}
#define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, cname, cbase, \
cbase2) \
UPB_DECLARE_TYPE(cppname, cname) \
UPB_C_UPCASTS2(cname, cbase, cbase2) \
namespace upb { \
template <> \
class Pointer<cppname> : public PointerBase2<cppname, cppbase, cppbase2> { \
public: \
explicit Pointer(cppname* ptr) \
: PointerBase2<cppname, cppbase, cppbase2>(ptr) {} \
}; \
template <> \
class Pointer<const cppname> \
: public PointerBase2<const cppname, const cppbase, const cppbase2> { \
public: \
explicit Pointer(const cppname* ptr) \
: PointerBase2<const cppname, const cppbase, const cppbase2>(ptr) {} \
}; \
}
#else /* !defined(__cplusplus) */
#define UPB_BEGIN_EXTERN_C
@ -186,13 +124,6 @@ template <int N> class InlinedEnvironment;
#define UPB_DECLARE_TYPE(cppname, cname) \
struct cname; \
typedef struct cname cname;
#define UPB_DECLARE_DERIVED_TYPE(cppname, cppbase, cname, cbase) \
UPB_DECLARE_TYPE(cppname, cname) \
UPB_C_UPCASTS(cname, cbase)
#define UPB_DECLARE_DERIVED_TYPE2(cppname, cppbase, cppbase2, \
cname, cbase, cbase2) \
UPB_DECLARE_TYPE(cppname, cname) \
UPB_C_UPCASTS2(cname, cbase, cbase2)
#endif /* defined(__cplusplus) */

Loading…
Cancel
Save