summaryrefslogtreecommitdiff
path: root/upb/bindings/stdc++/string.h
blob: 99efd4f31590a0958ed04e870da5a43eeda14def (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

#ifndef UPB_STDCPP_H_
#define UPB_STDCPP_H_

#include "upb/sink.h"

namespace upb {

template <class T>
class FillStringHandler {
 public:
  static void SetHandler(BytesHandler* handler) {
    upb_byteshandler_setstartstr(handler, &FillStringHandler::StartString,
                                 NULL);
    upb_byteshandler_setstring(handler, &FillStringHandler::StringBuf, NULL);
  }

 private:
  // TODO(haberman): add UpbBind/UpbMakeHandler support to BytesHandler so these
  // can be prettier callbacks.
  static void* StartString(void *c, const void *hd, size_t size) {
    UPB_UNUSED(hd);
    UPB_UNUSED(size);

    T* str = static_cast<T*>(c);
    str->clear();
    return c;
  }

  static size_t StringBuf(void* c, const void* hd, const char* buf, size_t n,
                          const BufferHandle* h) {
    UPB_UNUSED(hd);
    UPB_UNUSED(h);

    T* str = static_cast<T*>(c);
    try {
      str->append(buf, n);
      return n;
    } catch (const std::exception&) {
      return 0;
    }
  }
};

class StringSink {
 public:
  template <class T>
  explicit StringSink(T* target) {
    // TODO(haberman): we need to avoid rebuilding a new handler every time,
    // but with class globals disallowed for google3 C++ this is tricky.
    FillStringHandler<T>::SetHandler(&handler_);
    input_.Reset(&handler_, target);
  }

  BytesSink* input() { return &input_; }

 private:
  BytesHandler handler_;
  BytesSink input_;
};

}  // namespace upb

#endif  // UPB_STDCPP_H_
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback