google-protobuf 3.7.0 → 3.17.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of google-protobuf might be problematic. Click here for more details.

Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/ext/google/protobuf_c/convert.c +349 -0
  3. data/ext/google/protobuf_c/convert.h +72 -0
  4. data/ext/google/protobuf_c/defs.c +1555 -1228
  5. data/ext/google/protobuf_c/defs.h +107 -0
  6. data/ext/google/protobuf_c/extconf.rb +5 -7
  7. data/ext/google/protobuf_c/map.c +310 -470
  8. data/ext/google/protobuf_c/map.h +66 -0
  9. data/ext/google/protobuf_c/message.c +934 -346
  10. data/ext/google/protobuf_c/message.h +101 -0
  11. data/ext/google/protobuf_c/protobuf.c +390 -51
  12. data/ext/google/protobuf_c/protobuf.h +44 -544
  13. data/ext/google/protobuf_c/repeated_field.c +311 -308
  14. data/ext/google/protobuf_c/repeated_field.h +62 -0
  15. data/ext/google/protobuf_c/ruby-upb.c +8914 -0
  16. data/ext/google/protobuf_c/ruby-upb.h +4452 -0
  17. data/ext/google/protobuf_c/third_party/wyhash/wyhash.h +145 -0
  18. data/lib/google/protobuf/any_pb.rb +1 -1
  19. data/lib/google/protobuf/api_pb.rb +3 -3
  20. data/lib/google/protobuf/duration_pb.rb +1 -1
  21. data/lib/google/protobuf/empty_pb.rb +1 -1
  22. data/lib/google/protobuf/field_mask_pb.rb +1 -1
  23. data/lib/google/protobuf/source_context_pb.rb +1 -1
  24. data/lib/google/protobuf/struct_pb.rb +4 -4
  25. data/lib/google/protobuf/timestamp_pb.rb +1 -1
  26. data/lib/google/protobuf/type_pb.rb +8 -8
  27. data/lib/google/protobuf/well_known_types.rb +8 -2
  28. data/lib/google/protobuf/wrappers_pb.rb +9 -9
  29. data/lib/google/protobuf.rb +70 -0
  30. data/tests/basic.rb +315 -72
  31. data/tests/generated_code_test.rb +0 -0
  32. data/tests/stress.rb +0 -0
  33. metadata +27 -16
  34. data/ext/google/protobuf_c/encode_decode.c +0 -1574
  35. data/ext/google/protobuf_c/storage.c +0 -1019
  36. data/ext/google/protobuf_c/upb.c +0 -17318
  37. data/ext/google/protobuf_c/upb.h +0 -9755
@@ -0,0 +1,101 @@
1
+ // Protocol Buffers - Google's data interchange format
2
+ // Copyright 2008 Google Inc. All rights reserved.
3
+ // https://developers.google.com/protocol-buffers/
4
+ //
5
+ // Redistribution and use in source and binary forms, with or without
6
+ // modification, are permitted provided that the following conditions are
7
+ // met:
8
+ //
9
+ // * Redistributions of source code must retain the above copyright
10
+ // notice, this list of conditions and the following disclaimer.
11
+ // * Redistributions in binary form must reproduce the above
12
+ // copyright notice, this list of conditions and the following disclaimer
13
+ // in the documentation and/or other materials provided with the
14
+ // distribution.
15
+ // * Neither the name of Google Inc. nor the names of its
16
+ // contributors may be used to endorse or promote products derived from
17
+ // this software without specific prior written permission.
18
+ //
19
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ #ifndef RUBY_PROTOBUF_MESSAGE_H_
32
+ #define RUBY_PROTOBUF_MESSAGE_H_
33
+
34
+ #include <ruby/ruby.h>
35
+
36
+ #include "protobuf.h"
37
+ #include "ruby-upb.h"
38
+
39
+ // Gets the underlying upb_msg* and upb_msgdef for the given Ruby message
40
+ // wrapper. Requires that |value| is indeed a message object.
41
+ const upb_msg *Message_Get(VALUE value, const upb_msgdef **m);
42
+
43
+ // Like Message_Get(), but checks that the object is not frozen and returns a
44
+ // mutable pointer.
45
+ upb_msg *Message_GetMutable(VALUE value, const upb_msgdef **m);
46
+
47
+ // Returns the Arena object for this message.
48
+ VALUE Message_GetArena(VALUE value);
49
+
50
+ // Converts |value| into a upb_msg value of the expected upb_msgdef type,
51
+ // raising an error if this is not possible. Used when assigning |value| to a
52
+ // field of another message, which means the message must be of a particular
53
+ // type.
54
+ //
55
+ // This will perform automatic conversions in some cases (for example, Time ->
56
+ // Google::Protobuf::Timestamp). If any new message is created, it will be
57
+ // created on |arena|, and any existing message will have its arena fused with
58
+ // |arena|.
59
+ const upb_msg* Message_GetUpbMessage(VALUE value, const upb_msgdef* m,
60
+ const char* name, upb_arena* arena);
61
+
62
+ // Gets or constructs a Ruby wrapper object for the given message. The wrapper
63
+ // object will reference |arena| and ensure that it outlives this object.
64
+ VALUE Message_GetRubyWrapper(upb_msg* msg, const upb_msgdef* m, VALUE arena);
65
+
66
+ // Gets the given field from this message.
67
+ VALUE Message_getfield(VALUE _self, const upb_fielddef* f);
68
+
69
+ // Implements #inspect for this message, printing the text to |b|.
70
+ void Message_PrintMessage(StringBuilder* b, const upb_msg* msg,
71
+ const upb_msgdef* m);
72
+
73
+ // Returns a hash value for the given message.
74
+ uint64_t Message_Hash(const upb_msg *msg, const upb_msgdef *m, uint64_t seed);
75
+
76
+ // Returns a deep copy of the given message.
77
+ upb_msg* Message_deep_copy(const upb_msg* msg, const upb_msgdef* m,
78
+ upb_arena *arena);
79
+
80
+ // Returns true if these two messages are equal.
81
+ bool Message_Equal(const upb_msg *m1, const upb_msg *m2, const upb_msgdef *m);
82
+
83
+ // Checks that this Ruby object is a message, and raises an exception if not.
84
+ void Message_CheckClass(VALUE klass);
85
+
86
+ // Returns a new Hash object containing the contents of this message.
87
+ VALUE Scalar_CreateHash(upb_msgval val, TypeInfo type_info);
88
+
89
+ // Creates a message class or enum module for this descriptor, respectively.
90
+ VALUE build_class_from_descriptor(VALUE descriptor);
91
+ VALUE build_module_from_enumdesc(VALUE _enumdesc);
92
+
93
+ // Returns the Descriptor/EnumDescriptor for the given message class or enum
94
+ // module, respectively. Returns nil if this is not a message class or enum
95
+ // module.
96
+ VALUE MessageOrEnum_GetDescriptor(VALUE klass);
97
+
98
+ // Call at startup to register all types in this module.
99
+ void Message_register(VALUE protobuf);
100
+
101
+ #endif // RUBY_PROTOBUF_MESSAGE_H_
@@ -30,52 +30,404 @@
30
30
 
31
31
  #include "protobuf.h"
32
32
 
33
- // -----------------------------------------------------------------------------
34
- // Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
35
- // instances.
36
- // -----------------------------------------------------------------------------
33
+ #include <ruby/version.h>
37
34
 
38
- // This is a hash table from def objects (encoded by converting pointers to
39
- // Ruby integers) to MessageDef/EnumDef instances (as Ruby values).
40
- VALUE upb_def_to_ruby_obj_map;
35
+ #include "defs.h"
36
+ #include "map.h"
37
+ #include "message.h"
38
+ #include "repeated_field.h"
41
39
 
42
- VALUE cError;
43
40
  VALUE cParseError;
44
41
  VALUE cTypeError;
45
42
 
46
- void add_def_obj(const void* def, VALUE value) {
47
- rb_hash_aset(upb_def_to_ruby_obj_map, ULL2NUM((intptr_t)def), value);
43
+ const upb_fielddef* map_field_key(const upb_fielddef* field) {
44
+ const upb_msgdef *entry = upb_fielddef_msgsubdef(field);
45
+ return upb_msgdef_itof(entry, 1);
46
+ }
47
+
48
+ const upb_fielddef* map_field_value(const upb_fielddef* field) {
49
+ const upb_msgdef *entry = upb_fielddef_msgsubdef(field);
50
+ return upb_msgdef_itof(entry, 2);
51
+ }
52
+
53
+ // -----------------------------------------------------------------------------
54
+ // StringBuilder, for inspect
55
+ // -----------------------------------------------------------------------------
56
+
57
+ struct StringBuilder {
58
+ size_t size;
59
+ size_t cap;
60
+ char *data;
61
+ };
62
+
63
+ typedef struct StringBuilder StringBuilder;
64
+
65
+ static size_t StringBuilder_SizeOf(size_t cap) {
66
+ return sizeof(StringBuilder) + cap;
67
+ }
68
+
69
+ StringBuilder* StringBuilder_New() {
70
+ const size_t cap = 128;
71
+ StringBuilder* builder = malloc(sizeof(*builder));
72
+ builder->size = 0;
73
+ builder->cap = cap;
74
+ builder->data = malloc(builder->cap);
75
+ return builder;
76
+ }
77
+
78
+ void StringBuilder_Free(StringBuilder* b) {
79
+ free(b->data);
80
+ free(b);
81
+ }
82
+
83
+ void StringBuilder_Printf(StringBuilder* b, const char *fmt, ...) {
84
+ size_t have = b->cap - b->size;
85
+ size_t n;
86
+ va_list args;
87
+
88
+ va_start(args, fmt);
89
+ n = vsnprintf(&b->data[b->size], have, fmt, args);
90
+ va_end(args);
91
+
92
+ if (have <= n) {
93
+ while (have <= n) {
94
+ b->cap *= 2;
95
+ have = b->cap - b->size;
96
+ }
97
+ b->data = realloc(b->data, StringBuilder_SizeOf(b->cap));
98
+ va_start(args, fmt);
99
+ n = vsnprintf(&b->data[b->size], have, fmt, args);
100
+ va_end(args);
101
+ PBRUBY_ASSERT(n < have);
102
+ }
103
+
104
+ b->size += n;
48
105
  }
49
106
 
50
- VALUE get_def_obj(const void* def) {
51
- return rb_hash_aref(upb_def_to_ruby_obj_map, ULL2NUM((intptr_t)def));
107
+ VALUE StringBuilder_ToRubyString(StringBuilder* b) {
108
+ VALUE ret = rb_str_new(b->data, b->size);
109
+ rb_enc_associate(ret, rb_utf8_encoding());
110
+ return ret;
111
+ }
112
+
113
+ static void StringBuilder_PrintEnum(StringBuilder* b, int32_t val,
114
+ const upb_enumdef* e) {
115
+ const char *name = upb_enumdef_iton(e, val);
116
+ if (name) {
117
+ StringBuilder_Printf(b, ":%s", name);
118
+ } else {
119
+ StringBuilder_Printf(b, "%" PRId32, val);
120
+ }
121
+ }
122
+
123
+ void StringBuilder_PrintMsgval(StringBuilder* b, upb_msgval val,
124
+ TypeInfo info) {
125
+ switch (info.type) {
126
+ case UPB_TYPE_BOOL:
127
+ StringBuilder_Printf(b, "%s", val.bool_val ? "true" : "false");
128
+ break;
129
+ case UPB_TYPE_FLOAT: {
130
+ VALUE str = rb_inspect(DBL2NUM(val.float_val));
131
+ StringBuilder_Printf(b, "%s", RSTRING_PTR(str));
132
+ break;
133
+ }
134
+ case UPB_TYPE_DOUBLE: {
135
+ VALUE str = rb_inspect(DBL2NUM(val.double_val));
136
+ StringBuilder_Printf(b, "%s", RSTRING_PTR(str));
137
+ break;
138
+ }
139
+ case UPB_TYPE_INT32:
140
+ StringBuilder_Printf(b, "%" PRId32, val.int32_val);
141
+ break;
142
+ case UPB_TYPE_UINT32:
143
+ StringBuilder_Printf(b, "%" PRIu32, val.uint32_val);
144
+ break;
145
+ case UPB_TYPE_INT64:
146
+ StringBuilder_Printf(b, "%" PRId64, val.int64_val);
147
+ break;
148
+ case UPB_TYPE_UINT64:
149
+ StringBuilder_Printf(b, "%" PRIu64, val.uint64_val);
150
+ break;
151
+ case UPB_TYPE_STRING:
152
+ StringBuilder_Printf(b, "\"%.*s\"", (int)val.str_val.size, val.str_val.data);
153
+ break;
154
+ case UPB_TYPE_BYTES:
155
+ StringBuilder_Printf(b, "\"%.*s\"", (int)val.str_val.size, val.str_val.data);
156
+ break;
157
+ case UPB_TYPE_ENUM:
158
+ StringBuilder_PrintEnum(b, val.int32_val, info.def.enumdef);
159
+ break;
160
+ case UPB_TYPE_MESSAGE:
161
+ Message_PrintMessage(b, val.msg_val, info.def.msgdef);
162
+ break;
163
+ }
52
164
  }
53
165
 
54
166
  // -----------------------------------------------------------------------------
55
- // Utilities.
167
+ // Arena
56
168
  // -----------------------------------------------------------------------------
57
169
 
58
- // Raises a Ruby error if |status| is not OK, using its error message.
59
- void check_upb_status(const upb_status* status, const char* msg) {
60
- if (!upb_ok(status)) {
61
- rb_raise(rb_eRuntimeError, "%s: %s\n", msg, upb_status_errmsg(status));
170
+ typedef struct {
171
+ upb_arena *arena;
172
+ VALUE pinned_objs;
173
+ } Arena;
174
+
175
+ static void Arena_mark(void *data) {
176
+ Arena *arena = data;
177
+ rb_gc_mark(arena->pinned_objs);
178
+ }
179
+
180
+ static void Arena_free(void *data) {
181
+ Arena *arena = data;
182
+ upb_arena_free(arena->arena);
183
+ xfree(arena);
184
+ }
185
+
186
+ static VALUE cArena;
187
+
188
+ const rb_data_type_t Arena_type = {
189
+ "Google::Protobuf::Internal::Arena",
190
+ { Arena_mark, Arena_free, NULL },
191
+ .flags = RUBY_TYPED_FREE_IMMEDIATELY,
192
+ };
193
+
194
+ static VALUE Arena_alloc(VALUE klass) {
195
+ Arena *arena = ALLOC(Arena);
196
+ arena->arena = upb_arena_new();
197
+ arena->pinned_objs = Qnil;
198
+ return TypedData_Wrap_Struct(klass, &Arena_type, arena);
199
+ }
200
+
201
+ upb_arena *Arena_get(VALUE _arena) {
202
+ Arena *arena;
203
+ TypedData_Get_Struct(_arena, Arena, &Arena_type, arena);
204
+ return arena->arena;
205
+ }
206
+
207
+ VALUE Arena_new() {
208
+ return Arena_alloc(cArena);
209
+ }
210
+
211
+ void Arena_Pin(VALUE _arena, VALUE obj) {
212
+ Arena *arena;
213
+ TypedData_Get_Struct(_arena, Arena, &Arena_type, arena);
214
+ if (arena->pinned_objs == Qnil) {
215
+ arena->pinned_objs = rb_ary_new();
62
216
  }
217
+ rb_ary_push(arena->pinned_objs, obj);
218
+ }
219
+
220
+ void Arena_register(VALUE module) {
221
+ VALUE internal = rb_define_module_under(module, "Internal");
222
+ VALUE klass = rb_define_class_under(internal, "Arena", rb_cObject);
223
+ rb_define_alloc_func(klass, Arena_alloc);
224
+ rb_gc_register_address(&cArena);
225
+ cArena = klass;
63
226
  }
64
227
 
65
- // String encodings: we look these up once, at load time, and then cache them
66
- // here.
67
- rb_encoding* kRubyStringUtf8Encoding;
68
- rb_encoding* kRubyStringASCIIEncoding;
69
- rb_encoding* kRubyString8bitEncoding;
228
+ // -----------------------------------------------------------------------------
229
+ // Object Cache
230
+ // -----------------------------------------------------------------------------
70
231
 
71
- // Ruby-interned string: "descriptor". We use this identifier to store an
72
- // instance variable on message classes we create in order to link them back to
73
- // their descriptors.
232
+ // A pointer -> Ruby Object cache that keeps references to Ruby wrapper
233
+ // objects. This allows us to look up any Ruby wrapper object by the address
234
+ // of the object it is wrapping. That way we can avoid ever creating two
235
+ // different wrapper objects for the same C object, which saves memory and
236
+ // preserves object identity.
237
+ //
238
+ // We use WeakMap for the cache. For Ruby <2.7 we also need a secondary Hash
239
+ // to store WeakMap keys because Ruby <2.7 WeakMap doesn't allow non-finalizable
240
+ // keys.
74
241
  //
75
- // We intern this once at module load time then use the interned identifier at
76
- // runtime in order to avoid the cost of repeatedly interning in hot paths.
77
- const char* kDescriptorInstanceVar = "descriptor";
78
- ID descriptor_instancevar_interned;
242
+ // We also need the secondary Hash if sizeof(long) < sizeof(VALUE), because this
243
+ // means it may not be possible to fit a pointer into a Fixnum. Keys are
244
+ // pointers, and if they fit into a Fixnum, Ruby doesn't collect them, but if
245
+ // they overflow and require allocating a Bignum, they could get collected
246
+ // prematurely, thus removing the cache entry. This happens on 64-bit Windows,
247
+ // on which pointers are 64 bits but longs are 32 bits. In this case, we enable
248
+ // the secondary Hash to hold the keys and prevent them from being collected.
249
+
250
+ #if RUBY_API_VERSION_CODE >= 20700 && SIZEOF_LONG >= SIZEOF_VALUE
251
+ #define USE_SECONDARY_MAP 0
252
+ #else
253
+ #define USE_SECONDARY_MAP 1
254
+ #endif
255
+
256
+ #if USE_SECONDARY_MAP
257
+
258
+ // Maps Numeric -> Object. The object is then used as a key into the WeakMap.
259
+ // This is needed for Ruby <2.7 where a number cannot be a key to WeakMap.
260
+ // The object is used only for its identity; it does not contain any data.
261
+ VALUE secondary_map = Qnil;
262
+
263
+ // Mutations to the map are under a mutex, because SeconaryMap_MaybeGC()
264
+ // iterates over the map which cannot happen in parallel with insertions, or
265
+ // Ruby will throw:
266
+ // can't add a new key into hash during iteration (RuntimeError)
267
+ VALUE secondary_map_mutex = Qnil;
268
+
269
+ // Lambda that will GC entries from the secondary map that are no longer present
270
+ // in the primary map.
271
+ VALUE gc_secondary_map_lambda = Qnil;
272
+ ID length;
273
+
274
+ extern VALUE weak_obj_cache;
275
+
276
+ static void SecondaryMap_Init() {
277
+ rb_gc_register_address(&secondary_map);
278
+ rb_gc_register_address(&gc_secondary_map_lambda);
279
+ rb_gc_register_address(&secondary_map_mutex);
280
+ secondary_map = rb_hash_new();
281
+ gc_secondary_map_lambda = rb_eval_string(
282
+ "->(secondary, weak) {\n"
283
+ " secondary.delete_if { |k, v| !weak.key?(v) }\n"
284
+ "}\n");
285
+ secondary_map_mutex = rb_mutex_new();
286
+ length = rb_intern("length");
287
+ }
288
+
289
+ // The secondary map is a regular Hash, and will never shrink on its own.
290
+ // The main object cache is a WeakMap that will automatically remove entries
291
+ // when the target object is no longer reachable, but unless we manually
292
+ // remove the corresponding entries from the secondary map, it will grow
293
+ // without bound.
294
+ //
295
+ // To avoid this unbounded growth we periodically remove entries from the
296
+ // secondary map that are no longer present in the WeakMap. The logic of
297
+ // how often to perform this GC is an artbirary tuning parameter that
298
+ // represents a straightforward CPU/memory tradeoff.
299
+ //
300
+ // Requires: secondary_map_mutex is held.
301
+ static void SecondaryMap_MaybeGC() {
302
+ PBRUBY_ASSERT(rb_mutex_locked_p(secondary_map_mutex) == Qtrue);
303
+ size_t weak_len = NUM2ULL(rb_funcall(weak_obj_cache, length, 0));
304
+ size_t secondary_len = RHASH_SIZE(secondary_map);
305
+ if (secondary_len < weak_len) {
306
+ // Logically this case should not be possible: a valid entry cannot exist in
307
+ // the weak table unless there is a corresponding entry in the secondary
308
+ // table. It should *always* be the case that secondary_len >= weak_len.
309
+ //
310
+ // However ObjectSpace::WeakMap#length (and therefore weak_len) is
311
+ // unreliable: it overreports its true length by including non-live objects.
312
+ // However these non-live objects are not yielded in iteration, so we may
313
+ // have previously deleted them from the secondary map in a previous
314
+ // invocation of SecondaryMap_MaybeGC().
315
+ //
316
+ // In this case, we can't measure any waste, so we just return.
317
+ return;
318
+ }
319
+ size_t waste = secondary_len - weak_len;
320
+ // GC if we could remove at least 2000 entries or 20% of the table size
321
+ // (whichever is greater). Since the cost of the GC pass is O(N), we
322
+ // want to make sure that we condition this on overall table size, to
323
+ // avoid O(N^2) CPU costs.
324
+ size_t threshold = PBRUBY_MAX(secondary_len * 0.2, 2000);
325
+ if (waste > threshold) {
326
+ rb_funcall(gc_secondary_map_lambda, rb_intern("call"), 2,
327
+ secondary_map, weak_obj_cache);
328
+ }
329
+ }
330
+
331
+ // Requires: secondary_map_mutex is held by this thread iff create == true.
332
+ static VALUE SecondaryMap_Get(VALUE key, bool create) {
333
+ PBRUBY_ASSERT(!create || rb_mutex_locked_p(secondary_map_mutex) == Qtrue);
334
+ VALUE ret = rb_hash_lookup(secondary_map, key);
335
+ if (ret == Qnil && create) {
336
+ SecondaryMap_MaybeGC();
337
+ ret = rb_class_new_instance(0, NULL, rb_cObject);
338
+ rb_hash_aset(secondary_map, key, ret);
339
+ }
340
+ return ret;
341
+ }
342
+
343
+ #endif
344
+
345
+ // Requires: secondary_map_mutex is held by this thread iff create == true.
346
+ static VALUE ObjectCache_GetKey(const void* key, bool create) {
347
+ VALUE key_val = (VALUE)key;
348
+ PBRUBY_ASSERT((key_val & 3) == 0);
349
+ VALUE ret = LL2NUM(key_val >> 2);
350
+ #if USE_SECONDARY_MAP
351
+ ret = SecondaryMap_Get(ret, create);
352
+ #endif
353
+ return ret;
354
+ }
355
+
356
+ // Public ObjectCache API.
357
+
358
+ VALUE weak_obj_cache = Qnil;
359
+ ID item_get;
360
+ ID item_set;
361
+
362
+ static void ObjectCache_Init() {
363
+ rb_gc_register_address(&weak_obj_cache);
364
+ VALUE klass = rb_eval_string("ObjectSpace::WeakMap");
365
+ weak_obj_cache = rb_class_new_instance(0, NULL, klass);
366
+ item_get = rb_intern("[]");
367
+ item_set = rb_intern("[]=");
368
+ #if USE_SECONDARY_MAP
369
+ SecondaryMap_Init();
370
+ #endif
371
+ }
372
+
373
+ void ObjectCache_Add(const void* key, VALUE val) {
374
+ PBRUBY_ASSERT(ObjectCache_Get(key) == Qnil);
375
+ #if USE_SECONDARY_MAP
376
+ rb_mutex_lock(secondary_map_mutex);
377
+ #endif
378
+ VALUE key_rb = ObjectCache_GetKey(key, true);
379
+ rb_funcall(weak_obj_cache, item_set, 2, key_rb, val);
380
+ #if USE_SECONDARY_MAP
381
+ rb_mutex_unlock(secondary_map_mutex);
382
+ #endif
383
+ PBRUBY_ASSERT(ObjectCache_Get(key) == val);
384
+ }
385
+
386
+ // Returns the cached object for this key, if any. Otherwise returns Qnil.
387
+ VALUE ObjectCache_Get(const void* key) {
388
+ VALUE key_rb = ObjectCache_GetKey(key, false);
389
+ return rb_funcall(weak_obj_cache, item_get, 1, key_rb);
390
+ }
391
+
392
+ /*
393
+ * call-seq:
394
+ * Google::Protobuf.discard_unknown(msg)
395
+ *
396
+ * Discard unknown fields in the given message object and recursively discard
397
+ * unknown fields in submessages.
398
+ */
399
+ static VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
400
+ const upb_msgdef *m;
401
+ upb_msg *msg = Message_GetMutable(msg_rb, &m);
402
+ if (!upb_msg_discardunknown(msg, m, 128)) {
403
+ rb_raise(rb_eRuntimeError, "Messages nested too deeply.");
404
+ }
405
+
406
+ return Qnil;
407
+ }
408
+
409
+ /*
410
+ * call-seq:
411
+ * Google::Protobuf.deep_copy(obj) => copy_of_obj
412
+ *
413
+ * Performs a deep copy of a RepeatedField instance, a Map instance, or a
414
+ * message object, recursively copying its members.
415
+ */
416
+ VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj) {
417
+ VALUE klass = CLASS_OF(obj);
418
+ if (klass == cRepeatedField) {
419
+ return RepeatedField_deep_copy(obj);
420
+ } else if (klass == cMap) {
421
+ return Map_deep_copy(obj);
422
+ } else {
423
+ VALUE new_arena_rb = Arena_new();
424
+ upb_arena *new_arena = Arena_get(new_arena_rb);
425
+ const upb_msgdef *m;
426
+ const upb_msg *msg = Message_Get(obj, &m);
427
+ upb_msg* new_msg = Message_deep_copy(msg, m, new_arena);
428
+ return Message_GetRubyWrapper(new_msg, m, new_arena_rb);
429
+ }
430
+ }
79
431
 
80
432
  // -----------------------------------------------------------------------------
81
433
  // Initialization/entry point.
@@ -83,39 +435,26 @@ ID descriptor_instancevar_interned;
83
435
 
84
436
  // This must be named "Init_protobuf_c" because the Ruby module is named
85
437
  // "protobuf_c" -- the VM looks for this symbol in our .so.
438
+ __attribute__ ((visibility ("default")))
86
439
  void Init_protobuf_c() {
440
+ ObjectCache_Init();
441
+
87
442
  VALUE google = rb_define_module("Google");
88
443
  VALUE protobuf = rb_define_module_under(google, "Protobuf");
89
- VALUE internal = rb_define_module_under(protobuf, "Internal");
90
-
91
- descriptor_instancevar_interned = rb_intern(kDescriptorInstanceVar);
92
- DescriptorPool_register(protobuf);
93
- Descriptor_register(protobuf);
94
- FileDescriptor_register(protobuf);
95
- FieldDescriptor_register(protobuf);
96
- OneofDescriptor_register(protobuf);
97
- EnumDescriptor_register(protobuf);
98
- MessageBuilderContext_register(internal);
99
- OneofBuilderContext_register(internal);
100
- EnumBuilderContext_register(internal);
101
- FileBuilderContext_register(internal);
102
- Builder_register(internal);
444
+
445
+ Arena_register(protobuf);
446
+ Defs_register(protobuf);
103
447
  RepeatedField_register(protobuf);
104
448
  Map_register(protobuf);
449
+ Message_register(protobuf);
105
450
 
106
- cError = rb_const_get(protobuf, rb_intern("Error"));
107
451
  cParseError = rb_const_get(protobuf, rb_intern("ParseError"));
452
+ rb_gc_register_mark_object(cParseError);
108
453
  cTypeError = rb_const_get(protobuf, rb_intern("TypeError"));
454
+ rb_gc_register_mark_object(cTypeError);
109
455
 
110
456
  rb_define_singleton_method(protobuf, "discard_unknown",
111
457
  Google_Protobuf_discard_unknown, 1);
112
458
  rb_define_singleton_method(protobuf, "deep_copy",
113
459
  Google_Protobuf_deep_copy, 1);
114
-
115
- kRubyStringUtf8Encoding = rb_utf8_encoding();
116
- kRubyStringASCIIEncoding = rb_usascii_encoding();
117
- kRubyString8bitEncoding = rb_ascii8bit_encoding();
118
-
119
- rb_gc_register_address(&upb_def_to_ruby_obj_map);
120
- upb_def_to_ruby_obj_map = rb_hash_new();
121
460
  }